A free, open source, and extensible speech-to-text application that works completely offline.
add language detection (#2331)
CJ Pais126bed73cb4c
diff --git a/.nix/bun-lock-hash b/.nix/bun-lock-hashindex e866262e..5d502c16 100644--- a/.nix/bun-lock-hash+++ b/.nix/bun-lock-hash@@ -1 +1 @@-73d55331f6785a4e7d0e1d63f13ba7ba34b9ae38c57b83586aae6c67ff5ff32f+44fe61747609b3e88b300f02a8c45ae816d20a4c67575c9cb5fed497495ef405diff --git a/.nix/bun.nix b/.nix/bun.nixindex 17dfbe9f..fa7b4129 100644--- a/.nix/bun.nix+++ b/.nix/bun.nix@@ -301,9 +301,9 @@url = "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz";hash = "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==";};- "@handy-computer/[email protected]" = fetchurl {- url = "https://registry.npmjs.org/@handy-computer/models/-/models-0.2.2.tgz";- hash = "sha512-FklK9es5q34VMGufo9Yl9ic4ie9OPn2xYI4CciTAbNZh850WSFCPmUeu+UUiIdAHldsz7qlDYWMtyj7u6It03A==";+ "@handy-computer/[email protected]" = fetchurl {+ url = "https://registry.npmjs.org/@handy-computer/models/-/models-0.2.3.tgz";+ hash = "sha512-EcyPojMY8hG5adDZGR/2h/m9jniqAnSND00gmiAErRLB1BQqMD9jrJaqsfoYF/UfPC8ocKZFUNSkTegoYqjF5w==";};"@humanfs/[email protected]" = fetchurl {url = "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz";diff --git a/bun.lock b/bun.lockindex d619992a..bfcdebf9 100644--- a/bun.lock+++ b/bun.lock@@ -5,7 +5,7 @@"": {"name": "handy-app","dependencies": {- "@handy-computer/models": "0.2.2",+ "@handy-computer/models": "0.2.3","@tailwindcss/vite": "^4.1.16","@tauri-apps/api": "^2.11.0","@tauri-apps/plugin-autostart": "~2.5.1",@@ -191,7 +191,7 @@"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="],- "@handy-computer/models": ["@handy-computer/[email protected]", "", {}, "sha512-FklK9es5q34VMGufo9Yl9ic4ie9OPn2xYI4CciTAbNZh850WSFCPmUeu+UUiIdAHldsz7qlDYWMtyj7u6It03A=="],+ "@handy-computer/models": ["@handy-computer/[email protected]", "", {}, "sha512-EcyPojMY8hG5adDZGR/2h/m9jniqAnSND00gmiAErRLB1BQqMD9jrJaqsfoYF/UfPC8ocKZFUNSkTegoYqjF5w=="],"@humanfs/core": ["@humanfs/[email protected]", "", {}, "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA=="],diff --git a/package.json b/package.jsonindex 3d89187a..ce1c671a 100644--- a/package.json+++ b/package.json@@ -26,7 +26,7 @@"postinstall": "bun scripts/check-nix-deps.ts"},"dependencies": {- "@handy-computer/models": "0.2.2",+ "@handy-computer/models": "0.2.3","@tailwindcss/vite": "^4.1.16","@tauri-apps/api": "^2.11.0","@tauri-apps/plugin-autostart": "~2.5.1",diff --git a/scripts/mirror_models.py b/scripts/mirror_models.pyindex 4bbbe935..b53bf4d3 100644--- a/scripts/mirror_models.py+++ b/scripts/mirror_models.py@@ -80,11 +80,15 @@ def make_s3():def offered_models(catalog):- """Mirror every root-level ASR default Handy can download.+ """Mirror every root-level ASR default Handy can download, plus the+ language detector the catalog names (catalog::LANGUAGE_DETECTOR), which+ Handy fetches alongside models without their own language detection.Matches catalog::CatalogModel::is_offered (the models directory is flat)."""+ detector = catalog.get("languageDetector")for m in catalog["models"]:default = m["files"].get(m["quant"])- if m["role"] == "asr" and default and "/" not in default["filename"]:+ wanted = m["role"] == "asr" or (m["role"] == "langid" and m["id"] == detector)+ if wanted and default and "/" not in default["filename"]:yield mdiff --git a/src-tauri/src/actions.rs b/src-tauri/src/actions.rsindex 05137caf..c4d6e174 100644--- a/src-tauri/src/actions.rs+++ b/src-tauri/src/actions.rs@@ -7,7 +7,7 @@ use crate::managers::history::HistoryManager;use crate::managers::model::ModelManager;use crate::managers::transcription::policy::{live_decode, LiveDecode, ModelTraits};use crate::managers::transcription::StreamWorkKind;-use crate::managers::transcription::TranscriptionManager;+use crate::managers::transcription::{Transcription, TranscriptionManager};use crate::settings::{get_settings, AppSettings, OverlayStyle, APPLE_INTELLIGENCE_PROVIDER_ID};use crate::shortcut;use crate::tray::{set_tray_state, TrayIconState};@@ -745,7 +745,10 @@ impl ShortcutAction for TranscribeAction {}match transcription_result {- Ok(transcription) => {+ Ok(Transcription {+ text: transcription,+ language,+ }) => {debug!("Transcription completed in {:?}: '{}'",transcription_time.elapsed(),@@ -786,6 +789,7 @@ impl ShortcutAction for TranscribeAction {post_process,processed.post_processed_text.clone(),processed.post_process_prompt.clone(),+ language,) {error!("Failed to save history entry: {}", err);}@@ -886,6 +890,7 @@ impl ShortcutAction for TranscribeAction {post_process,None,None,+ None,) {error!("Failed to save failed history entry: {}", save_err);}diff --git a/src-tauri/src/audio_toolkit/cpu_engine.rs b/src-tauri/src/audio_toolkit/cpu_engine.rsnew file mode 100644index 00000000..540b669c--- /dev/null+++ b/src-tauri/src/audio_toolkit/cpu_engine.rs@@ -0,0 +1,24 @@+//! transcribe.cpp inside Handy's own process, for the small CPU-only models:+//! Silero VAD and the spoken-language detector. Everything that can touch a+//! GPU runs in the engine worker instead (`engine_supervisor`).++use anyhow::Result;+use std::path::Path;+use std::sync::OnceLock;++use transcribe_cpp::BackendMask;++/// Register transcribe.cpp's CPU backends once per process. The allowed mask+/// is fixed at first registration, so it must never include a GPU here.+pub(crate) fn init_cpu_backends() -> Result<()> {+ static INIT: OnceLock<Result<(), String>> = OnceLock::new();+ INIT.get_or_init(|| {+ // Route native/ggml diagnostics into Handy's log; must precede any+ // native call.+ transcribe_cpp::init_logging();+ transcribe_cpp::init_backends_with(None::<&Path>, BackendMask::CPU)+ .map_err(|e| e.to_string())+ })+ .clone()+ .map_err(|e| anyhow::anyhow!("Failed to initialize transcribe.cpp CPU backend: {e}"))+}diff --git a/src-tauri/src/audio_toolkit/mod.rs b/src-tauri/src/audio_toolkit/mod.rsindex 8fc1a7c4..0dc81f9c 100644--- a/src-tauri/src/audio_toolkit/mod.rs+++ b/src-tauri/src/audio_toolkit/mod.rs@@ -1,6 +1,7 @@pub mod audio;pub mod chunking;pub mod constants;+pub(crate) mod cpu_engine;pub mod lang_id;pub mod text;pub mod utils;diff --git a/src-tauri/src/audio_toolkit/text.rs b/src-tauri/src/audio_toolkit/text.rsindex 5bbe4943..e9dba8c7 100644--- a/src-tauri/src/audio_toolkit/text.rs+++ b/src-tauri/src/audio_toolkit/text.rs@@ -277,6 +277,8 @@ pub enum OutputLanguageEvidence {/// The transcription model itself identified the language (audio-based/// LID, e.g. Whisper in auto mode).ModelDetected(String),+ /// Handy's spoken-language detector picked it, and the model ran with it.+ Detected(String),/// Detected from the transcribed text with high confidence, constrained to/// the model's supported languages. Weakest accepted evidence.TextDetected(String),@@ -290,6 +292,7 @@ impl OutputLanguageEvidence {Self::UserSelected(language)| Self::ModelConstrained(language)| Self::ModelDetected(language)+ | Self::Detected(language)| Self::TextDetected(language) => Some(language),Self::TranslatedToEnglish => Some("en"),Self::Unknown => None,diff --git a/src-tauri/src/audio_toolkit/vad/silero.rs b/src-tauri/src/audio_toolkit/vad/silero.rsindex e349726f..4b731596 100644--- a/src-tauri/src/audio_toolkit/vad/silero.rs+++ b/src-tauri/src/audio_toolkit/vad/silero.rs@@ -1,11 +1,12 @@use anyhow::Result;use std::path::Path;-use std::sync::{Mutex, OnceLock, PoisonError};+use std::sync::{Mutex, PoisonError};-use transcribe_cpp::{Backend, BackendMask, Model, ModelOptions, VadSession, VadSessionOptions};+use transcribe_cpp::{Backend, Model, ModelOptions, VadSession, VadSessionOptions};use super::{check_whole_frames, SpeechScorer, VadFrame, VoiceActivityDetector};use crate::audio_toolkit::constants;+use crate::audio_toolkit::cpu_engine::init_cpu_backends;pub struct SileroVad {// `VadSession` is Send but not Sync; the trait requires both. Only ever@@ -15,21 +16,6 @@ pub struct SileroVad {threshold: f32,}-/// Register transcribe.cpp's CPU backends once per process. The allowed mask-/// is fixed at first registration, so it must never include a GPU here.-fn init_cpu_backends() -> Result<()> {- static INIT: OnceLock<Result<(), String>> = OnceLock::new();- INIT.get_or_init(|| {- // Route native/ggml diagnostics into Handy's log; must precede any- // native call.- transcribe_cpp::init_logging();- transcribe_cpp::init_backends_with(None::<&Path>, BackendMask::CPU)- .map_err(|e| e.to_string())- })- .clone()- .map_err(|e| anyhow::anyhow!("Failed to initialize transcribe.cpp CPU backend: {e}"))-}-impl SileroVad {pub fn new<P: AsRef<Path>>(model_path: P, threshold: f32) -> Result<Self> {if !(0.0..=1.0).contains(&threshold) {diff --git a/src-tauri/src/catalog/catalog.json b/src-tauri/src/catalog/catalog.jsonindex 88a526ae..41619e81 100644--- a/src-tauri/src/catalog/catalog.json+++ b/src-tauri/src/catalog/catalog.json@@ -1834,7 +1834,7 @@"zh"],"capabilities": {"streaming": false, "translate": false, "languageDetection": false, "timestamps": false},- "quant": "Q8_0",+ "quant": "F16","role": "langid","curated": false,"minEngine": "0.4.0",diff --git a/src-tauri/src/catalog/mod.rs b/src-tauri/src/catalog/mod.rsindex f57e323b..73185646 100644--- a/src-tauri/src/catalog/mod.rs+++ b/src-tauri/src/catalog/mod.rs@@ -60,6 +60,10 @@ struct CatalogRoot {#[cfg_attr(not(test), allow(dead_code))]transcribe_cpp: String,models: Vec<CatalogModel>,+ /// Catalog id of the spoken-language detector for transcription models+ /// without their own language detection.+ #[serde(default)]+ language_detector: Option<String>,/// Benchmark results keyed by catalog id.#[serde(default)]results: HashMap<String, ModelResults>,@@ -337,6 +341,36 @@ pub static CATALOG: Lazy<Vec<ModelDescriptor>> = Lazy::new(|| {.collect()});+/// The spoken-language detector the catalog names (`languageDetector`): the+/// file Handy fetches, at the package's default quant, and the labels it can+/// tell apart.+pub struct LanguageDetectorFile {+ pub repo_id: String,+ pub revision: String,+ pub filename: String,+ pub size_bytes: u64,+ sha256: String,+ /// The detector's own codes (`iw`, `jw`, `tl`, `no` included).+ pub labels: Vec<String>,+}++pub static LANGUAGE_DETECTOR: Lazy<Option<LanguageDetectorFile>> = Lazy::new(|| {+ let id = ROOT.language_detector.as_deref()?;+ let model = ROOT+ .models+ .iter()+ .find(|m| m.id == id && m.role == "langid")?;+ let file = model.default_file()?;+ Some(LanguageDetectorFile {+ repo_id: model.repository.clone(),+ revision: model.revision.clone(),+ filename: file.filename.clone(),+ size_bytes: file.size,+ sha256: file.sha256.clone(),+ labels: model.languages.clone(),+ })+});+/// A mirror copy of a catalog model's file, with the expected content hash for/// end-to-end verification. Mirrors are untrusted bit-pipes: the sha256 here/// (from the catalog compiled into the binary) is the trust anchor.@@ -364,18 +398,47 @@ pub fn mirror_fallbacks(model_id: &str) -> Vec<MirrorFile> {else {return Vec::new();};+ mirror_files(+ &m.repository,+ &m.revision,+ &file.filename,+ &file.sha256,+ file.size,+ )+}++/// Ordered mirror URLs for the language detector's file.+pub fn language_detector_mirrors() -> Vec<MirrorFile> {+ LANGUAGE_DETECTOR.as_ref().map_or_else(Vec::new, |d| {+ mirror_files(+ &d.repo_id,+ &d.revision,+ &d.filename,+ &d.sha256,+ d.size_bytes,+ )+ })+}++fn mirror_files(+ repository: &str,+ revision: &str,+ filename: &str,+ sha256: &str,+ size_bytes: u64,+) -> Vec<MirrorFile> {MIRRORS.iter().map(|base| MirrorFile {url: format!("{}/{}/{}/{}",base.trim_end_matches('/'),- m.repository,- m.revision,- file.filename+ repository,+ revision,+ filename),- sha256: file.sha256.clone(),- size_bytes: file.size,+ sha256: sha256.to_string(),+ size_bytes,}).collect()}@@ -438,6 +501,16 @@ mod tests {assert_eq!(before, ids.len(), "catalog descriptor ids must be unique");}+ #[test]+ fn names_a_language_detector() {+ let detector = LANGUAGE_DETECTOR+ .as_ref()+ .expect("catalog names a language detector");+ assert!(detector.filename.ends_with(".gguf"));+ assert!(detector.labels.iter().any(|l| l == "en"));+ assert!(detector.labels.iter().any(|l| l == "iw"));+ }+#[test]fn only_transcription_models_are_loaded() {// Language ID (ecapa_tdnn), VAD (silero_vad) and diarizationdiff --git a/src-tauri/src/commands/models.rs b/src-tauri/src/commands/models.rsindex 29dd9214..4387846d 100644--- a/src-tauri/src/commands/models.rs+++ b/src-tauri/src/commands/models.rs@@ -1,4 +1,4 @@-use crate::managers::model::{ModelInfo, ModelManager, RetiredModel};+use crate::managers::model::{ModelInfo, ModelManager, RetiredModel, LANGUAGE_DETECTOR_ID};use crate::managers::transcription::{ModelStateEvent, TranscriptionManager};use crate::settings::{get_settings, write_settings, ModelUnloadTimeout};use log::error;@@ -61,6 +61,36 @@ pub async fn download_model(result}+/// Whether the language detector is on disk.+#[tauri::command]+#[specta::specta]+pub fn is_language_detector_downloaded(model_manager: State<'_, Arc<ModelManager>>) -> bool {+ model_manager.language_detector_path().is_some()+}++/// Download the language detector on its own. Progress, completion,+/// cancellation and failure use the model download events under+/// `LANGUAGE_DETECTOR_ID`.+#[tauri::command]+#[specta::specta]+pub async fn download_language_detector(+ app_handle: AppHandle,+ model_manager: State<'_, Arc<ModelManager>>,+) -> Result<(), String> {+ let result = model_manager+ .download_language_detector()+ .await+ .map_err(|e| e.to_string());+ if let Err(ref error) = result {+ error!("Language detector download failed: {}", error);+ let _ = app_handle.emit(+ "model-download-failed",+ serde_json::json!({ "model_id": LANGUAGE_DETECTOR_ID, "error": error }),+ );+ }+ result+}+#[tauri::command]#[specta::specta]pub fn get_retired_models(model_manager: State<'_, Arc<ModelManager>>) -> Vec<RetiredModel> {diff --git a/src-tauri/src/commands/transcription.rs b/src-tauri/src/commands/transcription.rsindex 64d555cf..2212b07e 100644--- a/src-tauri/src/commands/transcription.rs+++ b/src-tauri/src/commands/transcription.rs@@ -1,3 +1,5 @@+use crate::language_detection::LanguageStatus;+use crate::managers::model::ModelManager;use crate::managers::transcription::TranscriptionManager;use crate::settings::{get_settings, write_settings, ModelUnloadTimeout};use serde::Serialize;@@ -19,6 +21,22 @@ pub fn set_model_unload_timeout(app: AppHandle, timeout: ModelUnloadTimeout) {write_settings(&app, settings);}+/// The language transcription on `model_id` will use, for the picker.+#[tauri::command]+#[specta::specta]+pub fn get_language_status(+ app: AppHandle,+ model_manager: State<Arc<ModelManager>>,+ model_id: String,+) -> LanguageStatus {+ let settings = get_settings(&app);+ crate::language_detection::status_for(+ &settings,+ model_manager.get_model_info(&model_id).as_ref(),+ model_manager.language_detector_path().is_some(),+ )+}+#[tauri::command]#[specta::specta]pub fn get_model_load_status(diff --git a/src-tauri/src/language_detection/detector.rs b/src-tauri/src/language_detection/detector.rsnew file mode 100644index 00000000..fa52c631--- /dev/null+++ b/src-tauri/src/language_detection/detector.rs@@ -0,0 +1,114 @@+//! The spoken-language detector model, loaded in Handy's process on CPU (like+//! Silero VAD) when first needed and unloaded with the transcription model.++use anyhow::Result;+use log::{debug, info};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Mutex, PoisonError, TryLockError};+use std::time::Instant;++use transcribe_cpp::{Backend, LangIdOptions, LangIdSession, Model, ModelOptions};++use super::Identified;+use crate::audio_toolkit::cpu_engine::init_cpu_backends;++#[derive(Default)]+pub struct LanguageDetector {+ // `LangIdSession` is Send but not Sync.+ loaded: Mutex<Option<Loaded>>,+ /// An unload is pending: it found a run holding the model, so that run+ /// drops it once it lets go of the lock.+ unload_requested: AtomicBool,+}++struct Loaded {+ path: PathBuf,+ session: LangIdSession,+}++impl Loaded {+ fn open(path: &Path) -> Result<Self> {+ init_cpu_backends()?;+ let started = Instant::now();+ let model = Model::load_with(+ path,+ &ModelOptions {+ backend: Backend::Cpu,+ device: None,+ },+ )+ .map_err(|e| anyhow::anyhow!("Failed to load the language detector: {e}"))?;+ // The session keeps the native model alive on its own.+ let session = model+ .langid_session()+ .map_err(|e| anyhow::anyhow!("Model is not a language detector: {e}"))?;+ info!(+ "Loaded the language detector {} in {} ms",+ path.file_name().unwrap_or_default().to_string_lossy(),+ started.elapsed().as_millis()+ );+ Ok(Self {+ path: path.to_path_buf(),+ session,+ })+ }+}++impl LanguageDetector {+ /// Rank `allowed` (the detector's labels) for 16 kHz mono `speech`,+ /// loading the model at `path` first if it isn't loaded.+ pub fn identify(&self, path: &Path, speech: &[f32], allowed: &[String]) -> Result<Identified> {+ let result = self.run(path, speech, allowed);+ // Checked only after the lock is released: an unload that found it+ // held posted its request first, so it can't be missed here.+ if self.unload_requested.load(Ordering::SeqCst) {+ self.unload();+ }+ result+ }++ fn run(&self, path: &Path, speech: &[f32], allowed: &[String]) -> Result<Identified> {+ let mut guard = self.loaded.lock().unwrap_or_else(PoisonError::into_inner);+ if guard.as_ref().is_some_and(|l| l.path != path) {+ *guard = None;+ }+ let loaded = match &mut *guard {+ Some(loaded) => loaded,+ slot @ None => slot.insert(Loaded::open(path)?),+ };+ let started = Instant::now();+ let result = loaded.session.run(+ speech,+ &LangIdOptions {+ allowed: Some(allowed.to_vec()),+ },+ )?;+ Ok(Identified {+ candidates: result+ .candidates+ .into_iter()+ .map(|c| (c.code, c.p))+ .collect(),+ allowed_mass: result.allowed_mass,+ elapsed: started.elapsed(),+ })+ }++ /// Never waits: an unload that lands mid-run is done by the run when it+ /// ends, so a model unload never blocks its caller (e.g. the event loop).+ pub fn unload(&self) {+ // Posted before trying the lock, so a run that releases it in between+ // still sees the request.+ self.unload_requested.store(true, Ordering::SeqCst);+ let mut loaded = match self.loaded.try_lock() {+ Ok(loaded) => loaded,+ Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),+ Err(TryLockError::WouldBlock) => return,+ };+ self.unload_requested.store(false, Ordering::SeqCst);+ if loaded.take().is_some() {+ debug!("Language detector unloaded");+ }+ }+}diff --git a/src-tauri/src/language_detection/mod.rs b/src-tauri/src/language_detection/mod.rsnew file mode 100644index 00000000..72087523--- /dev/null+++ b/src-tauri/src/language_detection/mod.rs@@ -0,0 +1,308 @@+//! Spoken-language detection for Auto: Handy's detector picks between the+//! person's languages for models that can't detect the language themselves+//! (and, in Always mode, for those that can). It never blocks a transcription.++mod detector;+pub mod policy;+pub mod speech;++use log::{info, warn};+use serde::{Deserialize, Serialize};+use specta::Type;+use std::time::Duration;++pub use detector::LanguageDetector;+pub use policy::{DetectFallback, LanguageStatus, Plan};++use crate::managers::model::ModelInfo;+use crate::settings::AppSettings;+use policy::ModelLanguages;++/// The detector's labels, from the catalog.+fn detector_labels() -> &'static [String] {+ crate::catalog::LANGUAGE_DETECTOR+ .as_ref()+ .map(|detector| detector.labels.as_slice())+ .unwrap_or_default()+}++fn model_languages(model: Option<&ModelInfo>, streaming: bool) -> ModelLanguages<'_> {+ ModelLanguages {+ languages: model+ .map(|m| m.supported_languages.as_slice())+ .unwrap_or_default(),+ detects: model.is_some_and(|m| m.supports_language_detection),+ streaming,+ }+}++/// How a transcription on `model` picks its language (`None`: a model the+/// registry doesn't know). Computed fresh each time and never written back+/// to settings, so the persisted intent survives switching models and back.+pub fn plan_for(settings: &AppSettings, model: Option<&ModelInfo>, streaming: bool) -> Plan {+ policy::plan(+ &settings.selected_language,+ &settings.spoken_languages,+ &model_languages(model, streaming),+ settings.language_detection,+ detector_labels(),+ )+}++/// What the language picker shows for `model`.+pub fn status_for(+ settings: &AppSettings,+ model: Option<&ModelInfo>,+ detector_ready: bool,+) -> LanguageStatus {+ policy::status(+ &settings.selected_language,+ &settings.spoken_languages,+ &model_languages(model, model.is_some_and(|m| m.supports_streaming)),+ settings.language_detection,+ detector_labels(),+ detector_ready,+ )+}++/// The detector rejects less speech than this (`InputTooShort`).+const MIN_SPEECH_SAMPLES: usize = 16_000 / 2;++/// A pick less than this many times as likely as the runner-up is logged as+/// uncertain (with two languages: p < 0.6). It is used either way.+const UNSURE_RATIO: f32 = 1.5;++/// How a transcription's language was chosen.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]+#[serde(rename_all = "snake_case")]+pub enum LanguageSource {+ /// The person picked it, or it is the only language of theirs the model+ /// supports.+ Selected,+ /// The model decides: its own detection, or its only language.+ Model,+ /// Handy's detector picked it.+ Detected,+ /// Handy had to pick without detecting (too little speech, detection+ /// failed or unavailable, or Auto can't work for these languages).+ Fallback,+}++impl LanguageSource {+ /// How it is stored in history.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Selected => "selected",+ Self::Model => "model",+ Self::Detected => "detected",+ Self::Fallback => "fallback",+ }+ }++ /// Reads [`as_str`](Self::as_str); `None` for anything else (a newer+ /// Handy's value).+ pub fn parse(value: &str) -> Option<Self> {+ [Self::Selected, Self::Model, Self::Detected, Self::Fallback]+ .into_iter()+ .find(|source| source.as_str() == value)+ }+}++/// The language one transcription runs in.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LanguageDecision {+ /// The model's code, or `None` for the model's own detection.+ pub language: Option<String>,+ pub source: LanguageSource,+}++impl LanguageDecision {+ /// As a language intent: the code, or `"auto"`.+ pub fn intent(&self) -> &str {+ self.language.as_deref().unwrap_or("auto")+ }+}++/// A detector run: `(label, p)` ranked by `p`, over the allowed labels.+pub struct Identified {+ pub candidates: Vec<(String, f32)>,+ pub allowed_mass: f32,+ pub elapsed: Duration,+}++pub enum IdentifyError {+ /// The detector isn't on disk.+ Missing,+ Failed(anyhow::Error),+}++impl Plan {+ /// Whether [`decide`](Self::decide) needs the audio's speech.+ pub fn detects(&self) -> bool {+ matches!(self, Plan::Detect { .. })+ }++ /// The language, given the transcription's `speech` (VAD'd, at most the+ /// detection window), or `None` if the detector isn't on disk. `identify`+ /// runs the detector over `allowed`.+ pub fn decide(+ &self,+ speech: Option<&[f32]>,+ identify: impl FnOnce(&[f32], &[String]) -> Result<Identified, IdentifyError>,+ ) -> LanguageDecision {+ let (languages, allowed, fallback) = match self {+ Plan::Fixed { language, source } => {+ return LanguageDecision {+ language: Some(language.clone()),+ source: *source,+ }+ }+ Plan::Native => {+ return LanguageDecision {+ language: None,+ source: LanguageSource::Model,+ }+ }+ Plan::Detect {+ languages,+ allowed,+ fallback,+ } => (languages, allowed, *fallback),+ };++ let fallback_decision = LanguageDecision {+ language: match fallback {+ DetectFallback::FirstLanguage => languages.first().cloned(),+ DetectFallback::Native => None,+ },+ source: LanguageSource::Fallback,+ };+ let transcribing_as = match &fallback_decision.language {+ Some(language) => format!("transcribing as {language}, the first preferred language"),+ None => "using the model's own detection".to_string(),+ };+ let Some(speech) = speech else {+ info!("Language detection: the detector isn't downloaded; {transcribing_as}");+ return fallback_decision;+ };+ let seconds = speech.len() as f32 / 16_000.0;++ if speech.len() < MIN_SPEECH_SAMPLES {+ info!(+ "Language detection: skipped, {seconds:.2} s of speech is under the 0.5 s minimum; {transcribing_as}"+ );+ return fallback_decision;+ }+ let identified = match identify(speech, allowed) {+ Ok(identified) => identified,+ Err(IdentifyError::Missing) => {+ info!("Language detection: the detector isn't downloaded; {transcribing_as}");+ return fallback_decision;+ }+ Err(IdentifyError::Failed(e)) => {+ warn!("Language detection failed: {e:#}; {transcribing_as}");+ return fallback_decision;+ }+ };++ let top = identified.candidates.first();+ let language = top+ .filter(|(_, p)| p.is_finite())+ .and_then(|(label, _)| allowed.iter().position(|a| a == label))+ .and_then(|i| languages.get(i))+ .cloned();+ let scores = identified+ .candidates+ .iter()+ .map(|(label, p)| format!("{label} {:.1}%", p * 100.0))+ .collect::<Vec<_>>()+ .join(", ");+ let uncertain = match (top, identified.candidates.get(1)) {+ (Some((_, first)), Some((_, second))) if *first < UNSURE_RATIO * second => {+ ", uncertain"+ }+ _ => "",+ };+ info!(+ "Language detection: {} ({scores}; {seconds:.2} s of speech, allowed mass {:.1}%{uncertain}, {} ms)",+ language.as_deref().unwrap_or("none"),+ identified.allowed_mass * 100.0,+ identified.elapsed.as_millis()+ );+ match language {+ Some(language) => LanguageDecision {+ language: Some(language),+ source: LanguageSource::Detected,+ },+ None => {+ warn!("Language detection returned no usable language; {transcribing_as}");+ fallback_decision+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn codes(list: &[&str]) -> Vec<String> {+ list.iter().map(|c| c.to_string()).collect()+ }++ fn detect(fallback: DetectFallback) -> Plan {+ Plan::Detect {+ languages: codes(&["he", "en"]),+ allowed: codes(&["iw", "en"]),+ fallback,+ }+ }++ fn ranked(candidates: &[(&str, f32)]) -> Result<Identified, IdentifyError> {+ Ok(Identified {+ candidates: candidates+ .iter()+ .map(|(label, p)| (label.to_string(), *p))+ .collect(),+ allowed_mass: 0.9,+ elapsed: Duration::ZERO,+ })+ }++ static SPEECH: [f32; 16_000] = [0.1; 16_000];++ #[test]+ fn detects_in_the_models_own_code() {+ let decision = detect(DetectFallback::FirstLanguage).decide(Some(&SPEECH), |_, allowed| {+ assert_eq!(allowed, codes(&["iw", "en"]));+ ranked(&[("iw", 0.9), ("en", 0.1)])+ });+ assert_eq!(decision.language.as_deref(), Some("he"));+ assert_eq!(decision.source, LanguageSource::Detected);+ }++ #[test]+ fn falls_back_when_detection_cant_decide() {+ let first = detect(DetectFallback::FirstLanguage);+ let fallback = |language: Option<&str>| LanguageDecision {+ language: language.map(String::from),+ source: LanguageSource::Fallback,+ };+ let short = &SPEECH[..MIN_SPEECH_SAMPLES - 1];+ assert_eq!(+ first.decide(Some(short), |_, _| panic!("too little speech to run")),+ fallback(Some("he"))+ );+ assert_eq!(+ first.decide(None, |_, _| panic!("no detector to run")),+ fallback(Some("he"))+ );+ let missing = first.decide(Some(&SPEECH), |_, _| Err(IdentifyError::Missing));+ assert_eq!(missing, fallback(Some("he")));+ // Always mode falls back to the model's own detection.+ let failed = detect(DetectFallback::Native).decide(Some(&SPEECH), |_, _| {+ Err(IdentifyError::Failed(anyhow::anyhow!("boom")))+ });+ assert_eq!(failed, fallback(None));+ }+}diff --git a/src-tauri/src/language_detection/policy.rs b/src-tauri/src/language_detection/policy.rsnew file mode 100644index 00000000..60225d8d--- /dev/null+++ b/src-tauri/src/language_detection/policy.rs@@ -0,0 +1,426 @@+//! Which language a transcription runs in. Ported from `autoLanguagePolicy`+//! in `@handy-computer/models`, plus Handy's single-language and Always rules.++use serde::Serialize;+use specta::Type;++use crate::managers::model::{canonical_language_code, effective_language, supported_code};+use crate::settings::LanguageDetectionMode;++use super::LanguageSource;++/// What a model does with languages, from its catalog or probed capabilities.+pub struct ModelLanguages<'a> {+ /// The model's own codes; empty when language-agnostic or unknown.+ pub languages: &'a [String],+ /// The model detects the language itself.+ pub detects: bool,+ pub streaming: bool,+}++/// How a transcription picks its language, decided before any audio.+#[derive(Debug, Clone, PartialEq)]+pub enum Plan {+ /// One language, no detection.+ Fixed {+ language: String,+ source: LanguageSource,+ },+ /// The model's own detection.+ Native,+ /// Handy's detector chooses between `languages` (the model's codes, in+ /// preference order); `allowed` holds the detector's label for each.+ Detect {+ languages: Vec<String>,+ allowed: Vec<String>,+ fallback: DetectFallback,+ },+}++/// What a detect plan uses when detection can't decide.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DetectFallback {+ /// The first preferred language.+ FirstLanguage,+ /// The model's own detection.+ Native,+}++/// How Auto works for a model and the languages the person speaks.+#[derive(Debug, Clone, PartialEq)]+pub enum AutoLanguage {+ /// The model detects the language itself.+ Native,+ /// The model has one language, or one of theirs fits it.+ Single(String),+ /// The detector chooses between these.+ Detect {+ languages: Vec<String>,+ allowed: Vec<String>,+ },+ /// The detector can't identify `undetectable`, which the model supports.+ /// `compatible` is every spoken language the model supports.+ Undetectable {+ compatible: Vec<String>,+ undetectable: Vec<String>,+ },+ /// None of the spoken languages fit the model.+ NoMatch,+}++/// The detector's label for `language` (`he` → `iw`), if it has one.+pub fn detector_label(labels: &[String], language: &str) -> Option<String> {+ let identity = canonical_language_code(&language.to_ascii_lowercase()).to_string();+ labels+ .iter()+ .find(|label| canonical_language_code(&label.to_ascii_lowercase()) == identity)+ .cloned()+}++/// Spoken languages this model supports, as its own codes, in preference+/// order, one per language.+fn compatible_preferences(languages: &[String], preferred: &[String]) -> Vec<String> {+ let mut compatible: Vec<String> = Vec::new();+ for preference in preferred {+ if let Some(code) = supported_code(preference, languages) {+ let identity = canonical_language_code(code);+ if !compatible+ .iter()+ .any(|c| canonical_language_code(c) == identity)+ {+ compatible.push(code.clone());+ }+ }+ }+ compatible+}++/// The model has more than one language.+fn is_multilingual(languages: &[String]) -> bool {+ languages+ .iter()+ .skip(1)+ .any(|l| canonical_language_code(l) != canonical_language_code(&languages[0]))+}++/// Whether Auto on this model needs Handy's detector, whatever the person+/// speaks (`requiresLanguageDetector`).+pub fn requires_language_detector(model: &ModelLanguages) -> bool {+ !model.detects && is_multilingual(model.languages)+}++pub fn auto_language(+ model: &ModelLanguages,+ preferred: &[String],+ labels: &[String],+) -> AutoLanguage {+ if model.detects {+ return AutoLanguage::Native;+ }+ if !is_multilingual(model.languages) {+ return AutoLanguage::Single(effective_language(+ "auto",+ preferred,+ model.languages,+ false,+ ));+ }+ let compatible = compatible_preferences(model.languages, preferred);+ let allowed: Vec<Option<String>> = compatible+ .iter()+ .map(|language| detector_label(labels, language))+ .collect();+ match compatible.len() {+ 0 => AutoLanguage::NoMatch,+ 1 => AutoLanguage::Single(compatible[0].clone()),+ _ if allowed.iter().any(Option::is_none) => AutoLanguage::Undetectable {+ undetectable: compatible+ .iter()+ .zip(&allowed)+ .filter(|(_, label)| label.is_none())+ .map(|(language, _)| language.clone())+ .collect(),+ compatible,+ },+ _ => AutoLanguage::Detect {+ languages: compatible,+ allowed: allowed.into_iter().flatten().collect(),+ },+ }+}++/// The plan for one transcription. `intent` is the persisted selection+/// (`"auto"` or a code); an explicit language the model supports always wins.+pub fn plan(+ intent: &str,+ preferred: &[String],+ model: &ModelLanguages,+ mode: LanguageDetectionMode,+ labels: &[String],+) -> Plan {+ if model.languages.is_empty() {+ // Language-agnostic or unknown: the engine decides, and a concrete+ // intent is passed on to be gated against the loaded model.+ return match intent {+ "auto" => Plan::Native,+ language => Plan::Fixed {+ language: language.to_string(),+ source: LanguageSource::Selected,+ },+ };+ }+ if intent != "auto" {+ if let Some(code) = supported_code(intent, model.languages) {+ return Plan::Fixed {+ language: code.clone(),+ source: LanguageSource::Selected,+ };+ }+ }++ match auto_language(model, preferred, labels) {+ AutoLanguage::Native => {+ if mode == LanguageDetectionMode::Always && !model.streaming {+ let unrestricted = ModelLanguages {+ detects: false,+ ..*model+ };+ match auto_language(&unrestricted, preferred, labels) {+ AutoLanguage::Detect { languages, allowed } => {+ return Plan::Detect {+ languages,+ allowed,+ fallback: DetectFallback::Native,+ };+ }+ // Limited to one language, Auto is that language.+ AutoLanguage::Single(language) => {+ return Plan::Fixed {+ language,+ source: LanguageSource::Selected,+ };+ }+ _ => {}+ }+ }+ Plan::Native+ }+ AutoLanguage::Single(language) => Plan::Fixed {+ source: if is_multilingual(model.languages) {+ LanguageSource::Selected+ } else {+ LanguageSource::Model+ },+ language,+ },+ AutoLanguage::Detect { languages, allowed } => Plan::Detect {+ languages,+ allowed,+ fallback: DetectFallback::FirstLanguage,+ },+ AutoLanguage::Undetectable { compatible, .. } => Plan::Fixed {+ language: compatible[0].clone(),+ source: LanguageSource::Fallback,+ },+ AutoLanguage::NoMatch => Plan::Fixed {+ language: effective_language("auto", preferred, model.languages, false),+ source: LanguageSource::Fallback,+ },+ }+}++/// What the language picker shows: the language a transcription will run in,+/// or Auto when it's decided per transcription. Derived from [`plan`], so it+/// can't disagree with what transcription does.+#[derive(Debug, Clone, PartialEq, Serialize, Type)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum LanguageStatus {+ /// The language they picked.+ Selected { language: String },+ /// Decided per transcription: the model's own detection, or Handy's.+ Auto,+ /// Auto needs Handy's detector, which isn't downloaded; `fallback` (the+ /// first preferred language) is used until it is.+ DetectorMissing { fallback: String },+ /// Auto can't work here; `language` is used instead.+ AutoUnavailable {+ language: String,+ reason: AutoUnavailableReason,+ },+}++#[derive(Debug, Clone, PartialEq, Serialize, Type)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum AutoUnavailableReason {+ /// Only one of their languages (or only one at all) fits the model.+ OneLanguage,+ /// The detector can't identify these spoken languages.+ Undetectable { languages: Vec<String> },+ /// None of their languages fit the model.+ NoMatch,+}++pub fn status(+ intent: &str,+ preferred: &[String],+ model: &ModelLanguages,+ mode: LanguageDetectionMode,+ labels: &[String],+ detector_ready: bool,+) -> LanguageStatus {+ let explicit = intent != "auto"+ && (model.languages.is_empty() || supported_code(intent, model.languages).is_some());+ match plan(intent, preferred, model, mode, labels) {+ Plan::Native => LanguageStatus::Auto,+ Plan::Detect {+ languages,+ fallback: DetectFallback::FirstLanguage,+ ..+ } if !detector_ready => LanguageStatus::DetectorMissing {+ fallback: languages[0].clone(),+ },+ Plan::Detect { .. } => LanguageStatus::Auto,+ Plan::Fixed { language, .. } if explicit => LanguageStatus::Selected { language },+ Plan::Fixed { language, .. } => LanguageStatus::AutoUnavailable {+ reason: match auto_language(model, preferred, labels) {+ AutoLanguage::Undetectable { undetectable, .. } => {+ AutoUnavailableReason::Undetectable {+ languages: undetectable,+ }+ }+ AutoLanguage::NoMatch => AutoUnavailableReason::NoMatch,+ _ => AutoUnavailableReason::OneLanguage,+ },+ language,+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use AutoUnavailableReason::{NoMatch, OneLanguage, Undetectable};+ use DetectFallback::{FirstLanguage, Native};+ use LanguageDetectionMode::{Always, WhenNeeded};+ use LanguageSource::{Fallback, Model, Selected};++ fn codes(list: &str) -> Vec<String> {+ list.split_whitespace().map(String::from).collect()+ }++ const LABELS: &str = "de en es fr iw ja zh";++ fn model(languages: &[String], detects: bool, streaming: bool) -> ModelLanguages<'_> {+ ModelLanguages {+ languages,+ detects,+ streaming,+ }+ }++ fn plan_on(+ model: &ModelLanguages,+ intent: &str,+ spoken: &str,+ mode: LanguageDetectionMode,+ ) -> Plan {+ plan(intent, &codes(spoken), model, mode, &codes(LABELS))+ }++ fn fixed(language: &str, source: LanguageSource) -> Plan {+ Plan::Fixed {+ language: language.into(),+ source,+ }+ }++ fn detect(languages: &str, allowed: &str, fallback: DetectFallback) -> Plan {+ Plan::Detect {+ languages: codes(languages),+ allowed: codes(allowed),+ fallback,+ }+ }++ #[test]+ fn needs_the_detector_only_without_native_multilingual_detection() {+ let (multi, one) = (codes("en de"), codes("en"));+ assert!(requires_language_detector(&model(&multi, false, false)));+ assert!(!requires_language_detector(&model(&multi, true, false)));+ assert!(!requires_language_detector(&model(&one, false, false)));+ }++ #[test]+ fn plans_the_language_without_native_detection() {+ let languages = codes("en he fr yue");+ let canary = model(&languages, false, false);+ // The spoken languages it supports, in order, as the detector's labels.+ let both = detect("he en", "iw en", FirstLanguage);+ assert_eq!(plan_on(&canary, "auto", "he ja en", WhenNeeded), both);+ assert_eq!(+ plan_on(&canary, "auto", "ja fr", WhenNeeded),+ fixed("fr", Selected)+ );+ assert_eq!(+ plan_on(&canary, "auto", "yue en", WhenNeeded),+ fixed("yue", Fallback)+ );+ assert_eq!(+ plan_on(&canary, "auto", "ja", WhenNeeded),+ fixed("en", Fallback)+ );+ assert_eq!(+ plan_on(&canary, "fr", "he en", Always),+ fixed("fr", Selected)+ );++ let english = codes("en");+ let parakeet = model(&english, false, false);+ assert_eq!(+ plan_on(¶keet, "auto", "de en", Always),+ fixed("en", Model)+ );+ }++ #[test]+ fn native_detection_is_kept_unless_always_and_not_streaming() {+ let languages = codes("en de");+ let whisper = model(&languages, true, false);+ let always = detect("en de", "en de", Native);+ assert_eq!(plan_on(&whisper, "auto", "en de", WhenNeeded), Plan::Native);+ assert_eq!(plan_on(&whisper, "auto", "en de", Always), always);+ assert_eq!(plan_on(&whisper, "auto", "en", WhenNeeded), Plan::Native);+ assert_eq!(+ plan_on(&whisper, "auto", "en ja", Always),+ fixed("en", Selected)+ );+ let streaming = model(&languages, true, true);+ assert_eq!(plan_on(&streaming, "auto", "en de", Always), Plan::Native);+ assert_eq!(plan_on(&streaming, "auto", "en", Always), Plan::Native);+ }++ #[test]+ fn status_shows_what_transcription_does() {+ let languages = codes("en de fr yue");+ let canary = model(&languages, false, false);+ let labels = codes(LABELS);+ let auto = |spoken: &str, ready| {+ status("auto", &codes(spoken), &canary, WhenNeeded, &labels, ready)+ };+ let unavailable = |language: &str, reason| LanguageStatus::AutoUnavailable {+ language: language.into(),+ reason,+ };+ let missing = LanguageStatus::DetectorMissing {+ fallback: "de".into(),+ };+ let undetectable = Undetectable {+ languages: codes("yue"),+ };+ assert_eq!(auto("de en", true), LanguageStatus::Auto);+ assert_eq!(auto("de en", false), missing);+ assert_eq!(auto("fr ja", true), unavailable("fr", OneLanguage));+ assert_eq!(auto("yue en", true), unavailable("yue", undetectable));+ assert_eq!(auto("ja", true), unavailable("en", NoMatch));+ }+}diff --git a/src-tauri/src/language_detection/speech.rs b/src-tauri/src/language_detection/speech.rsnew file mode 100644index 00000000..710b4d9d--- /dev/null+++ b/src-tauri/src/language_detection/speech.rs@@ -0,0 +1,61 @@+//! The speech the language detector hears: silence cut out by VAD, so a+//! window of N seconds is N seconds of speech.++use anyhow::Result;++use crate::audio_toolkit::vad::{VadFrame, VoiceActivityDetector};++/// The first `max_samples` of speech in `audio`, as `vad` keeps it.+pub fn speech_head(+ vad: &mut dyn VoiceActivityDetector,+ audio: &[f32],+ max_samples: usize,+) -> Result<Vec<f32>> {+ let mut speech = Vec::with_capacity(max_samples.min(audio.len()));+ for frame in audio.chunks_exact(vad.frame_samples()) {+ if let VadFrame::Speech(kept) = vad.push_frame(frame)? {+ speech.extend_from_slice(kept);+ if speech.len() >= max_samples {+ break;+ }+ }+ }+ speech.truncate(max_samples);+ Ok(speech)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Frames whose first sample is positive are speech.+ struct SignVad;++ impl VoiceActivityDetector for SignVad {+ fn push_frame<'a>(&'a mut self, frame: &'a [f32]) -> Result<VadFrame<'a>> {+ Ok(if frame[0] > 0.0 {+ VadFrame::Speech(frame)+ } else {+ VadFrame::Noise+ })+ }++ fn frame_samples(&self) -> usize {+ 2+ }+ }++ #[test]+ fn keeps_only_speech_up_to_the_window() {+ let audio = [0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 3.0, 4.0, 5.0, 6.0];+ assert_eq!(+ speech_head(&mut SignVad, &audio, 3).unwrap(),+ vec![1.0, 2.0, 3.0]+ );+ assert_eq!(+ speech_head(&mut SignVad, &audio, 100).unwrap(),+ vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]+ );+ assert!(speech_head(&mut SignVad, &[0.0; 6], 4).unwrap().is_empty());+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 7723ac61..480fdc22 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -12,6 +12,7 @@ mod commands;pub mod engine_supervisor;mod helpers;mod input;+mod language_detection;mod llm_client;mod managers;mod memory;@@ -673,6 +674,8 @@ pub fn run(cli_args: CliArgs) {shortcut::change_debug_mode_setting,shortcut::change_word_correction_threshold_setting,shortcut::change_extra_recording_buffer_setting,+ shortcut::change_language_detection_setting,+ shortcut::change_language_detection_window_setting,shortcut::change_paste_delay_ms_setting,shortcut::change_paste_delay_after_ms_setting,shortcut::change_reliable_paste_setting,@@ -740,6 +743,8 @@ pub fn run(cli_args: CliArgs) {commands::models::get_available_models,commands::models::get_model_info,commands::models::download_model,+ commands::models::download_language_detector,+ commands::models::is_language_detector_downloaded,commands::models::delete_model,commands::models::get_retired_models,commands::models::delete_retired_model,@@ -768,6 +773,7 @@ pub fn run(cli_args: CliArgs) {commands::audio::set_selected_channel,commands::transcription::set_model_unload_timeout,commands::transcription::get_model_load_status,+ commands::transcription::get_language_status,commands::transcription::unload_model_manually,commands::history::get_history_entries,commands::history::toggle_history_entry_saved,diff --git a/src-tauri/src/managers/audio.rs b/src-tauri/src/managers/audio.rsindex bd8668cc..6137a006 100644--- a/src-tauri/src/managers/audio.rs+++ b/src-tauri/src/managers/audio.rs@@ -349,27 +349,36 @@ pub fn create_detector(})}-fn create_capture_vad(+/// A detector for `backend` with a recording's smoothing (pre-roll, onset,+/// offline hangover): what keeps speech in a recording, and what cuts the+/// silence out of other audio the same way.+pub fn create_smoothed_detector(backend: VadBackend,app_handle: &tauri::AppHandle,-) -> Result<CaptureVad, anyhow::Error> {+) -> Result<SmoothedVad, anyhow::Error> {let detector: Box<dyn VoiceActivityDetector> = create_detector(backend, app_handle)?;// Earshot uses 16 ms frames while Silero uses 32 ms. Convert the existing// time-based capture profile to each detector's frame size so selecting a// backend does not shorten pre-roll, onset, or post-speech audio.let frame_samples = detector.frame_samples();- let prefill_frames = frames_for_duration_ms(VAD_PREFILL_MS, frame_samples);+ Ok(SmoothedVad::new(+ detector,+ frames_for_duration_ms(VAD_PREFILL_MS, frame_samples),+ frames_for_duration_ms(VAD_OFFLINE_HANGOVER_MS, frame_samples),+ frames_for_duration_ms(VAD_ONSET_MS, frame_samples),+ ))+}++fn create_capture_vad(+ backend: VadBackend,+ app_handle: &tauri::AppHandle,+) -> Result<CaptureVad, anyhow::Error> {+ let smoothed_vad = create_smoothed_detector(backend, app_handle)?;+ let frame_samples = smoothed_vad.frame_samples();let offline_hangover_frames = frames_for_duration_ms(VAD_OFFLINE_HANGOVER_MS, frame_samples);let streaming_hangover_frames =frames_for_duration_ms(VAD_STREAMING_HANGOVER_MS, frame_samples);- let onset_frames = frames_for_duration_ms(VAD_ONSET_MS, frame_samples);- let smoothed_vad = SmoothedVad::new(- detector,- prefill_frames,- offline_hangover_frames,- onset_frames,- );info!("Initialized {:?} VAD backend ({} samples/frame)",diff --git a/src-tauri/src/managers/history.rs b/src-tauri/src/managers/history.rsindex 88a0222d..834f5622 100644--- a/src-tauri/src/managers/history.rs+++ b/src-tauri/src/managers/history.rs@@ -10,6 +10,8 @@ use std::path::PathBuf;use tauri::AppHandle;use tauri_specta::Event;+use crate::language_detection::{LanguageDecision, LanguageSource};+/// Database migrations for transcription history./// Each migration is applied in order. The library tracks which migrations/// have been applied using SQLite's user_version pragma.@@ -33,6 +35,15 @@ static MIGRATIONS: &[M] = &[M::up("ALTER TABLE transcription_history ADD COLUMN post_process_requested BOOLEAN NOT NULL DEFAULT 0;"),];+/// Nullable columns added outside [`MIGRATIONS`]; see+/// [`HistoryManager::apply_migrations`].+const ADDED_COLUMNS: &[&str] = &["source_name", "language", "language_source"];++/// Every column a [`HistoryEntry`] is read from.+const ENTRY_COLUMNS: &str = "id, file_name, timestamp, saved, title, transcription_text, \+ post_processed_text, post_process_prompt, post_process_requested, source_name, language, \+ language_source";+#[derive(Clone, Debug, Serialize, Deserialize, Type)]pub struct PaginatedHistory {pub entries: Vec<HistoryEntry>,@@ -66,6 +77,10 @@ pub struct HistoryEntry {/// The name of the file this entry was transcribed from; `None` for a/// dictation.pub source_name: Option<String>,+ /// The language it was transcribed in, when known.+ pub language: Option<String>,+ /// How that language was chosen; `None` before it was recorded.+ pub language_source: Option<LanguageSource>,}pub struct HistoryManager {@@ -74,6 +89,14 @@ pub struct HistoryManager {db_path: PathBuf,}+/// A transcription's language as its two columns.+fn split_language(language: Option<LanguageDecision>) -> (Option<String>, Option<LanguageSource>) {+ match language {+ Some(decision) => (decision.language, Some(decision.source)),+ None => (None, None),+ }+}+impl HistoryManager {pub fn new(app_handle: &AppHandle) -> Result<Self> {// Create recordings directory in app data dir@@ -150,12 +173,14 @@ impl HistoryManager {// Not a migration: a higher user_version makes released builds refuse// the database, while an extra nullable column is invisible to them.- if !Self::has_column(conn, "source_name")? {- conn.execute(- "ALTER TABLE transcription_history ADD COLUMN source_name TEXT",- [],- )?;- info!("Added the source_name column to transcription history");+ for column in ADDED_COLUMNS {+ if !Self::has_column(conn, column)? {+ conn.execute(+ &format!("ALTER TABLE transcription_history ADD COLUMN {column} TEXT"),+ [],+ )?;+ info!("Added the {column} column to transcription history");+ }}Ok(())@@ -242,6 +267,11 @@ impl HistoryManager {post_process_prompt: row.get("post_process_prompt")?,post_process_requested: row.get("post_process_requested")?,source_name: row.get("source_name")?,+ language: row.get("language")?,+ language_source: row+ .get::<_, Option<String>>("language_source")?+ .as_deref()+ .and_then(LanguageSource::parse),})}@@ -258,7 +288,9 @@ impl HistoryManager {post_process_requested: bool,post_processed_text: Option<String>,post_process_prompt: Option<String>,+ language: Option<LanguageDecision>,) -> Result<HistoryEntry> {+ let (language, language_source) = split_language(language);let entry = self.insert_entry(HistoryEntry {id: 0,file_name,@@ -270,6 +302,8 @@ impl HistoryManager {post_process_prompt,post_process_requested,source_name: None,+ language,+ language_source,})?;self.cleanup_old_entries()?;@@ -292,6 +326,8 @@ impl HistoryManager {post_process_prompt: None,post_process_requested: false,source_name: Some(source_name),+ language: None,+ language_source: None,})}@@ -310,8 +346,10 @@ impl HistoryManager {post_processed_text,post_process_prompt,post_process_requested,- source_name- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",+ source_name,+ language,+ language_source+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",params![&entry.file_name,entry.timestamp,@@ -322,6 +360,8 @@ impl HistoryManager {&entry.post_process_prompt,entry.post_process_requested,&entry.source_name,+ &entry.language,+ entry.language_source.map(LanguageSource::as_str),],)?;entry.id = conn.last_insert_rowid();@@ -347,18 +387,24 @@ impl HistoryManager {transcription_text: String,post_processed_text: Option<String>,post_process_prompt: Option<String>,+ language: Option<LanguageDecision>,) -> Result<HistoryEntry> {+ let (language, language_source) = split_language(language);let conn = self.get_connection()?;let updated = conn.execute("UPDATE transcription_historySET transcription_text = ?1,post_processed_text = ?2,- post_process_prompt = ?3- WHERE id = ?4",+ post_process_prompt = ?3,+ language = ?4,+ language_source = ?5+ WHERE id = ?6",params![transcription_text,post_processed_text,post_process_prompt,+ language,+ language_source.map(LanguageSource::as_str),id],)?;@@ -367,13 +413,11 @@ impl HistoryManager {return Err(anyhow!("History entry {} not found", id));}- let entry = conn- .query_row(- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name- FROM transcription_history WHERE id = ?1",- params![id],- Self::map_history_entry,- )?;+ let entry = conn.query_row(+ &format!("SELECT {ENTRY_COLUMNS} FROM transcription_history WHERE id = ?1"),+ params![id],+ Self::map_history_entry,+ )?;debug!("Updated transcription for history entry {}", id);@@ -521,13 +565,13 @@ impl HistoryManager {let mut entries: Vec<HistoryEntry> = match (cursor, limit) {(Some(cursor_id), Some(lim)) => {let fetch_count = (lim + 1) as i64;- let mut stmt = conn.prepare(- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_historyWHERE id < ?1ORDER BY id DESC- LIMIT ?2",- )?;+ LIMIT ?2"+ ))?;let result = stmt.query_map(params![cursor_id, fetch_count], Self::map_history_entry)?.collect::<std::result::Result<Vec<_>, _>>()?;@@ -535,23 +579,23 @@ impl HistoryManager {}(None, Some(lim)) => {let fetch_count = (lim + 1) as i64;- let mut stmt = conn.prepare(- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_historyORDER BY id DESC- LIMIT ?1",- )?;+ LIMIT ?1"+ ))?;let result = stmt.query_map(params![fetch_count], Self::map_history_entry)?.collect::<std::result::Result<Vec<_>, _>>()?;result}(_, None) => {- let mut stmt = conn.prepare(- "SELECT id, file_name, timestamp, saved, title, transcription_text, post_processed_text, post_process_prompt, post_process_requested, source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_history- ORDER BY id DESC",- )?;+ ORDER BY id DESC"+ ))?;let result = stmt.query_map([], Self::map_history_entry)?.collect::<std::result::Result<Vec<_>, _>>()?;@@ -569,22 +613,12 @@ impl HistoryManager {#[cfg(test)]fn get_latest_entry_with_conn(conn: &Connection) -> Result<Option<HistoryEntry>> {- let mut stmt = conn.prepare(- "SELECT- id,- file_name,- timestamp,- saved,- title,- transcription_text,- post_processed_text,- post_process_prompt,- post_process_requested,- source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_historyORDER BY timestamp DESC- LIMIT 1",- )?;+ LIMIT 1"+ ))?;let entry = stmt.query_row([], Self::map_history_entry).optional()?;Ok(entry)@@ -598,23 +632,13 @@ impl HistoryManager {}fn get_latest_completed_entry_with_conn(conn: &Connection) -> Result<Option<HistoryEntry>> {- let mut stmt = conn.prepare(- "SELECT- id,- file_name,- timestamp,- saved,- title,- transcription_text,- post_processed_text,- post_process_prompt,- post_process_requested,- source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_historyWHERE transcription_text != '' AND source_name IS NULLORDER BY timestamp DESC- LIMIT 1",- )?;+ LIMIT 1"+ ))?;let entry = stmt.query_row([], Self::map_history_entry).optional()?;Ok(entry)@@ -653,21 +677,11 @@ impl HistoryManager {pub async fn get_entry_by_id(&self, id: i64) -> Result<Option<HistoryEntry>> {let conn = self.get_connection()?;- let mut stmt = conn.prepare(- "SELECT- id,- file_name,- timestamp,- saved,- title,- transcription_text,- post_processed_text,- post_process_prompt,- post_process_requested,- source_name+ let mut stmt = conn.prepare(&format!(+ "SELECT {ENTRY_COLUMNS}FROM transcription_history- WHERE id = ?1",- )?;+ WHERE id = ?1"+ ))?;let entry = stmt.query_row([id], Self::map_history_entry).optional()?;@@ -734,7 +748,9 @@ mod tests {post_processed_text TEXT,post_process_prompt TEXT,post_process_requested BOOLEAN NOT NULL DEFAULT 0,- source_name TEXT+ source_name TEXT,+ language TEXT,+ language_source TEXT);",).expect("create transcription_history table");@@ -773,10 +789,12 @@ mod tests {}#[test]- fn migrating_adds_source_name_without_raising_the_version() {+ fn migrating_adds_columns_without_raising_the_version() {let mut conn = Connection::open_in_memory().expect("open in-memory db");HistoryManager::apply_migrations(&mut conn).expect("migrate");- assert!(HistoryManager::has_column(&conn, "source_name").expect("read table info"));+ for column in ADDED_COLUMNS {+ assert!(HistoryManager::has_column(&conn, column).expect("read table info"));+ }assert_eq!(user_version(&conn), MIGRATIONS.len() as i32);// Opening it again changes nothing.@@ -804,6 +822,26 @@ mod tests {assert_eq!(entry.transcription_text, "still works");}+ #[test]+ fn reads_the_language_and_ignores_an_unknown_source() {+ let conn = setup_conn();+ let latest = |source: &str| {+ conn.execute(+ "INSERT INTO transcription_history (file_name, timestamp, title, transcription_text, language, language_source)+ VALUES ('a.wav', (SELECT COUNT(*) FROM transcription_history), 'a', 'hallo', 'de', ?1)",+ [source],+ )+ .expect("insert entry");+ HistoryManager::get_latest_entry_with_conn(&conn)+ .unwrap()+ .unwrap()+ };+ let entry = latest("detected");+ assert_eq!(entry.language.as_deref(), Some("de"));+ assert_eq!(entry.language_source, Some(LanguageSource::Detected));+ assert_eq!(latest("from_the_future").language_source, None);+ }+#[test]fn get_latest_entry_returns_none_when_empty() {let conn = setup_conn();diff --git a/src-tauri/src/managers/model.rs b/src-tauri/src/managers/model.rsindex b7b9d4cb..8f8949b0 100644--- a/src-tauri/src/managers/model.rs+++ b/src-tauri/src/managers/model.rs@@ -286,7 +286,10 @@ pub fn effective_language(}/// The model's own code for `language`, if it hears it.-fn supported_code<'a>(language: &str, supported_languages: &'a [String]) -> Option<&'a String> {+pub(crate) fn supported_code<'a>(+ language: &str,+ supported_languages: &'a [String],+) -> Option<&'a String> {// Exact base first, then aliases: with both `no` and `nb` listed, `nb` must pick `nb`.supported_languages.iter()@@ -521,12 +524,70 @@ fn local_caps(probe: &CapabilityProbe) -> LocalCaps {}}+/// Download id under which a standalone language detector download reports+/// progress, completion and cancellation, like a model's.+pub const LANGUAGE_DETECTOR_ID: &str = "language-detector";++/// Where one file's download progress is reported: under `model_id`, its bytes+/// counted from `offset`, out of `total` (default: `offset` + the file's own+/// size). Lets two files (the language detector, then a model) fill one bar.+#[derive(Clone)]+pub(super) struct ProgressTarget {+ pub model_id: String,+ pub offset: u64,+ pub total: Option<u64>,+}++impl ProgressTarget {+ /// A file reporting on its own.+ fn own(model_id: &str) -> Self {+ Self {+ model_id: model_id.to_string(),+ offset: 0,+ total: None,+ }+ }++ /// The event for `downloaded` of this file's `total` bytes.+ pub(super) fn progress(+ &self,+ downloaded: u64,+ total: u64,+ bytes_per_sec: Option<f64>,+ ) -> DownloadProgress {+ let downloaded = self.offset + downloaded;+ let total = self.total.unwrap_or(self.offset + total).max(downloaded);+ DownloadProgress {+ model_id: self.model_id.clone(),+ downloaded,+ total,+ percentage: if total > 0 {+ downloaded as f64 / total as f64 * 100.0+ } else {+ 0.0+ },+ bytes_per_sec,+ }+ }+}++/// One file to fetch from Hugging Face, with mirror fallback.+struct FileTransfer<'a> {+ /// What the logs call it.+ label: &'a str,+ repo_id: &'a str,+ revision: &'a str,+ filename: &'a str,+ mirrors: Vec<crate::catalog::MirrorFile>,+ progress: ProgressTarget,+}+/// Bridges hf-hub's async download progress to Handy's `model-download-progress`/// event. hf-hub clones the reporter, so shared state lives behind an `Arc`.#[derive(Clone)]struct HfDownloadProgress {app_handle: AppHandle,- model_id: String,+ target: ProgressTarget,state: Arc<Mutex<HfProgressState>>,}@@ -604,10 +665,10 @@ impl HfProgressState {}impl HfDownloadProgress {- fn new(app_handle: AppHandle, model_id: String) -> Self {+ fn new(app_handle: AppHandle, target: ProgressTarget) -> Self {Self {app_handle,- model_id,+ target,state: Arc::new(Mutex::new(HfProgressState::new(Instant::now()))),}}@@ -626,20 +687,9 @@ impl HfDownloadProgress {}fn emit(&self, (downloaded, total, bytes_per_sec): HfProgressSnapshot) {- let percentage = if total > 0 {- (downloaded as f64 / total as f64) * 100.0- } else {- 0.0- };let _ = self.app_handle.emit("model-download-progress",- &DownloadProgress {- model_id: self.model_id.clone(),- downloaded,- total,- percentage,- bytes_per_sec,- },+ &self.target.progress(downloaded, total, bytes_per_sec),);}}@@ -822,6 +872,9 @@ pub struct ModelManager {/// Single-flight guard for [`Self::rescan_local_models`] so concurrent/// refresh requests coalesce instead of scanning the disk in parallel.is_rescanning: Arc<AtomicBool>,+ /// One language detector transfer at a time, however many downloads+ /// want it.+ detector_download: tokio::sync::Mutex<()>,}impl ModelManager {@@ -1025,6 +1078,7 @@ impl ModelManager {available_models: Mutex::new(available_models),cancel_flags: Arc::new(Mutex::new(HashMap::new())),is_rescanning: Arc::new(AtomicBool::new(false)),+ detector_download: tokio::sync::Mutex::new(()),};// Migrate any bundled models to user directory@@ -1509,8 +1563,13 @@ impl ModelManager {continue;};- // Skip predefined model files- if predefined_filenames.contains(&filename) {+ // Skip predefined model files, and the language detector (a mirror+ // download lands here), which isn't a transcription model.+ if predefined_filenames.contains(&filename)+ || crate::catalog::LANGUAGE_DETECTOR+ .as_ref()+ .is_some_and(|detector| detector.filename == filename)+ {continue;}@@ -1754,6 +1813,7 @@ impl ModelManager {/// hf-hub, reporting progress through the same `model-download-progress`/// event the URL path uses. Uses hf-hub's stock cache, but deliberately/// disables authentication because every catalog repository is public.+ /// A model that needs the language detector gets it first, in one bar.async fn download_hf_model(&self,model_info: &ModelInfo,@@ -1764,10 +1824,11 @@ impl ModelManager {let filename = model_info.filename.clone();// Already in the shared cache (possibly from another tool), or dropped- // into the models dir (mirror fallback / manual install)? Done.- if hf_cached_path(&repo_id, &revision, &filename).is_some()- || self.models_dir.join(&filename).exists()- {+ // into the models dir (mirror fallback / manual install)?+ let model_present = hf_cached_path(&repo_id, &revision, &filename).is_some()+ || self.models_dir.join(&filename).exists();+ let detector = self.missing_detector_for(model_info);+ if model_present && detector.is_none() {self.update_download_status()?;let _ = self.app_handle.emit("model-download-complete", &model_id);return Ok(());@@ -1796,8 +1857,151 @@ impl ModelManager {disarmed: false,};+ // The detector, then the model, as one bar: the detector's bytes come+ // first, out of both files' total.+ let mut offset = 0;+ if let Some(detector) = detector {+ let model_bytes = if model_present {+ 0+ } else {+ crate::catalog::file_in_catalog(&filename, Some(&repo_id))+ .map(|(_, file)| file.size_bytes)+ .unwrap_or(model_info.size_mb * 1024 * 1024)+ };+ let progress = ProgressTarget {+ model_id: model_id.clone(),+ offset: 0,+ total: Some(detector.size_bytes + model_bytes),+ };+ match self.fetch_language_detector(progress, &cancel_token).await {+ Ok(true) => offset = detector.size_bytes,+ Ok(false) => {+ info!("HF download cancelled for: {}", model_id);+ return Ok(());+ }+ // The model works without it: Auto falls back to the first+ // preferred language and the language picker offers the+ // download, so it doesn't cost them the model.+ Err(e) => warn!(+ "Language detector download failed; continuing with {}: {:#}",+ model_id, e+ ),+ }+ }++ if !model_present {+ let transfer = FileTransfer {+ label: &model_id,+ repo_id: &repo_id,+ revision: &revision,+ filename: &filename,+ mirrors: crate::catalog::mirror_fallbacks(&model_id),+ progress: ProgressTarget {+ model_id: model_id.clone(),+ offset,+ total: None,+ },+ };+ if !self.fetch_hf_file(&transfer, &cancel_token).await? {+ return Ok(());+ }+ }++ cleanup.disarmed = true;+ self.update_download_status()?;+ self.cancel_flags.lock().unwrap().remove(&model_id);+ let _ = self.app_handle.emit("model-download-complete", &model_id);+ info!("HF model {} downloaded", model_id);+ Ok(())+ }++ /// The language detector, when `model` needs it for Auto and it isn't on+ /// disk.+ fn missing_detector_for(+ &self,+ model: &ModelInfo,+ ) -> Option<&'static crate::catalog::LanguageDetectorFile> {+ let languages = crate::language_detection::policy::ModelLanguages {+ languages: &model.supported_languages,+ detects: model.supports_language_detection,+ streaming: model.supports_streaming,+ };+ if !crate::language_detection::policy::requires_language_detector(&languages)+ || self.language_detector_path().is_some()+ {+ return None;+ }+ crate::catalog::LANGUAGE_DETECTOR.as_ref()+ }++ /// Download the language detector on its own, tracked and cancelled under+ /// [`LANGUAGE_DETECTOR_ID`] like a model.+ pub async fn download_language_detector(&self) -> Result<()> {+ let cancel_token = CancellationToken::new();+ self.cancel_flags+ .lock()+ .unwrap()+ .insert(LANGUAGE_DETECTOR_ID.to_string(), cancel_token.clone());+ let fetched = self+ .fetch_language_detector(ProgressTarget::own(LANGUAGE_DETECTOR_ID), &cancel_token)+ .await;+ self.cancel_flags+ .lock()+ .unwrap()+ .remove(LANGUAGE_DETECTOR_ID);+ if fetched? {+ let _ = self+ .app_handle+ .emit("model-download-complete", LANGUAGE_DETECTOR_ID);+ }+ Ok(())+ }++ /// Fetch the language detector unless it's on disk. One transfer at a+ /// time: a second caller waits, then finds the file there. `Ok(false)` if+ /// cancelled.+ async fn fetch_language_detector(+ &self,+ progress: ProgressTarget,+ cancel_token: &CancellationToken,+ ) -> Result<bool> {+ let detector = crate::catalog::LANGUAGE_DETECTOR+ .as_ref()+ .ok_or_else(|| anyhow::anyhow!("The catalog names no language detector"))?;+ let _single = tokio::select! {+ guard = self.detector_download.lock() => guard,+ _ = cancel_token.cancelled() => return Ok(false),+ };+ if self.language_detector_path().is_some() {+ return Ok(true);+ }+ let transfer = FileTransfer {+ label: "the language detector",+ repo_id: &detector.repo_id,+ revision: &detector.revision,+ filename: &detector.filename,+ mirrors: crate::catalog::language_detector_mirrors(),+ progress,+ };+ self.fetch_hf_file(&transfer, cancel_token).await+ }++ /// Fetch one file from Hugging Face into the shared cache, retrying, then+ /// falling back to the mirrors into the models dir. `Ok(false)` if+ /// cancelled (partial kept for resume).+ async fn fetch_hf_file(+ &self,+ transfer: &FileTransfer<'_>,+ cancel_token: &CancellationToken,+ ) -> Result<bool> {+ let model_id = transfer.label;+ let repo_id = transfer.repo_id.to_string();+ let revision = transfer.revision.to_string();+ let filename = transfer.filename;+ let cancel_token = cancel_token.clone();+info!(- "Downloading HF model {} from {}@{} ({})",+ "Downloading {} from {}@{} ({})",model_id, repo_id, revision, filename);@@ -1839,7 +2043,8 @@ impl ModelManager {RepoType::Model,revision.clone(),));- let progress = HfDownloadProgress::new(self.app_handle.clone(), model_id.clone());+ let progress =+ HfDownloadProgress::new(self.app_handle.clone(), transfer.progress.clone());// hf-hub has no internal timeouts, so a wedged connection would// otherwise hang this attempt forever and neither the retry loop@@ -1873,7 +2078,7 @@ impl ModelManager {// `.sync.part` resume offset), then drop the future outright,// which aborts whatever request it was wedged in.let mut download = std::pin::pin!(repo.download_with_progress_cancellable(- &filename,+ filename,progress,attempt_token.clone()));@@ -1897,7 +2102,7 @@ impl ModelManager {// drops the token; `cancel_download` already emitted// `model-download-cancelled`.info!("HF download cancelled for: {}", model_id);- return Ok(());+ return Ok(false);}Err(hf_hub::api::tokio::ApiError::Cancelled) => {let err = anyhow::anyhow!(@@ -1926,7 +2131,7 @@ impl ModelManager {_ = tokio::time::sleep(delay) => {}_ = cancel_token.cancelled() => {info!("HF download cancelled for: {}", model_id);- return Ok(());+ return Ok(false);}}attempt += 1;@@ -1953,7 +2158,7 @@ impl ModelManager {_ = tokio::time::sleep(delay) => {}_ = cancel_token.cancelled() => {info!("HF download cancelled for: {}", model_id);- return Ok(());+ return Ok(false);}}attempt += 1;@@ -1967,7 +2172,7 @@ impl ModelManager {"HF download failed for {} after {} attempt(s): {:?}",model_id, attempt, hf_error);- let mirrors = crate::catalog::mirror_fallbacks(&model_id);+ let mirrors = &transfer.mirrors;if mirrors.is_empty() {return Err(anyhow::anyhow!("Hugging Face download failed after {} attempt(s): {}",@@ -1976,10 +2181,15 @@ impl ModelManager {));}let mut completed = false;- for mirror in &mirrors {+ for mirror in mirrors {info!("Falling back to mirror for {}: {}", model_id, mirror.url);match self- .download_from_mirror(&model_id, &filename, mirror, cancel_token.clone())+ .download_from_mirror(+ &transfer.progress,+ filename,+ mirror,+ cancel_token.clone(),+ ).await{Ok(true) => {@@ -1988,7 +2198,7 @@ impl ModelManager {}Ok(false) => {info!("Mirror download cancelled for: {}", model_id);- return Ok(());+ return Ok(false);}Err(e) => {warn!(@@ -2007,12 +2217,7 @@ impl ModelManager {}}- cleanup.disarmed = true;- self.update_download_status()?;- self.cancel_flags.lock().unwrap().remove(&model_id);- let _ = self.app_handle.emit("model-download-complete", &model_id);- info!("HF model {} downloaded", model_id);- Ok(())+ Ok(true)}/// Direct-HTTP download of a catalog model's file from a mirror into the@@ -2020,7 +2225,7 @@ impl ModelManager {/// `Ok(true)` on completion, `Ok(false)` if cancelled (partial kept).async fn download_from_mirror(&self,- model_id: &str,+ progress: &ProgressTarget,filename: &str,mirror: &crate::catalog::MirrorFile,cancel_token: CancellationToken,@@ -2035,7 +2240,7 @@ impl ModelManager {match self.download_http_resumable(- model_id,+ progress,&mirror.url,&partial_path,Some(mirror.size_bytes),@@ -2049,7 +2254,7 @@ impl ModelManager {fs::rename(&partial_path, &model_path)?;info!("Mirror download of {} completed and verified ({:?})",- model_id, model_path+ filename, model_path);Ok(true)}@@ -2119,7 +2324,7 @@ impl ModelManager {// the server's content-length for progress and completeness checks.match self.download_http_resumable(- model_id,+ &ProgressTarget::own(model_id),&url,&partial_path,None,@@ -2362,6 +2567,16 @@ impl ModelManager {Ok(model_path)}+ /// The spoken-language detector's file, when it is fully on disk: in the+ /// HF cache, or in the models dir (mirror fallback / manual drop-in).+ pub fn language_detector_path(&self) -> Option<PathBuf> {+ let detector = crate::catalog::LANGUAGE_DETECTOR.as_ref()?;+ hf_cached_path(&detector.repo_id, &detector.revision, &detector.filename).or_else(|| {+ let local = self.models_dir.join(&detector.filename);+ local.is_file().then_some(local)+ })+ }+pub fn cancel_download(&self, model_id: &str) -> Result<()> {debug!("ModelManager: cancel_download called for: {}", model_id);@@ -2400,6 +2615,26 @@ impl ModelManager {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn detector_then_model_report_as_one_bar() {+ // 45 MB detector, then a 700 MB model: one bar from 0 to 745 MB.+ let detector = ProgressTarget {+ model_id: "m".into(),+ offset: 0,+ total: Some(745),+ };+ let p = detector.progress(45, 45, None);+ assert_eq!((p.model_id.as_str(), p.downloaded, p.total), ("m", 45, 745));++ let model = ProgressTarget {+ model_id: "m".into(),+ offset: 45,+ total: None,+ };+ let p = model.progress(350, 700, Some(1.0));+ assert_eq!((p.downloaded, p.total), (395, 745));+ }use std::fs::File;use std::io::Write;use tempfile::TempDir;@@ -2902,6 +3137,17 @@ mod tests {assert_eq!(models.len(), count_before);}+ #[test]+ fn a_mirrored_language_detector_is_not_a_custom_model() {+ let temp_dir = TempDir::new().unwrap();+ let detector = crate::catalog::LANGUAGE_DETECTOR.as_ref().unwrap();+ fs::write(temp_dir.path().join(&detector.filename), b"gguf").unwrap();++ let mut models = HashMap::new();+ ModelManager::discover_custom_transcribe_models(temp_dir.path(), &mut models).unwrap();+ assert!(models.is_empty());+ }+#[test]fn test_discover_custom_models_nonexistent_dir() {let models_dir = PathBuf::from("/nonexistent/path/that/does/not/exist");diff --git a/src-tauri/src/managers/model/download.rs b/src-tauri/src/managers/model/download.rsindex 866f1c3f..38802be4 100644--- a/src-tauri/src/managers/model/download.rs+++ b/src-tauri/src/managers/model/download.rs@@ -3,7 +3,7 @@//! Both legacy URL models and Hugging Face mirror fallbacks use this module;//! source-specific orchestration and finalization remain in the parent module.-use super::{DownloadProgress, ModelManager};+use super::{DownloadProgress, ModelManager, ProgressTarget};use anyhow::Result;use futures_util::StreamExt;use hf_hub::api::tokio::CancellationToken;@@ -175,7 +175,7 @@ impl ModelManager {/// bus — the production entry point.pub(super) async fn download_http_resumable(&self,- model_id: &str,+ target: &ProgressTarget,url: &str,partial_path: &Path,expected_size: Option<u64>,@@ -183,9 +183,9 @@ impl ModelManager {cancel_token: &CancellationToken,) -> Result<HttpDownloadOutcome> {let app_handle = self.app_handle.clone();- let id = model_id.to_string();+ let id = target.model_id.clone();Self::download_http_resumable_with_events(- model_id,+ &target.model_id,url,partial_path,expected_size,@@ -193,9 +193,14 @@ impl ModelManager {cancel_token,&move |event| {let _ = match event {- HttpDownloadEvent::Progress(progress) => {- app_handle.emit("model-download-progress", progress)- }+ HttpDownloadEvent::Progress(progress) => app_handle.emit(+ "model-download-progress",+ target.progress(+ progress.downloaded,+ progress.total,+ progress.bytes_per_sec,+ ),+ ),HttpDownloadEvent::VerificationStarted => {app_handle.emit("model-verification-started", &id)}diff --git a/src-tauri/src/managers/transcription.rs b/src-tauri/src/managers/transcription.rsindex 4173a6b5..b3a40c09 100644--- a/src-tauri/src/managers/transcription.rs+++ b/src-tauri/src/managers/transcription.rs@@ -8,13 +8,17 @@ use crate::engine_supervisor::{CancelMark, DeviceInfo, DeviceSelector, EngineError, EngineSupervisor, LoadSpec, LoadedInfo,Unloading,};-use crate::managers::audio::AudioRecordingManager;+use crate::language_detection::speech::speech_head;+use crate::language_detection::{+ IdentifyError, LanguageDecision, LanguageDetector, LanguageSource, Plan,+};+use crate::managers::audio::{create_smoothed_detector, AudioRecordingManager};use crate::managers::model::ModelManager;use crate::settings::{get_settings, AppSettings, ChineseScript, ModelUnloadTimeout, TranscribeAcceleratorSetting,};use anyhow::Result;-use chunked::ChunkedDecode;+use chunked::{ChunkSetup, ChunkedDecode};use live::LiveSession;use log::{debug, error, info, warn};use policy::{batch_decode, live_decode, BatchDecode, ModelTraits};@@ -269,6 +273,9 @@ pub struct TranscriptionManager {/// True while a background job is queued or running. It holds the model,/// so one transcript is never written by two models.job_active: Arc<AtomicBool>,+ /// Handy's spoken-language detector, loaded in this process on first+ /// use and unloaded with the model.+ language_detector: Arc<LanguageDetector>,}impl TranscriptionManager {@@ -289,6 +296,7 @@ impl TranscriptionManager {next_stream_worker_id: Arc::new(AtomicU64::new(1)),active_stream_worker: Arc::new(AtomicU64::new(0)),job_active: Arc::new(AtomicBool::new(false)),+ language_detector: Arc::new(LanguageDetector::default()),};// Start the idle watcher@@ -457,6 +465,7 @@ impl TranscriptionManager {/// it. Only the worker's exit is left to wait for.fn begin_unload(&self) -> Unloading {let unloading = self.engine.unload();+ self.language_detector.unload();{let mut current_model = self.current_model_id.lock().unwrap();*current_model = None;@@ -916,12 +925,12 @@ impl TranscriptionManager {/// Transcribe a whole clip in batch: a re-transcribed history entry, or/// a file from the CLI.pub fn transcribe(&self, audio: Vec<f32>) -> Result<String> {- self.complete(Instant::now(), audio, None)+ Ok(self.complete(Instant::now(), audio, None)?.text)}/// Transcribe a finished recording: what its live decode produced, or a/// batch run of the whole recording when there is no live result.- pub fn transcribe_recording(&self, samples: Vec<f32>) -> Result<String> {+ pub fn transcribe_recording(&self, samples: Vec<f32>) -> Result<Transcription> {let started = Instant::now();let live = self.finalize_live(samples.len())?;self.complete(started, samples, live)@@ -934,7 +943,7 @@ impl TranscriptionManager {started: Instant,audio: Vec<f32>,live: Option<RunOutcome>,- ) -> Result<String> {+ ) -> Result<Transcription> {#[cfg(debug_assertions)]if std::env::var("HANDY_FORCE_TRANSCRIPTION_FAILURE").is_ok() {return Err(anyhow::anyhow!(@@ -947,7 +956,10 @@ impl TranscriptionManager {if audio.is_empty() {debug!("Empty audio vector");self.maybe_unload_immediately("empty audio");- return Ok(String::new());+ return Ok(Transcription {+ text: String::new(),+ language: None,+ });}let outcome = match live {@@ -955,6 +967,9 @@ impl TranscriptionManager {None => self.decode_batch(audio)?,};let settings = get_settings(&self.app_handle);+ let language = outcome+ .setup+ .spoken_language(outcome.model_detected_language.as_deref());let final_result = finish_text(outcome, &settings);let translation_note = if settings.translate_to_english {@@ -984,7 +999,10 @@ impl TranscriptionManager {self.maybe_unload_immediately("transcription");- Ok(final_result)+ Ok(Transcription {+ text: final_result,+ language: Some(language),+ })}/// Decode a whole clip with the loaded model, loading it first if a load@@ -994,13 +1012,14 @@ impl TranscriptionManager {// included) stops every run of this transcription.let mark = self.engine.cancel_mark();self.touch_activity();- let batch = self.batch_context()?;+ let batch = self.batch_context(&audio)?;self.transcribe_cpp(mark, batch, audio)}- /// Waits out any model load, then reads what a batch transcription runs- /// with: the loaded model, the settings, and the language resolved for it.- fn batch_context(&self) -> Result<BatchContext> {+ /// Waits out any model load, then reads what a batch transcription of+ /// `audio` runs with: the loaded model, the settings, and the language+ /// resolved for it.+ fn batch_context(&self, audio: &[f32]) -> Result<BatchContext> {{let mut is_loading = self.is_loading.lock().unwrap();while *is_loading {@@ -1019,19 +1038,8 @@ impl TranscriptionManager {let active_model = self.get_current_model().unwrap_or_else(|| settings.selected_model.clone());- // Resolve the persisted language *intent* into the language this model- // will actually use. The coercion is capability-aware (a must-pick model- // never receives "auto") and computed fresh here — it is never written- // back to settings, so the intent survives switching models and back.- let validated_language =- effective_language_for_model(&settings, self.model_manager.as_ref(), &active_model);- if validated_language != settings.selected_language {- debug!(- "Language intent '{}' resolved to '{}' for model '{}'",- settings.selected_language, validated_language, active_model- );- }- let setup = run_setup(&info, &settings, &validated_language);+ let plan = self.language_plan(&settings, &active_model, &info);+ let setup = self.setup_for(&info, &settings, &plan, audio);Ok(BatchContext {info,settings,@@ -1040,6 +1048,69 @@ impl TranscriptionManager {})}+ /// How a transcription on `model_id` picks its language, decided before+ /// any audio. Computed fresh each time and never written back to+ /// settings, so the persisted intent survives switching models and back.+ fn language_plan(&self, settings: &AppSettings, model_id: &str, info: &LoadedInfo) -> Plan {+ let model = self.model_manager.get_model_info(model_id);+ crate::language_detection::plan_for(+ settings,+ model.as_ref(),+ info.capabilities.supports_streaming,+ )+ }++ /// Resolves `plan` with the transcription's `audio` into the run setup+ /// every run of it uses. Detection runs only for a detect plan.+ fn setup_for(+ &self,+ info: &LoadedInfo,+ settings: &AppSettings,+ plan: &Plan,+ audio: &[f32],+ ) -> RunSetup {+ // No VAD pass when the detector isn't there to use the speech.+ let speech = if !plan.detects() {+ Some(Vec::new())+ } else if self.model_manager.language_detector_path().is_some() {+ Some(self.detection_speech(settings, audio))+ } else {+ None+ };+ let language = plan.decide(speech.as_deref(), |speech, allowed| {+ let path = self+ .model_manager+ .language_detector_path()+ .ok_or(IdentifyError::Missing)?;+ self.language_detector+ .identify(&path, speech, allowed)+ .map_err(IdentifyError::Failed)+ });+ info!(+ "Transcription language: {} ({:?})",+ language.intent(),+ language.source+ );+ run_setup(info, settings, language)+ }++ /// The first window of speech in `audio`: silence is always cut out by+ /// VAD first, whatever `vad_enabled` says, so the window is all speech.+ fn detection_speech(&self, settings: &AppSettings, audio: &[f32]) -> Vec<f32> {+ create_smoothed_detector(settings.vad_backend, &self.app_handle)+ .and_then(|mut vad| {+ speech_head(+ &mut vad,+ audio,+ settings.language_detection_window_samples(),+ )+ })+ .unwrap_or_else(|e| {+ warn!("Language detection: VAD failed: {e:#}");+ Vec::new()+ })+ }+fn transcribe_cpp(&self,mark: CancelMark,@@ -1052,24 +1123,26 @@ impl TranscriptionManager {active_model,setup,} = batch;- let whole = |pcm: Vec<f32>| {- self.run_batch(mark, pcm, &setup.run_options, &active_model)- .map_err(engine_error)- };// `mark` covers every chunk, so a cancel between two stops the rest.// A failed chunk fails the whole transcription.- let transcripts = match batch_decode(ModelTraits::of(&info), settings.long_form_chunking) {- BatchDecode::Chunked => ChunkedDecode::decode_clip(- self,- mark,- setup.run_options.clone(),- audio,- &active_model,- settings.vad_backend,- )- .map_err(engine_error)?,- BatchDecode::Whole => vec![whole(audio)?],- };+ let (transcripts, setup) =+ match batch_decode(ModelTraits::of(&info), settings.long_form_chunking) {+ BatchDecode::Chunked => ChunkedDecode::decode_clip(+ self,+ mark,+ ChunkSetup::Ready(Box::new(setup)),+ audio,+ &active_model,+ settings.vad_backend,+ )+ .map_err(engine_error)?,+ BatchDecode::Whole => {+ let transcript = self+ .run_batch(mark, audio, &setup.run_options, &active_model)+ .map_err(engine_error)?;+ (vec![transcript], setup)+ }+ };let (text, model_detected_language) = join_chunks(transcripts);Ok(RunOutcome {setup,@@ -1107,6 +1180,14 @@ struct BatchContext {setup: RunSetup,}+/// A finished transcription.+pub struct Transcription {+ pub text: String,+ /// The language it ran in and how that was chosen; `None` when there was+ /// no audio to run.+ pub language: Option<LanguageDecision>,+}+/// What one transcription decoded (live or in batch), with how its runs were/// set up, which post-processing needs to know.struct RunOutcome {@@ -1140,6 +1221,8 @@ fn finish_text(outcome: RunOutcome, settings: &AppSettings) -> String {/// configured on the loaded model, and what post-processing needs to know.struct RunSetup {run_options: RunOptions,+ /// The language every run uses, and how it was chosen.+ language: LanguageDecision,languages: Vec<String>,applied_language_hint: Option<String>,output_was_translated: bool,@@ -1151,6 +1234,18 @@ impl RunSetup {!self.run_options.vocabulary.is_empty()}+ /// The language the runs were in. When the model decided, the language+ /// it reported (if any).+ fn spoken_language(&self, model_detected_language: Option<&str>) -> LanguageDecision {+ let mut decision = self.language.clone();+ if decision.language.is_none() {+ decision.language = model_detected_language+ .filter(|language| !language.is_empty() && *language != "auto")+ .map(str::to_string);+ }+ decision+ }+/// What the output language is known to be, given the model's own/// detection when it reported one.fn output_language(@@ -1162,6 +1257,7 @@ impl RunSetup {resolve_output_language_evidence(settings,self.applied_language_hint.as_deref(),+ self.language.source == LanguageSource::Detected,&self.languages,self.output_was_translated,),@@ -1173,7 +1269,7 @@ impl RunSetup {/// The loaded model's live capabilities (cheap GGUF-metadata reads) are the/// source of truth, not the ModelManager copy; translate is gated on what the/// model advertises.-fn run_setup(info: &LoadedInfo, settings: &AppSettings, validated_language: &str) -> RunSetup {+fn run_setup(info: &LoadedInfo, settings: &AppSettings, language: LanguageDecision) -> RunSetup {let model_supports_translate = info.capabilities.supports_translate;let languages = info.capabilities.languages.clone();debug!(@@ -1188,12 +1284,34 @@ fn run_setup(info: &LoadedInfo, settings: &AppSettings, validated_language: &strlet run_plan = transcribe_cpp_run_plan(settings.translate_to_english,- validated_language,+ language.intent(),&languages,model_supports_translate,);let output_was_translated = run_plan.target_language.as_deref() == Some("en");let applied_language_hint = run_plan.language.clone();+ if applied_language_hint.is_none()+ && matches!(+ language.source,+ LanguageSource::Detected | LanguageSource::Fallback+ )+ {+ if let Some(chosen) = &language.language {+ warn!(+ "Language '{}' isn't one the loaded model advertises ({:?}); it runs without a language",+ chosen, languages+ );+ }+ }+ // The model wasn't told a language, so record what it reports instead.+ let language = if applied_language_hint.is_none() && language.language.is_some() {+ LanguageDecision {+ language: None,+ source: LanguageSource::Model,+ }+ } else {+ language+ };let run_options = RunOptions {task: run_plan.task,@@ -1212,6 +1330,7 @@ fn run_setup(info: &LoadedInfo, settings: &AppSettings, validated_language: &strRunSetup {run_options,+ language,languages,applied_language_hint,output_was_translated,@@ -1231,11 +1350,7 @@ fn engine_error(e: EngineError) -> anyhow::Error {/// language hint was passed). Chunks that disagree leave it unknown. A single/// transcript passes through untouched.fn join_chunks(transcripts: Vec<Transcript>) -> (String, Option<String>) {- let mut detected = transcripts.iter().map(|t| t.language.clone());- let language = detected- .next()- .flatten()- .filter(|first| detected.all(|language| language.as_ref() == Some(first)));+ let language = agreed_language(&transcripts);let text = match <[Transcript; 1]>::try_from(transcripts) {Ok([one]) => one.text,Err(many) => {@@ -1245,6 +1360,15 @@ fn join_chunks(transcripts: Vec<Transcript>) -> (String, Option<String>) {(text, language)}+/// The language every chunk's model reported, if they all agree.+fn agreed_language(transcripts: &[Transcript]) -> Option<String> {+ let mut detected = transcripts.iter().map(|t| t.language.clone());+ detected+ .next()+ .flatten()+ .filter(|first| detected.all(|language| language.as_ref() == Some(first)))+}+fn emit_stream_text(app_handle: &AppHandle, committed: &str, tentative: &str) {let _ = StreamTextEvent {committed: committed.to_string(),@@ -1365,30 +1489,13 @@ fn real_time_factor(audio_secs: f64, compute_secs: f64) -> f64 {}}-/// Resolve the persisted language intent into the language a specific model can-/// use without writing the coerced value back to settings.-fn effective_language_for_model(- settings: &AppSettings,- model_manager: &ModelManager,- model_id: &str,-) -> String {- match model_manager.get_model_info(model_id) {- Some(info) => crate::managers::model::effective_language(- &settings.selected_language,- &settings.spoken_languages,- &info.supported_languages,- info.supports_language_detection,- ),- None => settings.selected_language.clone(),- }-}-/// Resolve how confidently Handy knows the language of the text produced by a/// transcription run. The UI language is deliberately not part of this/// decision.fn resolve_output_language_evidence(settings: &AppSettings,applied_language_hint: Option<&str>,+ detected: bool,supported_languages: &[String],translated_to_english: bool,) -> OutputLanguageEvidence {@@ -1402,6 +1509,9 @@ fn resolve_output_language_evidence(// drops a requested hint when the loaded model does not advertise it.if let Some(language) = applied_language_hint.filter(|lang| !lang.is_empty() && *lang != "auto"){+ if detected {+ return OutputLanguageEvidence::Detected(language.to_string());+ }if settings.selected_language != "auto"&& crate::managers::model::canonical_language_code(&settings.selected_language)== crate::managers::model::canonical_language_code(language)@@ -1945,7 +2055,8 @@ mod tests {..Default::default()};let supported = languages(&["en", "pt"]);- let evidence = resolve_output_language_evidence(&settings, Some("pt"), &supported, false);+ let evidence =+ resolve_output_language_evidence(&settings, Some("pt"), false, &supported, false);let result = post_process_transcription_text("eu vi um carro".to_string(),@@ -1969,8 +2080,13 @@ mod tests {..Default::default()};- let evidence =- resolve_output_language_evidence(&settings, Some("nb"), &languages(&["nb"]), false);+ let evidence = resolve_output_language_evidence(+ &settings,+ Some("nb"),+ false,+ &languages(&["nb"]),+ false,+ );assert_eq!(evidence,@@ -1984,8 +2100,13 @@ mod tests {selected_language: "auto".to_string(),..Default::default()};- let evidence =- resolve_output_language_evidence(&settings, None, &languages(&["en", "pt"]), false);+ let evidence = resolve_output_language_evidence(+ &settings,+ None,+ false,+ &languages(&["en", "pt"]),+ false,+ );// Too short for a reliable text detection, so the gated "um" must// survive; the universal "uhm" is removed regardless.@@ -2075,7 +2196,7 @@ mod tests {};let evidence =- resolve_output_language_evidence(&settings, None, &languages(&["en"]), false);+ resolve_output_language_evidence(&settings, None, false, &languages(&["en"]), false);assert_eq!(evidence,@@ -2093,6 +2214,7 @@ mod tests {let evidence = resolve_output_language_evidence(&settings,Some("en"),+ false,&languages(&["en", "de"]),false,);@@ -2113,7 +2235,7 @@ mod tests {};let supported = languages(&["en", "de", "pt"]);- let evidence = resolve_output_language_evidence(&settings, None, &supported, false);+ let evidence = resolve_output_language_evidence(&settings, None, false, &supported, false);assert_eq!(evidence, OutputLanguageEvidence::Unknown);let result = post_process_transcription_text(@@ -2140,6 +2262,7 @@ mod tests {resolve_output_language_evidence(&settings,plan.language.as_deref(),+ false,&supported,false,),@@ -2157,6 +2280,7 @@ mod tests {let evidence = resolve_output_language_evidence(&settings,Some("pt"),+ false,&languages(&["en", "pt"]),true,);diff --git a/src-tauri/src/managers/transcription/chunked.rs b/src-tauri/src/managers/transcription/chunked.rsindex 3e226657..7df75ce7 100644--- a/src-tauri/src/managers/transcription/chunked.rs+++ b/src-tauri/src/managers/transcription/chunked.rs@@ -4,13 +4,42 @@use std::time::Instant;use log::info;-use transcribe_cpp::{RunOptions, Transcript};+use transcribe_cpp::Transcript;-use super::TranscriptionManager;+use super::{RunSetup, TranscriptionManager};use crate::audio_toolkit::chunking::Chunker;-use crate::engine_supervisor::{CancelMark, EngineError};+use crate::engine_supervisor::{CancelMark, EngineError, LoadedInfo};+use crate::language_detection::Plan;use crate::managers::audio::create_detector;-use crate::settings::VadBackend;+use crate::settings::{AppSettings, VadBackend};++/// How a chunked decode's runs are set up: known up front (a whole clip), or+/// once the first chunk's audio can pick the language (a live recording).+pub(super) enum ChunkSetup {+ Ready(Box<RunSetup>),+ Pending(Box<PendingSetup>),+}++/// What a chunked decode's setup is resolved from.+pub(super) struct PendingSetup {+ pub plan: Plan,+ pub info: LoadedInfo,+ pub settings: AppSettings,+}++impl ChunkSetup {+ /// The setup, resolving a pending one with `audio`.+ fn resolve(&mut self, tm: &TranscriptionManager, audio: &[f32]) -> &RunSetup {+ if let Self::Pending(pending) = self {+ let setup = tm.setup_for(&pending.info, &pending.settings, &pending.plan, audio);+ *self = Self::Ready(Box::new(setup));+ }+ match self {+ Self::Ready(setup) => setup,+ Self::Pending(_) => unreachable!("resolved above"),+ }+ }+}/// Cuts audio at pauses as it arrives and decodes each chunk once its cut is/// certain, so a recording has only its last chunk left when it stops.@@ -18,7 +47,7 @@ pub(super) struct ChunkedDecode<'a> {tm: &'a TranscriptionManager,/// Every chunk's run stops with one cancel.mark: CancelMark,- run_options: RunOptions,+ setup: ChunkSetup,model_id: String,chunker: Chunker,transcripts: Vec<Transcript>,@@ -31,7 +60,7 @@ impl<'a> ChunkedDecode<'a> {pub(super) fn new(tm: &'a TranscriptionManager,mark: CancelMark,- run_options: RunOptions,+ setup: ChunkSetup,model_id: &str,backend: VadBackend,) -> Self {@@ -40,7 +69,7 @@ impl<'a> ChunkedDecode<'a> {Self {tm,mark,- run_options,+ setup,model_id: model_id.to_string(),chunker: Chunker::new(Box::new(move || create_detector(backend, &app_handle))),transcripts: Vec::new(),@@ -48,16 +77,16 @@ impl<'a> ChunkedDecode<'a> {}}- /// A whole clip's chunks, decoded in order.+ /// A whole clip's chunks, decoded in order, and the setup they ran with.pub(super) fn decode_clip(tm: &'a TranscriptionManager,mark: CancelMark,- run_options: RunOptions,+ setup: ChunkSetup,audio: Vec<f32>,model_id: &str,backend: VadBackend,- ) -> Result<Vec<Transcript>, EngineError> {- let mut decode = Self::new(tm, mark, run_options, model_id, backend);+ ) -> Result<(Vec<Transcript>, RunSetup), EngineError> {+ let mut decode = Self::new(tm, mark, setup, model_id, backend);decode.push(audio);decode.finish()}@@ -87,9 +116,9 @@ impl<'a> ChunkedDecode<'a> {self.decode(chunks);}- /// Decodes what is left. Every chunk's transcript in order, or the run- /// that failed or was cancelled.- pub(super) fn finish(mut self) -> Result<Vec<Transcript>, EngineError> {+ /// Decodes what is left. Every chunk's transcript in order and the setup+ /// they ran with, or the run that failed or was cancelled.+ pub(super) fn finish(mut self) -> Result<(Vec<Transcript>, RunSetup), EngineError> {if self.failure.is_none() {let chunks = self.chunker.finish();self.decode(chunks);@@ -104,7 +133,12 @@ impl<'a> ChunkedDecode<'a> {self.transcripts.len());}- Ok(self.transcripts)+ // No chunk at all (no audio) still needs a setup to finish with.+ self.setup.resolve(self.tm, &[]);+ let ChunkSetup::Ready(setup) = self.setup else {+ unreachable!("resolved above")+ };+ Ok((self.transcripts, *setup))}fn decode(&mut self, chunks: Vec<Vec<f32>>) {@@ -112,11 +146,13 @@ impl<'a> ChunkedDecode<'a> {if self.failure.is_some() {return;}+ // The first chunk picks the language for every chunk.+ let run_options = self.setup.resolve(self.tm, &chunk).run_options.clone();let audio_secs = chunk.len() as f64 / 16_000.0;let started = Instant::now();match self.tm- .run_batch(self.mark, chunk, &self.run_options, &self.model_id)+ .run_batch(self.mark, chunk, &run_options, &self.model_id){Ok(transcript) => {self.transcripts.push(transcript);diff --git a/src-tauri/src/managers/transcription/job.rs b/src-tauri/src/managers/transcription/job.rsindex 5553c920..d7a62ca6 100644--- a/src-tauri/src/managers/transcription/job.rs+++ b/src-tauri/src/managers/transcription/job.rs@@ -7,8 +7,8 @@ use std::time::Instant;use transcribe_cpp::Transcript;use super::{- engine_error, post_process_transcription_text, real_time_factor, BatchContext,- TranscriptionManager,+ agreed_language, engine_error, post_process_transcription_text, real_time_factor, BatchContext,+ Transcription, TranscriptionManager,};use crate::audio_toolkit::chunking::Chunker;use crate::engine_supervisor::EngineError;@@ -39,11 +39,14 @@ impl TranscriptionManager {&self,audio: Vec<f32>,control: &dyn ChunkControl,- ) -> Result<Option<String>> {+ ) -> Result<Option<Transcription>> {let started = Instant::now();let total = audio.len();if total == 0 {- return Ok(Some(String::new()));+ return Ok(Some(Transcription {+ text: String::new(),+ language: None,+ }));}self.touch_activity();@@ -54,7 +57,7 @@ impl TranscriptionManager {active_model,setup,..- } = self.batch_context()?;+ } = self.batch_context(&audio)?;let backend = settings.vad_backend;let app_handle = self.app_handle.clone();@@ -102,6 +105,7 @@ impl TranscriptionManager {}debug!("Transcribed {} chunks in the background", transcripts.len());+ let language = setup.spoken_language(agreed_language(&transcripts).as_deref());let paragraphs: Vec<String> = transcripts.into_iter().map(|t| {@@ -126,6 +130,9 @@ impl TranscriptionManager {elapsed_secs,real_time_factor(audio_secs, elapsed_secs));- Ok(Some(paragraphs.join("\n\n")))+ Ok(Some(Transcription {+ text: paragraphs.join("\n\n"),+ language: Some(language),+ }))}}diff --git a/src-tauri/src/managers/transcription/live.rs b/src-tauri/src/managers/transcription/live.rsindex ae1e4050..4e92e288 100644--- a/src-tauri/src/managers/transcription/live.rs+++ b/src-tauri/src/managers/transcription/live.rs@@ -7,24 +7,25 @@ use std::sync::{Arc, Mutex};use log::{debug, error, info};use transcribe_cpp::StreamOptions;-use super::chunked::ChunkedDecode;+use super::chunked::{ChunkSetup, ChunkedDecode, PendingSetup};use super::policy::LiveDecode;use super::{- effective_language_for_model, emit_stream_text, join_chunks, lock_perf, run_setup,- PreviewScript, RunOutcome, RunSetup, StreamFinalizeReply, StreamPerf, TranscriptionManager,+ emit_stream_text, join_chunks, lock_perf, PreviewScript, RunOutcome, RunSetup,+ StreamFinalizeReply, StreamPerf, TranscriptionManager,};use crate::audio_toolkit::OutputLanguageEvidence;use crate::engine_supervisor::{EngineError, LoadedInfo, StreamHandle, StreamProgress};use crate::settings::{get_settings, AppSettings};-/// One recording's live decode, with the run setup its result finishes with.+/// One recording's live decode.pub(super) struct LiveSession<'a> {- setup: RunSetup,decoder: LiveDecoder<'a>,}enum LiveDecoder<'a> {- Stream(StreamSession<'a>),+ /// With the run setup its result finishes with.+ Stream(StreamSession<'a>, Box<RunSetup>),+ /// Its setup is resolved by its first chunk.Chunked(Box<ChunkedDecode<'a>>),}@@ -47,31 +48,38 @@ impl<'a> LiveSession<'a> {// The same run setup as the batch path: task + language gated// against what the model actually advertises.let settings = get_settings(&tm.app_handle);- let effective_language =- effective_language_for_model(&settings, tm.model_manager.as_ref(), model_id);- let setup = run_setup(info, &settings, &effective_language);+ let plan = tm.language_plan(&settings, model_id, info);let decoder = match mode {LiveDecode::None => unreachable!("returned above"),LiveDecode::Stream => {- LiveDecoder::Stream(StreamSession::begin(tm, info, &settings, &setup, model_id)?)+ // A stream's language is fixed before any audio, so it can't+ // be detected; a detect plan falls back.+ let setup = tm.setup_for(info, &settings, &plan, &[]);+ let stream = StreamSession::begin(tm, info, &settings, &setup, model_id)?;+ LiveDecoder::Stream(stream, Box::new(setup))}LiveDecode::Chunked => {info!("Live long-form chunking started (model '{}')", model_id);+ let backend = settings.vad_backend;LiveDecoder::Chunked(Box::new(ChunkedDecode::new(tm,tm.engine.cancel_mark(),- setup.run_options.clone(),+ ChunkSetup::Pending(Box::new(PendingSetup {+ plan,+ info: info.clone(),+ settings,+ })),model_id,- settings.vad_backend,+ backend,)))}};- Some(Self { setup, decoder })+ Some(Self { decoder })}pub(super) fn feed(&mut self, pcm: Vec<f32>) {match &mut self.decoder {- LiveDecoder::Stream(stream) => stream.feed(pcm),+ LiveDecoder::Stream(stream, _) => stream.feed(pcm),LiveDecoder::Chunked(chunks) => chunks.push(pcm),}}@@ -79,22 +87,25 @@ impl<'a> LiveSession<'a> {/// The live result; `None` to transcribe the recording in batch instead./// `recorded_samples` is the whole recording's length.pub(super) fn finish(self, recorded_samples: usize) -> StreamFinalizeReply {- let decoded = match self.decoder {- LiveDecoder::Stream(stream) => stream.finish()?,- LiveDecoder::Chunked(chunks) => finish_chunks(*chunks, recorded_samples)?,- };- Ok(decoded.map(|(text, model_detected_language)| RunOutcome {- setup: self.setup,- text,- model_detected_language,- }))+ match self.decoder {+ LiveDecoder::Stream(stream, setup) => {+ Ok(stream+ .finish()?+ .map(|(text, model_detected_language)| RunOutcome {+ setup: *setup,+ text,+ model_detected_language,+ }))+ }+ LiveDecoder::Chunked(chunks) => finish_chunks(*chunks, recorded_samples),+ }}}fn finish_chunks(chunks: ChunkedDecode<'_>,recorded_samples: usize,-) -> Result<Option<Decoded>, EngineError> {+) -> Result<Option<RunOutcome>, EngineError> {// A failure stops the decode short of the recording; report the failure.if chunks.samples() != recorded_samples && !chunks.failed() {debug!(@@ -106,7 +117,7 @@ fn finish_chunks(}let while_recording = chunks.decoded();match chunks.finish() {- Ok(transcripts) => {+ Ok((transcripts, setup)) => {if while_recording > 0 {info!("{} of {} chunks were decoded while recording",@@ -114,7 +125,12 @@ fn finish_chunks(transcripts.len());}- Ok(Some(join_chunks(transcripts)))+ let (text, model_detected_language) = join_chunks(transcripts);+ Ok(Some(RunOutcome {+ setup,+ text,+ model_detected_language,+ }))}Err(EngineError::Cancelled) => Err(EngineError::Cancelled),Err(e) => {diff --git a/src-tauri/src/managers/transcription_jobs.rs b/src-tauri/src/managers/transcription_jobs.rsindex 9556fffa..303b49bf 100644--- a/src-tauri/src/managers/transcription_jobs.rs+++ b/src-tauri/src/managers/transcription_jobs.rs@@ -19,7 +19,9 @@ use tauri_specta::Event;use crate::actions::process_transcription_output;use crate::audio_toolkit::{decode_audio_file, read_wav_samples, save_wav_file};use crate::managers::history::{HistoryEntry, HistoryManager};-use crate::managers::transcription::{panic_payload_message, ChunkControl, TranscriptionManager};+use crate::managers::transcription::{+ panic_payload_message, ChunkControl, Transcription, TranscriptionManager,+};/// How often a waiting chunk checks whether dictation has finished.const DICTATION_POLL: Duration = Duration::from_millis(200);@@ -294,7 +296,8 @@ impl TranscriptionJobManager {cancelled,percent: Cell::new(0),};- let Some(text) = tm.transcribe_in_chunks(samples, &control)? else {+ let Some(Transcription { text, language }) = tm.transcribe_in_chunks(samples, &control)?+ else {return Ok(());};if text.is_empty() {@@ -318,6 +321,7 @@ impl TranscriptionJobManager {text,processed.post_processed_text,processed.post_process_prompt,+ language,)?;Ok(())}diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rsindex 6c303612..e01f5f38 100644--- a/src-tauri/src/settings.rs+++ b/src-tauri/src/settings.rs@@ -343,6 +343,18 @@ pub enum VadBackend {Earshot,}+/// When Handy's spoken-language detector picks the language for Auto.+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Type, Default)]+#[serde(rename_all = "snake_case")]+pub enum LanguageDetectionMode {+ /// Only for models that can't detect the language themselves.+ #[default]+ WhenNeeded,+ /// For every model except streaming ones, restricted to the languages+ /// the person speaks.+ Always,+}+#[derive(Clone, Serialize, Deserialize, Type)]#[serde(transparent)]pub(crate) struct SecretMap(HashMap<String, String>);@@ -538,6 +550,12 @@ pub struct AppSettings {/// decides whether silence is dropped from recordings.#[serde(default = "default_long_form_chunking")]pub long_form_chunking: bool,+ #[serde(default)]+ pub language_detection: LanguageDetectionMode,+ /// Seconds of speech the language detector hears (debug). Read through+ /// [`AppSettings::language_detection_window_samples`], which clamps it.+ #[serde(default = "default_language_detection_window_secs")]+ pub language_detection_window_secs: u32,/// Which recording overlay to show: None / Minimal / Live. Streaming mode is/// not gated on this — that follows model capability. Migrated from the old/// `overlay_position` (position `none` → style `None`).@@ -614,6 +632,10 @@ fn default_long_form_chunking() -> bool {true}+fn default_language_detection_window_secs() -> u32 {+ 5+}+fn default_filler_word_removal_enabled() -> bool {true}@@ -1033,6 +1055,8 @@ pub fn get_default_settings() -> AppSettings {vad_enabled: default_vad_enabled(),vad_backend: VadBackend::default(),long_form_chunking: default_long_form_chunking(),+ language_detection: LanguageDetectionMode::default(),+ language_detection_window_secs: default_language_detection_window_secs(),overlay_style: default_overlay_style(),}}@@ -1043,7 +1067,17 @@ impl Default for AppSettings {}}+/// The language detector's window bounds: below 2 s it guesses, and it only+/// scores the first 30 s of what it's given.+pub const LANGUAGE_DETECTION_WINDOW_SECS: std::ops::RangeInclusive<u32> = 2..=30;+impl AppSettings {+ /// Samples (16 kHz) of speech the language detector hears.+ pub fn language_detection_window_samples(&self) -> usize {+ let (min, max) = LANGUAGE_DETECTION_WINDOW_SECS.into_inner();+ self.language_detection_window_secs.clamp(min, max) as usize * 16_000+ }+pub fn active_post_process_provider(&self) -> Option<&PostProcessProvider> {self.post_process_providers.iter()diff --git a/src-tauri/src/shortcut/mod.rs b/src-tauri/src/shortcut/mod.rsindex eb19887e..00bfcec2 100644--- a/src-tauri/src/shortcut/mod.rs+++ b/src-tauri/src/shortcut/mod.rs@@ -23,8 +23,9 @@ use tauri::{AppHandle, Emitter, Manager};use crate::settings::APPLE_INTELLIGENCE_DEFAULT_MODEL_ID;use crate::settings::{self, get_settings, AutoSubmitKey, ChineseScript, ClipboardHandling, KeyboardImplementation,- LLMPrompt, OverlayPosition, OverlayStyle, PasteMethod, ShortcutActivation, ShortcutBinding,- SoundTheme, Theme, TypingTool, VadBackend, APPLE_INTELLIGENCE_PROVIDER_ID,+ LLMPrompt, LanguageDetectionMode, OverlayPosition, OverlayStyle, PasteMethod,+ ShortcutActivation, ShortcutBinding, SoundTheme, Theme, TypingTool, VadBackend,+ APPLE_INTELLIGENCE_PROVIDER_ID,};use crate::tray;@@ -910,6 +911,28 @@ pub fn change_word_correction_threshold_setting(Ok(())}+#[tauri::command]+#[specta::specta]+pub fn change_language_detection_setting(+ app: AppHandle,+ mode: LanguageDetectionMode,+) -> Result<(), String> {+ let mut settings = settings::get_settings(&app);+ settings.language_detection = mode;+ settings::write_settings(&app, settings);+ Ok(())+}++#[tauri::command]+#[specta::specta]+pub fn change_language_detection_window_setting(app: AppHandle, secs: u32) -> Result<(), String> {+ let (min, max) = settings::LANGUAGE_DETECTION_WINDOW_SECS.into_inner();+ let mut settings = settings::get_settings(&app);+ settings.language_detection_window_secs = secs.clamp(min, max);+ settings::write_settings(&app, settings);+ Ok(())+}+#[tauri::command]#[specta::specta]pub fn change_extra_recording_buffer_setting(app: AppHandle, ms: u64) -> Result<(), String> {diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rsindex d3db3576..a5c8320f 100644--- a/src-tauri/src/tray.rs+++ b/src-tauri/src/tray.rs@@ -697,6 +697,8 @@ mod tests {post_process_prompt: None,post_process_requested: false,source_name: None,+ language: None,+ language_source: None,}}diff --git a/src/bindings.ts b/src/bindings.tsindex 1f13e3d9..9902fa6a 100644--- a/src/bindings.ts+++ b/src/bindings.ts@@ -149,6 +149,22 @@ async changeExtraRecordingBufferSetting(ms: number) : Promise<Result<null, strinelse return { status: "error", error: e as any };}},+async changeLanguageDetectionSetting(mode: LanguageDetectionMode) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("change_language_detection_setting", { mode }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async changeLanguageDetectionWindowSetting(secs: number) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("change_language_detection_window_setting", { secs }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},async changePasteDelayMsSetting(ms: number) : Promise<Result<null, string>> {try {return { status: "ok", data: await TAURI_INVOKE("change_paste_delay_ms_setting", { ms }) };@@ -692,6 +708,25 @@ async downloadModel(modelId: string) : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},+/**+ * Download the language detector on its own. Progress, completion,+ * cancellation and failure use the model download events under+ * `LANGUAGE_DETECTOR_ID`.+ */+async downloadLanguageDetector() : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("download_language_detector") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+/**+ * Whether the language detector is on disk.+ */+async isLanguageDetectorDownloaded() : Promise<boolean> {+ return await TAURI_INVOKE("is_language_detector_downloaded");+},async deleteModel(modelId: string) : Promise<Result<null, string>> {try {return { status: "ok", data: await TAURI_INVOKE("delete_model", { modelId }) };@@ -890,6 +925,12 @@ async getModelLoadStatus() : Promise<Result<ModelLoadStatus, string>> {else return { status: "error", error: e as any };}},+/**+ * The language transcription on `model_id` will use, for the picker.+ */+async getLanguageStatus(modelId: string) : Promise<LanguageStatus> {+ return await TAURI_INVOKE("get_language_status", { modelId });+},async unloadModelManually() : Promise<Result<null, string>> {try {return { status: "ok", data: await TAURI_INVOKE("unload_model_manually") };@@ -1086,7 +1127,12 @@ vad_backend?: VadBackend;* degrades on long audio. Independent of `vad_enabled`, which only* decides whether silence is dropped from recordings.*/-long_form_chunking?: boolean;+long_form_chunking?: boolean; language_detection?: LanguageDetectionMode;+/**+ * Seconds of speech the language detector hears (debug). Read through+ * [`AppSettings::language_detection_window_samples`], which clamps it.+ */+language_detection_window_secs?: number;/*** Which recording overlay to show: None / Minimal / Live. Streaming mode is* not gated on this — that follows model capability. Migrated from the old@@ -1095,6 +1141,19 @@ long_form_chunking?: boolean;overlay_style?: OverlayStyle }export type AudioDevice = { index: string; name: string; is_default: boolean }export type AutoSubmitKey = "enter" | "ctrl_enter" | "cmd_enter"+export type AutoUnavailableReason =+/**+ * Only one of their languages (or only one at all) fits the model.+ */+{ kind: "one_language" } |+/**+ * The detector can't identify these spoken languages.+ */+{ kind: "undetectable"; languages: string[] } |+/**+ * None of their languages fit the model.+ */+{ kind: "no_match" }export type AvailableAccelerators = { transcribe: string[]; gpu_devices: GpuDeviceOption[] }export type BindingResponse = { success: boolean; binding: ShortcutBinding | null; error: string | null }/**@@ -1122,7 +1181,15 @@ export type HistoryEntry = { id: number; file_name: string; timestamp: number; s* The name of the file this entry was transcribed from; `None` for a* dictation.*/-source_name: string | null }+source_name: string | null;+/**+ * The language it was transcribed in, when known.+ */+language: string | null;+/**+ * How that language was chosen; `None` before it was recorded.+ */+language_source: LanguageSource | null }export type HistoryUpdatePayload = { action: "added"; entry: HistoryEntry } | { action: "updated"; entry: HistoryEntry } | { action: "deleted"; id: number } | { action: "toggled"; id: number }/*** Result of changing keyboard implementation@@ -1139,6 +1206,64 @@ export type KeyboardDiagnosticReport = { secure_input_enabled: boolean; culprit_key_down: number; key_up: number; flags_changed: number; mouse: number; duration_ms: number }export type KeyboardImplementation = "tauri" | "handy_keys"export type LLMPrompt = { id: string; name: string; prompt: string }+/**+ * When Handy's spoken-language detector picks the language for Auto.+ */+export type LanguageDetectionMode =+/**+ * Only for models that can't detect the language themselves.+ */+"when_needed" |+/**+ * For every model except streaming ones, restricted to the languages+ * the person speaks.+ */+"always"+/**+ * How a transcription's language was chosen.+ */+export type LanguageSource =+/**+ * The person picked it, or it is the only language of theirs the model+ * supports.+ */+"selected" |+/**+ * The model decides: its own detection, or its only language.+ */+"model" |+/**+ * Handy's detector picked it.+ */+"detected" |+/**+ * Handy had to pick without detecting (too little speech, detection+ * failed or unavailable, or Auto can't work for these languages).+ */+"fallback"+/**+ * What the language picker shows: the language a transcription will run in,+ * or Auto when it's decided per transcription. Derived from [`plan`], so it+ * can't disagree with what transcription does.+ */+export type LanguageStatus =+/**+ * The language they picked.+ */+{ kind: "selected"; language: string } |+/**+ * Decided per transcription: the model's own detection, or Handy's.+ */+{ kind: "auto" } |+/**+ * Auto needs Handy's detector, which isn't downloaded; `fallback` (the+ * first preferred language) is used until it is.+ */+{ kind: "detector_missing"; fallback: string } |+/**+ * Auto can't work here; `language` is used instead.+ */+{ kind: "auto_unavailable"; language: string; reason: AutoUnavailableReason }export type LogLevel = "trace" | "debug" | "info" | "warn" | "error"export type ModelInfo = { id: string; name: string; description: string; filename: string; source: ModelSource; size_mb: number; is_downloaded: boolean; is_downloading: boolean; partial_size: number; accuracy_score: number; speed_score: number; supports_translation: boolean; is_recommended: boolean; supported_languages: string[]; supports_language_selection: boolean; is_custom: boolean; supports_streaming: boolean; supports_language_detection: boolean }export type ModelLoadStatus = { is_loaded: boolean; current_model: string | null }diff --git a/src/components/model-selector/ModelSelector.tsx b/src/components/model-selector/ModelSelector.tsxindex 9a4b783d..bfe32eeb 100644--- a/src/components/model-selector/ModelSelector.tsx+++ b/src/components/model-selector/ModelSelector.tsx@@ -4,6 +4,7 @@ import { listen } from "@tauri-apps/api/event";import { commands } from "@/bindings";import { getTranslatedModelName } from "../../lib/utils/modelTranslation";import { useModelStore } from "../../stores/modelStore";+import { LANGUAGE_DETECTOR_ID } from "../../hooks/useLanguageDetector";import {areModelsLocked,useModelsLocked,@@ -104,6 +105,8 @@ const ModelSelector: React.FC<ModelSelectorProps> = ({ onError }) => {"model-download-complete",(event) => {const modelId = event.payload;+ // The language detector downloads like a model but isn't one.+ if (modelId === LANGUAGE_DETECTOR_ID) return;setTimeout(async () => {try {const isRecording = await commands.isRecording();diff --git a/src/components/settings/LanguageDetection.tsx b/src/components/settings/LanguageDetection.tsxnew file mode 100644index 00000000..2275ac79--- /dev/null+++ b/src/components/settings/LanguageDetection.tsx@@ -0,0 +1,69 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { useSettings } from "@/hooks/useSettings";+import { useLanguageDetector } from "@/hooks/useLanguageDetector";+import { SettingContainer } from "@/components/ui/SettingContainer";+import { Switch } from "@/components/ui/Switch";+import { LanguageDetectorDownload } from "./LanguageDetectorDownload";++interface LanguageDetectionProps {+ descriptionMode?: "tooltip" | "inline";+ grouped?: boolean;+}++/** Use the language detector for every model, so Auto only picks from their languages. */+export const LanguageDetection: React.FC<LanguageDetectionProps> = ({+ descriptionMode = "tooltip",+ grouped = false,+}) => {+ const { t } = useTranslation();+ const { getSetting, updateSetting, isUpdating } = useSettings();+ const mode = getSetting("language_detection") ?? "when_needed";+ const detector = useLanguageDetector();+ const missing = detector.downloaded === false;+ // Without the detector nothing is limited, so it shows off unless the+ // detector is on its way.+ const checked = mode === "always" && (!missing || detector.downloading);+ const label = t("settings.advanced.languageDetection.title");++ const handleChange = async (on: boolean) => {+ // Turning it off mid-download is how it's stopped.+ if (!on && detector.downloading) {+ detector.cancel();+ }+ await updateSetting("language_detection", on ? "always" : "when_needed");+ // Turning it on is the consent to fetch the detector it needs.+ if (on && missing) {+ await detector.download();+ }+ };++ return (+ <SettingContainer+ title={label}+ description={t("settings.advanced.languageDetection.description")}+ descriptionMode={descriptionMode}+ grouped={grouped}+ >+ <div className="flex items-center gap-3">+ {missing && (+ <LanguageDetectorDownload+ downloading={detector.downloading}+ percent={detector.percent}+ hint={t(+ detector.downloading+ ? "settings.advanced.languageDetection.downloadingHint"+ : "settings.advanced.languageDetection.downloadHint",+ )}+ />+ )}+ <Switch+ checked={checked}+ onChange={handleChange}+ disabled={isUpdating("language_detection")}+ ariaLabel={label}+ />+ </div>+ </SettingContainer>+ );+};diff --git a/src/components/settings/LanguageDetectorDownload.tsx b/src/components/settings/LanguageDetectorDownload.tsxnew file mode 100644index 00000000..82082e87--- /dev/null+++ b/src/components/settings/LanguageDetectorDownload.tsx@@ -0,0 +1,56 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { X } from "lucide-react";+import { DownloadMark } from "../shared/DownloadMark";+import { ProgressRing } from "../shared/ProgressRing";+import { Tooltip } from "../ui/Tooltip";+import { LANGUAGE_DETECTOR_SIZE } from "../../hooks/useLanguageDetector";++interface LanguageDetectorDownloadProps {+ downloading: boolean;+ percent: number;+ /** Explains the size or the progress on hover. */+ hint?: string;+ /** Offers a stop button while downloading, where nothing else can stop it. */+ onCancel?: () => void;+}++/** The end of a row whose choice downloads the language detector: its size, then its progress. */+export const LanguageDetectorDownload: React.FC<+ LanguageDetectorDownloadProps+> = ({ downloading, percent, hint, onCancel }) => {+ const { t } = useTranslation();+ const state = downloading ? (+ <span+ role="status"+ aria-label={t("modelSelector.downloading", { percentage: percent })}+ className="flex items-center gap-1.5 text-xs tabular-nums whitespace-nowrap text-ink-3"+ >+ <ProgressRing size={14} value={percent / 100} />+ {percent}%+ </span>+ ) : (+ <span className="flex items-center gap-1.5 text-xs whitespace-nowrap text-ink-3">+ {LANGUAGE_DETECTOR_SIZE}+ <DownloadMark accent />+ </span>+ );+ const stop = t("settings.general.language.stopDetectorDownload");++ return (+ <span className="flex items-center gap-1">+ {hint ? <Tooltip text={hint}>{state}</Tooltip> : state}+ {downloading && onCancel && (+ <button+ type="button"+ onClick={onCancel}+ title={stop}+ aria-label={stop}+ className="grid size-[20px] cursor-pointer place-items-center rounded-[6px] text-ink-3 hover:bg-line hover:text-text focus:outline-none focus-visible:ring-1 focus-visible:ring-logo-primary"+ >+ <X className="size-[13px]" aria-hidden="true" />+ </button>+ )}+ </span>+ );+};diff --git a/src/components/settings/LanguageSelector.tsx b/src/components/settings/LanguageSelector.tsxindex 435860bf..070d2fc6 100644--- a/src/components/settings/LanguageSelector.tsx+++ b/src/components/settings/LanguageSelector.tsx@@ -1,49 +1,40 @@import React, { useState, useRef, useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";+import { listen } from "@tauri-apps/api/event";import { SettingContainer } from "../ui/SettingContainer";import { ResetButton } from "../ui/ResetButton";+import { InfoTooltip } from "../ui/InfoTooltip";+import { Tooltip } from "../ui/Tooltip";+import { LanguageDetectorDownload } from "./LanguageDetectorDownload";import { useSettings } from "../../hooks/useSettings";+import { useLanguageDetector } from "../../hooks/useLanguageDetector";import { languageIdentity } from "@handy-computer/models";+import {+ commands,+ type AutoUnavailableReason,+ type LanguageStatus,+} from "@/bindings";import {LANGUAGES,+ languageList,languageName,languagesOf,searchLanguages,- supportsLanguage,} from "../../lib/constants/languages";interface LanguageSelectorProps {descriptionMode?: "inline" | "tooltip";grouped?: boolean;+ /** The model whose language status is shown. */+ modelId: string;supportedLanguages?: string[];- // Whether the model can auto-detect language. Gates the "Auto" option:- // must-pick models (no detection) omit it and force a concrete choice.- supportsLanguageDetection?: boolean;}-// Mirrors `effective_language` in src-tauri/src/managers/model.rs, but returns-// the picker's language identity (`jv`), not the model's concrete code (`jw`).-const effectiveLanguage = (- intent: string,- preferred: string[],- supported: string[],- supportsDetection: boolean,-): string => {- const wanted = languageIdentity(intent);- if (supported.length === 0) return wanted;- if (wanted !== "auto" && supportsLanguage(supported, wanted)) return wanted;- if (supportsDetection) return "auto";- if (preferred.length === 1 && supportsLanguage(supported, preferred[0]))- return languageIdentity(preferred[0]);- if (supportsLanguage(supported, "en")) return "en";- return languageIdentity(supported[0]);-};-export const LanguageSelector: React.FC<LanguageSelectorProps> = ({descriptionMode = "tooltip",grouped = false,+ modelId,supportedLanguages,- supportsLanguageDetection = true,}) => {const { t, i18n } = useTranslation();const { getSetting, updateSetting, resetSetting, isUpdating } = useSettings();@@ -52,15 +43,38 @@ export const LanguageSelector: React.FC<LanguageSelectorProps> = ({const dropdownRef = useRef<HTMLDivElement>(null);const searchInputRef = useRef<HTMLInputElement>(null);- // The persisted *intent* (auto | code). What's actually used/shown is the- // effective value resolved against the current model's capabilities.+ // The persisted *intent* (auto | code). What's shown is what transcription+ // will actually use, which the backend resolves from the same policy.const intent = getSetting("selected_language") || "auto";- const selectedLanguage = effectiveLanguage(- intent,- getSetting("spoken_languages") ?? [],- supportedLanguages ?? [],- supportsLanguageDetection,- );+ const spoken = getSetting("spoken_languages");+ const detectionMode = getSetting("language_detection");+ const spokenKey = spoken?.join(",");+ const [status, setStatus] = useState<LanguageStatus | null>(null);+ const detector = useLanguageDetector();++ useEffect(() => {+ let cancelled = false;+ const refresh = () =>+ commands.getLanguageStatus(modelId).then((next) => {+ if (!cancelled) setStatus(next);+ });+ refresh();+ // The language detector arriving changes what Auto does.+ const unlisten = listen("model-download-complete", refresh);+ return () => {+ cancelled = true;+ unlisten.then((stop) => stop());+ };+ }, [modelId, intent, spokenKey, detectionMode]);++ const selectedLanguage =+ status === null+ ? languageIdentity(intent)+ : status.kind === "auto"+ ? "auto"+ : status.kind === "detector_missing"+ ? languageIdentity(status.fallback)+ : languageIdentity(status.language);useEffect(() => {const handleClickOutside = (event: MouseEvent) => {@@ -85,10 +99,7 @@ export const LanguageSelector: React.FC<LanguageSelectorProps> = ({}}, [isOpen]);- // The current model's own languages; every language before one is loaded.- const hasModelLanguages = !!supportedLanguages?.length;// The languages they speak lead, in the order they added them.- const spoken = getSetting("spoken_languages");const availableLanguages = useMemo(() => {const all = supportedLanguages?.length? languagesOf(supportedLanguages)@@ -106,25 +117,50 @@ export const LanguageSelector: React.FC<LanguageSelectorProps> = ({const ui = i18n.language;const autoLabel = t("settings.general.language.auto");+ const autoUnavailableNote = (reason: AutoUnavailableReason): string => {+ switch (reason.kind) {+ case "one_language":+ return t("settings.general.language.autoUnavailable.oneLanguage");+ case "undetectable":+ return t("settings.general.language.autoUnavailable.undetectable", {+ languages: languageList(reason.languages.map(languageIdentity), ui),+ });+ case "no_match":+ return t("settings.general.language.autoUnavailable.noMatch");+ }+ };+ // Auto is always listed; when it can't work here it stays visible, muted,+ // with the reason in a tooltip, so it's clear why it isn't in use. Without+ // the detector it's offered as a download instead.+ const autoNote =+ status?.kind === "auto_unavailable"+ ? autoUnavailableNote(status.reason)+ : status?.kind === "detector_missing"+ ? t("settings.general.language.detectorMissing")+ : undefined;const filteredLanguages = useMemo(() => {- const showAuto =- (!hasModelLanguages || supportsLanguageDetection) &&- autoLabel.toLowerCase().includes(searchQuery.trim().toLowerCase());+ const showAuto = autoLabel+ .toLowerCase()+ .includes(searchQuery.trim().toLowerCase());return [- ...(showAuto ? [{ value: "auto", label: autoLabel }] : []),+ ...(showAuto+ ? [+ {+ value: "auto",+ label: autoLabel,+ disabled: autoNote !== undefined,+ note: autoNote,+ },+ ]+ : []),...searchLanguages(searchQuery, ui, availableLanguages).map((l) => ({value: l.code,label: languageName(l.code, ui),+ disabled: false,+ note: undefined,})),];- }, [- searchQuery,- ui,- autoLabel,- availableLanguages,- hasModelLanguages,- supportsLanguageDetection,- ]);+ }, [searchQuery, ui, autoLabel, autoNote, availableLanguages]);const selectedLanguageName =selectedLanguage === "auto"@@ -151,9 +187,10 @@ export const LanguageSelector: React.FC<LanguageSelectorProps> = ({};const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter" && filteredLanguages.length > 0) {- // Select first filtered language on Enter- handleLanguageSelect(filteredLanguages[0].value);+ const first = filteredLanguages.find((language) => !language.disabled);+ if (event.key === "Enter" && first) {+ // Select first selectable filtered language on Enter+ handleLanguageSelect(first.value);} else if (event.key === "Escape") {setIsOpen(false);setSearchQuery("");@@ -218,22 +255,74 @@ export const LanguageSelector: React.FC<LanguageSelectorProps> = ({{t("settings.general.language.noResults")}</div>) : (- filteredLanguages.map((language) => (- <button- key={language.value}- type="button"- className={`w-full px-2 py-1 text-sm text-start hover:bg-logo-primary/10 transition-colors duration-150 ${- selectedLanguage === language.value- ? "bg-logo-primary/20 text-logo-primary font-semibold"- : ""- }`}- onClick={() => handleLanguageSelect(language.value)}- >- <div className="flex items-center justify-between">+ filteredLanguages.map((language) =>+ language.value === "auto" &&+ status?.kind === "detector_missing" ? (+ detector.downloading ? (+ <div+ key={language.value}+ className="flex items-center justify-between gap-2 px-2 py-1 text-sm text-ink-3"+ >+ <span className="truncate">{language.label}</span>+ <LanguageDetectorDownload+ downloading+ percent={detector.percent}+ onCancel={detector.cancel}+ />+ </div>+ ) : (+ // Like a model not downloaded yet: choosing it downloads it.+ <Tooltip+ key={language.value}+ title={t(+ "settings.general.language.detectorMissingTitle",+ )}+ text={language.note}+ className="w-full"+ >+ <button+ type="button"+ onClick={detector.download}+ className="group flex w-full items-center justify-between gap-2 px-2 py-1 text-sm text-ink-3 transition-colors duration-150 hover:bg-logo-primary/10 hover:text-text"+ >+ <span className="truncate">{language.label}</span>+ <LanguageDetectorDownload+ downloading={false}+ percent={0}+ />+ </button>+ </Tooltip>+ )+ ) : language.disabled ? (+ <div+ key={language.value}+ className="flex items-center justify-between gap-2 px-2 py-1 text-sm text-ink-3"+ ><span className="truncate">{language.label}</span>+ {language.note && (+ <InfoTooltip+ title={t(+ "settings.general.language.autoUnavailable.title",+ )}+ text={language.note}+ />+ )}</div>- </button>- ))+ ) : (+ <button+ key={language.value}+ type="button"+ className={`w-full px-2 py-1 text-sm text-start transition-colors duration-150 ${+ selectedLanguage === language.value+ ? "bg-logo-primary/20 text-logo-primary font-semibold"+ : "hover:bg-logo-primary/10"+ }`}+ onClick={() => handleLanguageSelect(language.value)}+ >+ <span className="block truncate">{language.label}</span>+ </button>+ ),+ ))}</div></div>diff --git a/src/components/settings/advanced/AdvancedSettings.tsx b/src/components/settings/advanced/AdvancedSettings.tsxindex 6d29b97a..9fd0d261 100644--- a/src/components/settings/advanced/AdvancedSettings.tsx+++ b/src/components/settings/advanced/AdvancedSettings.tsx@@ -20,6 +20,7 @@ import { useSettings } from "../../../hooks/useSettings";import { KeyboardImplementationSelector } from "../debug/KeyboardImplementationSelector";import { VoiceActivityDetection } from "../VoiceActivityDetection";import { LongFormChunking } from "../LongFormChunking";+import { LanguageDetection } from "../LanguageDetection";import { AccelerationSelector } from "../AccelerationSelector";import { LazyStreamClose } from "../LazyStreamClose";import { FillerWordRemoval } from "../FillerWordRemoval";@@ -74,6 +75,7 @@ export const AdvancedSettings: React.FC = () => {<AccelerationSelector descriptionMode="tooltip" grouped={true} /><LazyStreamClose descriptionMode="tooltip" grouped={true} /><VadBackendSelector descriptionMode="tooltip" grouped={true} />+ <LanguageDetection descriptionMode="tooltip" grouped={true} /></SettingsGroup>)}</div>diff --git a/src/components/settings/debug/DebugSettings.tsx b/src/components/settings/debug/DebugSettings.tsxindex fc41acb2..139d8496 100644--- a/src/components/settings/debug/DebugSettings.tsx+++ b/src/components/settings/debug/DebugSettings.tsx@@ -7,6 +7,7 @@ import { PasteDelay } from "./PasteDelay";import { HoldThreshold } from "./HoldThreshold";import { ReliablePasteToggle } from "./ReliablePaste";import { RecordingBuffer } from "./RecordingBuffer";+import { LanguageDetectionWindow } from "./LanguageDetectionWindow";import { SettingsGroup } from "../../ui/SettingsGroup";import { AlwaysOnMicrophone } from "../AlwaysOnMicrophone";import { SoundPicker } from "../SoundPicker";@@ -69,6 +70,7 @@ export const DebugSettings: React.FC<DebugSettingsProps> = ({<ReliablePasteToggle descriptionMode="tooltip" grouped={true} /><HoldThreshold descriptionMode="tooltip" grouped={true} /><RecordingBuffer descriptionMode="tooltip" grouped={true} />+ <LanguageDetectionWindow descriptionMode="tooltip" grouped={true} /><AlwaysOnMicrophone descriptionMode="tooltip" grouped={true} /><ClamshellMicrophoneSelector descriptionMode="tooltip" grouped={true} /><KeyboardDiagnostic />diff --git a/src/components/settings/debug/LanguageDetectionWindow.tsx b/src/components/settings/debug/LanguageDetectionWindow.tsxnew file mode 100644index 00000000..fd881ecf--- /dev/null+++ b/src/components/settings/debug/LanguageDetectionWindow.tsx@@ -0,0 +1,35 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { Slider } from "../../ui/Slider";+import { useSettings } from "../../../hooks/useSettings";++interface LanguageDetectionWindowProps {+ descriptionMode?: "tooltip" | "inline";+ grouped?: boolean;+}++export const LanguageDetectionWindow: React.FC<+ LanguageDetectionWindowProps+> = ({ descriptionMode = "tooltip", grouped = false }) => {+ const { t } = useTranslation();+ const { settings, updateSetting, resetSetting, isUpdating } = useSettings();++ return (+ <Slider+ value={settings?.language_detection_window_secs ?? 5}+ onChange={(value) =>+ updateSetting("language_detection_window_secs", value)+ }+ onReset={() => resetSetting("language_detection_window_secs")}+ isResetting={isUpdating("language_detection_window_secs")}+ min={2}+ max={30}+ step={1}+ label={t("settings.debug.languageDetectionWindow.title")}+ description={t("settings.debug.languageDetectionWindow.description")}+ descriptionMode={descriptionMode}+ grouped={grouped}+ formatValue={(v) => `${v}s`}+ />+ );+};diff --git a/src/components/settings/general/ModelSettingsCard.tsx b/src/components/settings/general/ModelSettingsCard.tsxindex 03d8b1b1..19f1ef9f 100644--- a/src/components/settings/general/ModelSettingsCard.tsx+++ b/src/components/settings/general/ModelSettingsCard.tsx@@ -32,10 +32,8 @@ export const ModelSettingsCard: React.FC = () => {<LanguageSelectordescriptionMode="tooltip"grouped={true}+ modelId={currentModelInfo.id}supportedLanguages={currentModelInfo.supported_languages}- supportsLanguageDetection={- currentModelInfo.supports_language_detection- }/>)}{supportsTranslation && (diff --git a/src/components/settings/models/ModelRow.tsx b/src/components/settings/models/ModelRow.tsxindex da64748d..82a91c72 100644--- a/src/components/settings/models/ModelRow.tsx+++ b/src/components/settings/models/ModelRow.tsx@@ -1,6 +1,7 @@import React, { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { ArrowDown, Loader2, Lock, Trash2, X } from "lucide-react";+import { Loader2, Lock, Trash2, X } from "lucide-react";+import { DownloadMark } from "@/components/shared/DownloadMark";import { Radio } from "@/components/ui/Radio";import { Button } from "@/components/ui/Button";import { ModelTableRow } from "@/components/shared/modelTable/ModelTableRow";@@ -62,14 +63,7 @@ export const ModelRow: React.FC<{ entry: Entry }> = ({ entry }) => {/>);case "remote":- return (- <span- aria-hidden="true"- className="grid size-[18px] place-items-center rounded-full border-[1.5px] border-dashed border-line-strong text-ink-3 transition-colors group-hover:border-solid group-hover:border-text group-hover:text-text"- >- <ArrowDown className="size-[11px]" strokeWidth={2.75} />- </span>- );+ return <DownloadMark />;default:return null;}diff --git a/src/components/shared/DownloadMark.tsx b/src/components/shared/DownloadMark.tsxnew file mode 100644index 00000000..aeb21958--- /dev/null+++ b/src/components/shared/DownloadMark.tsx@@ -0,0 +1,19 @@+import React from "react";+import { ArrowDown } from "lucide-react";++/**+ * Marks something not downloaded yet; turns solid while its `group` row is+ * hovered, in the accent color on rows that highlight in it.+ */+export const DownloadMark: React.FC<{ accent?: boolean }> = ({ accent }) => (+ <span+ aria-hidden="true"+ className={`grid size-[18px] shrink-0 place-items-center rounded-full border-[1.5px] border-dashed border-line-strong text-ink-3 transition-colors group-hover:border-solid ${+ accent+ ? "group-hover:border-logo-primary group-hover:text-logo-primary"+ : "group-hover:border-text group-hover:text-text"+ }`}+ >+ <ArrowDown className="size-[11px]" strokeWidth={2.75} />+ </span>+);diff --git a/src/components/ui/InfoTooltip.tsx b/src/components/ui/InfoTooltip.tsxnew file mode 100644index 00000000..083b1e87--- /dev/null+++ b/src/components/ui/InfoTooltip.tsx@@ -0,0 +1,38 @@+import React from "react";+import { Tooltip } from "./Tooltip";++interface InfoTooltipProps {+ title?: React.ReactNode;+ text: React.ReactNode;+ placement?: "above" | "below";+}++/** An info icon that explains something in a tooltip. */+export const InfoTooltip: React.FC<InfoTooltipProps> = ({+ title,+ text,+ placement = "above",+}) => (+ <Tooltip title={title} text={text} placement={placement} showOnPress>+ <button+ type="button"+ aria-label="More information"+ className="grid cursor-help text-ink-3 transition-colors duration-200 hover:text-logo-primary"+ >+ <svg+ className="w-4 h-4"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ aria-hidden="true"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"+ />+ </svg>+ </button>+ </Tooltip>+);diff --git a/src/components/ui/SettingContainer.tsx b/src/components/ui/SettingContainer.tsxindex 9707841c..913e331b 100644--- a/src/components/ui/SettingContainer.tsx+++ b/src/components/ui/SettingContainer.tsx@@ -1,5 +1,5 @@import React from "react";-import { Tooltip } from "./Tooltip";+import { InfoTooltip } from "./InfoTooltip";interface SettingContainerProps {title: string;@@ -23,31 +23,10 @@ export const SettingContainer: React.FC<SettingContainerProps> = ({tooltipPosition = "top",}) => {const info = (- <Tooltip+ <InfoTooltiptext={description}placement={tooltipPosition === "bottom" ? "below" : "above"}- >- <button- type="button"- aria-label="More information"- className="grid cursor-help text-ink-3 transition-colors duration-200 hover:text-logo-primary"- >- <svg- className="w-4 h-4"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- aria-hidden="true"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"- />- </svg>- </button>- </Tooltip>+ />);const containerClasses = groupeddiff --git a/src/components/ui/Tooltip.tsx b/src/components/ui/Tooltip.tsxindex ecacf260..2de9e95e 100644--- a/src/components/ui/Tooltip.tsx+++ b/src/components/ui/Tooltip.tsx@@ -16,6 +16,8 @@ interface TooltipProps {children: React.ReactElement<{ "aria-describedby"?: string }>;/** Where it goes when there's room; it flips when there isn't. */placement?: "above" | "below";+ /** Pressing shows it at once, for an element that only explains; otherwise a press hides it. */+ showOnPress?: boolean;className?: string;}@@ -33,6 +35,7 @@ export const Tooltip: React.FC<TooltipProps> = ({text,children,placement = "above",+ showOnPress = false,className = "",}) => {const id = useId();@@ -107,7 +110,7 @@ export const Tooltip: React.FC<TooltipProps> = ({className={`inline-grid ${className}`}onPointerEnter={(e) => e.pointerType === "mouse" && show()}onPointerLeave={hide}- onPointerDown={hide}+ onPointerDown={() => (showOnPress ? show(true) : hide())}onFocus={(e) => e.target.matches(":focus-visible") && show(true)}onBlur={hide}>diff --git a/src/components/ui/index.ts b/src/components/ui/index.tsindex f855d11e..60771b41 100644--- a/src/components/ui/index.ts+++ b/src/components/ui/index.ts@@ -7,3 +7,4 @@ export { SettingsGroup } from "./SettingsGroup";export { TextDisplay } from "./TextDisplay";export { Textarea } from "./Textarea";export { Tooltip } from "./Tooltip";+export { InfoTooltip } from "./InfoTooltip";diff --git a/src/hooks/useLanguageDetector.ts b/src/hooks/useLanguageDetector.tsnew file mode 100644index 00000000..733400ab--- /dev/null+++ b/src/hooks/useLanguageDetector.ts@@ -0,0 +1,63 @@+import { useCallback, useEffect, useState } from "react";+import { listen } from "@tauri-apps/api/event";+import { commands } from "@/bindings";+import { LANGUAGE_DETECTION_MODEL, modelFile } from "@handy-computer/models";+import { useModelStore } from "@/stores/modelStore";+import { BYTES_PER_MB, formatModelSize } from "@/lib/utils/format";++/** Download id of the language detector (`LANGUAGE_DETECTOR_ID` in Rust). */+export const LANGUAGE_DETECTOR_ID = "language-detector";++/** The size of the detector file the backend fetches. */+export const LANGUAGE_DETECTOR_SIZE = formatModelSize(+ modelFile(LANGUAGE_DETECTION_MODEL).size / BYTES_PER_MB,+);++/** The language detector's download state, shared everywhere it's offered. */+export const useLanguageDetector = () => {+ const [downloaded, setDownloaded] = useState<boolean | null>(null);+ const [starting, setStarting] = useState(false);+ const progress = useModelStore(+ (state) => state.downloadProgress[LANGUAGE_DETECTOR_ID],+ );++ const refresh = useCallback(+ () => commands.isLanguageDetectorDownloaded().then(setDownloaded),+ [],+ );++ useEffect(() => {+ refresh();+ // A model download can bring the detector along, so any completion+ // may change it.+ const unlisten = listen("model-download-complete", refresh);+ return () => {+ unlisten.then((stop) => stop());+ };+ }, [refresh]);++ const download = useCallback(async () => {+ setStarting(true);+ try {+ // Failure toasts from the model store's download-failed listener.+ await commands.downloadLanguageDetector();+ } finally {+ setStarting(false);+ }+ await refresh();+ }, [refresh]);++ // Stops at once in the UI; the next download resumes where this one ended.+ const cancel = useCallback(() => {+ setStarting(false);+ return useModelStore.getState().cancelDownload(LANGUAGE_DETECTOR_ID);+ }, []);++ return {+ downloaded,+ downloading: starting || progress !== undefined,+ percent: Math.round(progress?.percentage ?? 0),+ download,+ cancel,+ };+};diff --git a/src/i18n/locales/ar/translation.json b/src/i18n/locales/ar/translation.jsonindex 497aaa5e..4088f5da 100644--- a/src/i18n/locales/ar/translation.json+++ b/src/i18n/locales/ar/translation.json@@ -356,7 +356,16 @@"description": ".اختر لغة التعرف على الكلام. سيحدد 'تلقائي' اللغة تلقائياً، بينما يؤدي اختيار لغة معينة إلى تحسين الدقة لتلك اللغة","searchPlaceholder": "البحث عن اللغات...","noResults": "لم يتم العثور على لغات",- "auto": "تلقائي"+ "auto": "تلقائي",+ "autoUnavailable": {+ "title": "الوضع التلقائي معطّل",+ "oneLanguage": "لغة واحدة فقط من لغاتك تعمل مع هذا النموذج",+ "undetectable": "غير متاح مع {{languages}}",+ "noMatch": "لا تعمل أي من لغاتك مع هذا النموذج"+ },+ "detectorMissingTitle": "يحتاج الوضع التلقائي إلى تنزيل منفصل",+ "detectorMissing": "لا يستطيع هذا النموذج معرفة اللغة التي تتحدث بها. يحتاج الوضع التلقائي إلى أداة صغيرة لاكتشاف اللغة لمعرفتها",+ "stopDetectorDownload": "إيقاف تنزيل أداة اكتشاف اللغة"},"preferredLanguages": {"title": "اللغات المفضلة",@@ -583,6 +592,12 @@"title": "تقسيم الصوت الطويل","description": "يقسّم التسجيلات الطويلة عند فترات التوقف قبل نسخها، مما يحسّن أداء النسخ عادةً. تُقسَّم الملفات المنسوخة وعمليات إعادة النسخ الطويلة دائمًا."},+ "languageDetection": {+ "title": "قصر الوضع التلقائي على لغاتي",+ "description": "يختار الوضع التلقائي من لغاتك المفضلة فقط، باستخدام أداة صغيرة لاكتشاف اللغة. فعّل هذا إذا ظل الوضع التلقائي يختار لغة لا تتحدثها",+ "downloadHint": "يؤدي تفعيل هذا إلى تنزيل أداة صغيرة لاكتشاف اللغة",+ "downloadingHint": "جارٍ تنزيل أداة اكتشاف اللغة. أوقف هذا الخيار للإلغاء"+ },"vadBackend": {"title": "محرك كشف النشاط الصوتي","description": "اختر الكاشف المستخدم لتصفية الصمت. Earshot تجريبي؛ ارجع إلى Silero إذا تم اقتطاع الكلام أو الاحتفاظ بالضوضاء.",@@ -823,6 +838,10 @@"title": "مخزن التسجيل الإضافي","description": "وقت إضافي (بالمللي ثانية) للاستمرار في التسجيل بعد تحرير المفتاح، لالتقاط الصوت المتبقي. 0 = لا مخزن إضافي."},+ "languageDetectionWindow": {+ "title": "صوت اكتشاف اللغة",+ "description": "عدد ثواني الكلام التي تسمعها أداة اكتشاف اللغة. المدة الأطول أدق لكنها أبطأ."+ },"keyboardDiagnostic": {"title": "تشخيص لوحة المفاتيح","description": "يتحقق مما إذا كانت أحداث لوحة المفاتيح تصل إلى Handy. يُسجَّل عدد الأحداث فقط — ولا تُسجَّل أبدًا المفاتيح التي تضغط عليها.",diff --git a/src/i18n/locales/bg/translation.json b/src/i18n/locales/bg/translation.jsonindex fd821ed3..06c65794 100644--- a/src/i18n/locales/bg/translation.json+++ b/src/i18n/locales/bg/translation.json@@ -356,7 +356,16 @@"description": "Изберете езика за разпознаване на реч. „Автоматично“ определя езика сам, а изборът на конкретен език може да подобри точността за него.","searchPlaceholder": "Търсене на езици...","noResults": "Няма намерени езици",- "auto": "Автоматично"+ "auto": "Автоматично",+ "autoUnavailable": {+ "title": "Автоматично е изключено",+ "oneLanguage": "Само един от вашите езици работи с този модел",+ "undetectable": "Не е налично с {{languages}}",+ "noMatch": "Нито един от вашите езици не работи с този модел"+ },+ "detectorMissingTitle": "Автоматично изисква отделно изтегляне",+ "detectorMissing": "Този модел не може да разпознае на какъв език говорите. Автоматично се нуждае от малък детектор на език, за да го разпознае",+ "stopDetectorDownload": "Спри изтеглянето на детектора на език"},"preferredLanguages": {"title": "Предпочитани езици",@@ -583,6 +592,12 @@"title": "Разделяне на дълго аудио","description": "Разделя дългите записи на паузите преди транскрибиране, което обикновено подобрява качеството на транскрипцията. Транскрибираните файлове и дългите повторни транскрипции винаги се разделят."},+ "languageDetection": {+ "title": "Ограничи „Автоматично“ до моите езици",+ "description": "„Автоматично“ избира само от предпочитаните ви езици с помощта на малък детектор на език. Включете това, ако „Автоматично“ постоянно избира език, на който не говорите",+ "downloadHint": "Включването изтегля малък детектор на език",+ "downloadingHint": "Детекторът на език се изтегля. Изключете, за да откажете"+ },"vadBackend": {"title": "Бекенд за откриване на глас","description": "Изберете детектора, използван за филтриране на тишината. Earshot е експериментален; върнете се към Silero, ако речта се отрязва или шумът се запазва.",@@ -823,6 +838,10 @@"title": "Допълнителен буфер на записа","description": "Допълнително време (в милисекунди) за запис след пускане на клавиша, за да се улови краят на аудиото. 0 = без допълнителен буфер."},+ "languageDetectionWindow": {+ "title": "Аудио за разпознаване на език",+ "description": "Секунди реч, които детекторът на език чува. По-дълго е по-точно, но по-бавно."+ },"keyboardDiagnostic": {"title": "Диагностика на клавиатурата","description": "Проверява дали клавиатурните събития достигат до Handy. Записва се само броят на събитията — никога кои клавиши натискате.",diff --git a/src/i18n/locales/ca/translation.json b/src/i18n/locales/ca/translation.jsonindex 2e60fd93..c0c807ee 100644--- a/src/i18n/locales/ca/translation.json+++ b/src/i18n/locales/ca/translation.json@@ -356,7 +356,16 @@"description": "Seleccioneu la llengua per al reconeixement de la parla. L'opció automàtica detecta la llengua, mentre que seleccionar-ne una d'específica pot millorar-ne la precisió.","searchPlaceholder": "Cerca llengües...","noResults": "No s'ha trobat cap llengua",- "auto": "Automàtica"+ "auto": "Automàtica",+ "autoUnavailable": {+ "title": "Automàtica està desactivada",+ "oneLanguage": "Només una de les teves llengües funciona amb aquest model",+ "undetectable": "No disponible amb {{languages}}",+ "noMatch": "Cap de les teves llengües funciona amb aquest model"+ },+ "detectorMissingTitle": "Automàtica necessita una baixada a part",+ "detectorMissing": "Aquest model no pot saber en quin idioma parles. Automàtica necessita un petit detector d'idioma per esbrinar-ho",+ "stopDetectorDownload": "Atura la baixada del detector d'idioma"},"preferredLanguages": {"title": "Llengües preferides",@@ -583,6 +592,12 @@"title": "Divisió d'àudio llarg","description": "Divideix els enregistraments llargs a les pauses abans de transcriure'ls, cosa que normalment millora el rendiment de la transcripció. Els fitxers transcrits i les retranscripcions llargues sempre es divideixen."},+ "languageDetection": {+ "title": "Limita Automàtica als meus idiomes",+ "description": "Automàtica només tria entre els teus idiomes preferits, amb un petit detector d'idioma. Activa-ho si Automàtica tria sovint un idioma que no parles",+ "downloadHint": "Activar-ho baixa un petit detector d'idioma",+ "downloadingHint": "S'està baixant el detector d'idioma. Desactiva-ho per cancel·lar"+ },"vadBackend": {"title": "Motor de detecció d'activitat de veu","description": "Trieu el detector utilitzat per filtrar els silencis. L'Earshot és experimental; torneu al Silero si es corta la parla o es conserva el soroll.",@@ -823,6 +838,10 @@"title": "Marge addicional d'enregistrament","description": "Temps addicional (en mil·lisegons) durant el qual es continua enregistrant després de deixar anar la tecla per capturar l'àudio final. 0 = sense marge addicional."},+ "languageDetectionWindow": {+ "title": "Àudio de detecció d'idioma",+ "description": "Segons de veu que escolta el detector d'idioma. Més llarg és més precís però més lent."+ },"keyboardDiagnostic": {"title": "Diagnòstic del teclat","description": "Comprova si els esdeveniments del teclat arriben al Handy. Només se'n registra el recompte, mai les tecles que premeu.",diff --git a/src/i18n/locales/cs/translation.json b/src/i18n/locales/cs/translation.jsonindex 11df6077..e3e6fbba 100644--- a/src/i18n/locales/cs/translation.json+++ b/src/i18n/locales/cs/translation.json@@ -356,7 +356,16 @@"description": "Vyberte jazyk rozpoznávání řeči. Auto jazyk určí automaticky, zatímco výběr konkrétního jazyka může zlepšit přesnost.","searchPlaceholder": "Hledat jazyky...","noResults": "Žádné jazyky nenalezeny",- "auto": "Automaticky"+ "auto": "Automaticky",+ "autoUnavailable": {+ "title": "Automaticky je vypnuto",+ "oneLanguage": "S tímto modelem funguje jen jeden z vašich jazyků",+ "undetectable": "Není k dispozici pro {{languages}}",+ "noMatch": "Žádný z vašich jazyků s tímto modelem nefunguje"+ },+ "detectorMissingTitle": "Automaticky vyžaduje samostatné stažení",+ "detectorMissing": "Tento model nepozná, jakým jazykem mluvíte. Režim Automaticky potřebuje malý detektor jazyka, který to zjistí",+ "stopDetectorDownload": "Zastavit stahování detektoru jazyka"},"preferredLanguages": {"title": "Preferované jazyky",@@ -583,6 +592,12 @@"title": "Dělení dlouhého zvuku","description": "Před přepisem rozdělí dlouhé nahrávky v pauzách, což obvykle zlepšuje kvalitu přepisu. Přepisované soubory a dlouhé opakované přepisy se rozdělují vždy."},+ "languageDetection": {+ "title": "Omezit Automaticky na mé jazyky",+ "description": "Automaticky vybírá jen z vašich preferovaných jazyků pomocí malého detektoru jazyka. Zapněte to, pokud Automaticky stále volí jazyk, kterým nemluvíte",+ "downloadHint": "Zapnutím se stáhne malý detektor jazyka",+ "downloadingHint": "Stahuje se detektor jazyka. Vypnutím stahování zrušíte"+ },"vadBackend": {"title": "Backend detekce hlasu","description": "Vyberte detektor používaný k filtrování ticha. Earshot je experimentální; pokud je řeč ořezávána nebo zůstává šum, přepněte zpět na Silero.",@@ -823,6 +838,10 @@"title": "Extra vyrovnávací paměť nahrávání","description": "Extra čas (v milisekundách) pro pokračování nahrávání po uvolnění klávesy, pro zachycení zbývajícího zvuku. 0 = žádná extra vyrovnávací paměť."},+ "languageDetectionWindow": {+ "title": "Zvuk pro rozpoznání jazyka",+ "description": "Kolik sekund řeči detektor jazyka slyší. Delší je přesnější, ale pomalejší."+ },"keyboardDiagnostic": {"title": "Diagnostika klávesnice","description": "Ověří, zda události klávesnice dorazí do Handy. Zaznamenává se pouze počet událostí — nikdy to, které klávesy stisknete.",diff --git a/src/i18n/locales/da/translation.json b/src/i18n/locales/da/translation.jsonindex 3a572c22..db7220ba 100644--- a/src/i18n/locales/da/translation.json+++ b/src/i18n/locales/da/translation.json@@ -356,7 +356,16 @@"description": "Vælg sproget til talegenkendelse. Auto tyder automatisk sproget, mens valg af et specifikt sprog kan forbedre nøjagtigheden for det pågældende sprog.","searchPlaceholder": "Søg efter sprog...","noResults": "Ingen sprog fundet",- "auto": "Automatisk"+ "auto": "Automatisk",+ "autoUnavailable": {+ "title": "Automatisk er slået fra",+ "oneLanguage": "Kun ét af dine sprog virker med denne model",+ "undetectable": "Ikke tilgængelig med {{languages}}",+ "noMatch": "Ingen af dine sprog virker med denne model"+ },+ "detectorMissingTitle": "Automatisk kræver en separat download",+ "detectorMissing": "Denne model kan ikke afgøre, hvilket sprog du taler. Automatisk har brug for en lille sprogregistrering til at finde ud af det",+ "stopDetectorDownload": "Stop download af sprogregistreringen"},"preferredLanguages": {"title": "Foretrukne sprog",@@ -583,6 +592,12 @@"title": "Opdeling af lang lyd","description": "Deler lange optagelser ved pauser før transskribering, hvilket typisk forbedrer transskriptionen. Transskriberede filer og lange gentransskriberinger deles altid."},+ "languageDetection": {+ "title": "Begræns Automatisk til mine sprog",+ "description": "Automatisk vælger kun blandt dine foretrukne sprog ved hjælp af en lille sprogregistrering. Slå det til, hvis Automatisk bliver ved med at vælge et sprog, du ikke taler",+ "downloadHint": "Når du slår det til, downloades en lille sprogregistrering",+ "downloadingHint": "Sprogregistreringen downloades. Slå det fra for at annullere"+ },"vadBackend": {"title": "Stemmedetektions-backend","description": "Vælg den detektor, der bruges til at filtrere stilhed. Earshot er eksperimentel; skift tilbage til Silero, hvis tale klippes eller støj bevares.",@@ -823,6 +838,10 @@"title": "Ekstra optagelsesbuffer","description": "Ekstra tid (i millisekunder) til at fortsætte optagelsen, efter du slipper tasten, for at fange efterfølgende lyd. 0 = ingen ekstra buffer."},+ "languageDetectionWindow": {+ "title": "Lyd til sprogregistrering",+ "description": "Sekunder tale, som sprogregistreringen hører. Længere er mere præcist, men langsommere."+ },"keyboardDiagnostic": {"title": "Tastaturdiagnostik","description": "Kontrollerer, om tastaturhændelser når frem til Handy. Kun antallet af hændelser registreres — aldrig hvilke taster du trykker på.",diff --git a/src/i18n/locales/de/translation.json b/src/i18n/locales/de/translation.jsonindex dccf1c04..a8f18c6c 100644--- a/src/i18n/locales/de/translation.json+++ b/src/i18n/locales/de/translation.json@@ -356,7 +356,16 @@"description": "Wähle die Sprache für die Spracherkennung. Auto erkennt die Sprache automatisch, die Auswahl einer bestimmten Sprache kann die Genauigkeit verbessern.","searchPlaceholder": "Sprachen suchen...","noResults": "Keine Sprachen gefunden",- "auto": "Automatisch"+ "auto": "Automatisch",+ "autoUnavailable": {+ "title": "Automatisch ist deaktiviert",+ "oneLanguage": "Nur eine deiner Sprachen funktioniert mit diesem Modell",+ "undetectable": "Nicht verfügbar mit {{languages}}",+ "noMatch": "Keine deiner Sprachen funktioniert mit diesem Modell"+ },+ "detectorMissingTitle": "Automatisch braucht einen separaten Download",+ "detectorMissing": "Dieses Modell erkennt nicht, welche Sprache du sprichst. Automatisch braucht eine kleine Spracherkennung, die das herausfindet",+ "stopDetectorDownload": "Download der Spracherkennung stoppen"},"preferredLanguages": {"title": "Bevorzugte Sprachen",@@ -583,6 +592,12 @@"title": "Lange Aufnahmen aufteilen","description": "Teilt lange Aufnahmen vor der Transkription an Sprechpausen auf, was die Transkription in der Regel verbessert. Transkribierte Dateien und lange erneute Transkriptionen werden immer aufgeteilt."},+ "languageDetection": {+ "title": "Automatisch auf meine Sprachen beschränken",+ "description": "Automatisch wählt nur aus deinen bevorzugten Sprachen, mithilfe einer kleinen Spracherkennung. Schalte das ein, wenn Automatisch immer wieder eine Sprache wählt, die du nicht sprichst",+ "downloadHint": "Beim Einschalten wird eine kleine Spracherkennung heruntergeladen",+ "downloadingHint": "Die Spracherkennung wird heruntergeladen. Zum Abbrechen ausschalten"+ },"vadBackend": {"title": "VAD-Backend","description": "Wählt den Detektor zum Herausfiltern von Stille. Earshot ist experimentell; wechseln Sie zurück zu Silero, wenn Sprache abgeschnitten oder Rauschen beibehalten wird.",@@ -823,6 +838,10 @@"title": "Zusätzlicher Aufnahmepuffer","description": "Zusätzliche Zeit (in Millisekunden), um nach dem Loslassen der Taste weiter aufzunehmen, um nachlaufendes Audio zu erfassen. 0 = kein zusätzlicher Puffer."},+ "languageDetectionWindow": {+ "title": "Audio für Spracherkennung",+ "description": "Sekunden Sprache, die die Spracherkennung hört. Länger ist genauer, aber langsamer."+ },"keyboardDiagnostic": {"title": "Tastatur-Diagnose","description": "Prüft, ob Tastaturereignisse Handy erreichen. Es wird nur die Anzahl der Ereignisse erfasst — niemals, welche Tasten du drückst.",diff --git a/src/i18n/locales/en/translation.json b/src/i18n/locales/en/translation.jsonindex 199ea2d2..96bb5ec8 100644--- a/src/i18n/locales/en/translation.json+++ b/src/i18n/locales/en/translation.json@@ -356,7 +356,16 @@"description": "Select the language for speech recognition. Auto will automatically determine the language, while selecting a specific language can improve accuracy for that language.","searchPlaceholder": "Search languages...","noResults": "No languages found",- "auto": "Auto"+ "auto": "Auto",+ "autoUnavailable": {+ "title": "Auto is disabled",+ "oneLanguage": "Only one of your languages works with this model",+ "undetectable": "Not available with {{languages}}",+ "noMatch": "None of your languages work with this model"+ },+ "detectorMissingTitle": "Auto needs a separate download",+ "detectorMissing": "This model can't tell which language you're speaking. Auto needs a small language detector to figure it out",+ "stopDetectorDownload": "Stop downloading the language detector"},"preferredLanguages": {"title": "Preferred Languages",@@ -583,6 +592,12 @@"title": "Long Audio Chunking","description": "Splits long recordings at pauses before transcribing, which typically improves transcription performance. Transcribed files and long re-transcriptions are always split."},+ "languageDetection": {+ "title": "Limit Auto to My Languages",+ "description": "Auto only picks from your preferred languages, using a small language detector. Turn this on if Auto keeps choosing a language you don't speak",+ "downloadHint": "Turning this on downloads a small language detector",+ "downloadingHint": "Downloading the language detector. Turn this off to cancel"+ },"vadBackend": {"title": "Voice Activity Backend","description": "Choose the detector used to filter silence. Earshot is experimental; switch back to Silero if speech is clipped or noise is retained.",@@ -823,6 +838,10 @@"title": "Extra Recording Buffer","description": "Extra time (in milliseconds) to keep recording after you release the key, to capture trailing audio. 0 = no extra buffer."},+ "languageDetectionWindow": {+ "title": "Language Detection Audio",+ "description": "Seconds of speech the language detector hears. Longer is more accurate but slower."+ },"keyboardDiagnostic": {"title": "Keyboard Diagnostic","description": "Checks whether keyboard events reach Handy. Only event counts are recorded — never which keys you press.",diff --git a/src/i18n/locales/es/translation.json b/src/i18n/locales/es/translation.jsonindex 7e7720e2..985f9bd9 100644--- a/src/i18n/locales/es/translation.json+++ b/src/i18n/locales/es/translation.json@@ -356,7 +356,16 @@"description": "Selecciona el idioma para el reconocimiento de voz. Auto detectará automáticamente el idioma, mientras que seleccionar un idioma específico puede mejorar la precisión para ese idioma.","searchPlaceholder": "Buscar idiomas...","noResults": "No se encontraron idiomas",- "auto": "Automático"+ "auto": "Automático",+ "autoUnavailable": {+ "title": "Automático está desactivado",+ "oneLanguage": "Solo uno de tus idiomas funciona con este modelo",+ "undetectable": "No disponible con {{languages}}",+ "noMatch": "Ninguno de tus idiomas funciona con este modelo"+ },+ "detectorMissingTitle": "Automático necesita una descarga aparte",+ "detectorMissing": "Este modelo no puede saber qué idioma hablas. Automático necesita un pequeño detector de idioma para averiguarlo",+ "stopDetectorDownload": "Detener la descarga del detector de idioma"},"preferredLanguages": {"title": "Idiomas preferidos",@@ -583,6 +592,12 @@"title": "División de audio largo","description": "Divide las grabaciones largas en las pausas antes de transcribirlas, lo que normalmente mejora el rendimiento de la transcripción. Los archivos transcritos y las re-transcripciones largas siempre se dividen."},+ "languageDetection": {+ "title": "Limitar Automático a mis idiomas",+ "description": "Automático solo elige entre tus idiomas preferidos, usando un pequeño detector de idioma. Actívalo si Automático sigue eligiendo un idioma que no hablas",+ "downloadHint": "Al activarlo se descarga un pequeño detector de idioma",+ "downloadingHint": "Descargando el detector de idioma. Desactívalo para cancelar"+ },"vadBackend": {"title": "Backend de detección de voz","description": "Elige el detector usado para filtrar el silencio. Earshot es experimental; vuelve a Silero si la voz se recorta o se conserva el ruido.",@@ -823,6 +838,10 @@"title": "Búfer de grabación adicional","description": "Tiempo adicional (en milisegundos) para seguir grabando después de soltar la tecla, para capturar el audio restante. 0 = sin búfer adicional."},+ "languageDetectionWindow": {+ "title": "Audio de detección de idioma",+ "description": "Segundos de voz que escucha el detector de idioma. Más largo es más preciso pero más lento."+ },"keyboardDiagnostic": {"title": "Diagnóstico del teclado","description": "Comprueba si los eventos de teclado llegan a Handy. Solo se registra el número de eventos, nunca qué teclas pulsas.",diff --git a/src/i18n/locales/fr/translation.json b/src/i18n/locales/fr/translation.jsonindex 3d0e4d0a..2cf606ba 100644--- a/src/i18n/locales/fr/translation.json+++ b/src/i18n/locales/fr/translation.json@@ -356,7 +356,16 @@"description": "Sélectionnez la langue pour la reconnaissance vocale. Auto déterminera automatiquement la langue, tandis que sélectionner une langue spécifique peut améliorer la précision pour cette langue.","searchPlaceholder": "Rechercher des langues...","noResults": "Aucune langue trouvée",- "auto": "Automatique"+ "auto": "Automatique",+ "autoUnavailable": {+ "title": "Automatique est désactivé",+ "oneLanguage": "Une seule de vos langues fonctionne avec ce modèle",+ "undetectable": "Indisponible avec {{languages}}",+ "noMatch": "Aucune de vos langues ne fonctionne avec ce modèle"+ },+ "detectorMissingTitle": "Automatique nécessite un téléchargement séparé",+ "detectorMissing": "Ce modèle ne peut pas savoir quelle langue vous parlez. Automatique a besoin d'un petit détecteur de langue pour le déterminer",+ "stopDetectorDownload": "Arrêter le téléchargement du détecteur de langue"},"preferredLanguages": {"title": "Langues préférées",@@ -583,6 +592,12 @@"title": "Découpage des longs enregistrements","description": "Découpe les longs enregistrements aux pauses avant la transcription, ce qui améliore généralement la qualité de la transcription. Les fichiers transcrits et les longues re-transcriptions sont toujours découpés."},+ "languageDetection": {+ "title": "Limiter Automatique à mes langues",+ "description": "Automatique ne choisit que parmi vos langues préférées, grâce à un petit détecteur de langue. Activez cette option si Automatique choisit souvent une langue que vous ne parlez pas",+ "downloadHint": "L'activer télécharge un petit détecteur de langue",+ "downloadingHint": "Téléchargement du détecteur de langue. Désactivez pour annuler"+ },"vadBackend": {"title": "Backend de détection vocale","description": "Choisissez le détecteur utilisé pour filtrer le silence. Earshot est expérimental ; revenez à Silero si la parole est coupée ou si le bruit est conservé.",@@ -823,6 +838,10 @@"title": "Tampon d'enregistrement supplémentaire","description": "Temps supplémentaire (en millisecondes) pour continuer l'enregistrement après avoir relâché la touche, pour capturer l'audio restant. 0 = pas de tampon supplémentaire."},+ "languageDetectionWindow": {+ "title": "Audio de détection de la langue",+ "description": "Secondes de parole entendues par le détecteur de langue. Plus long est plus précis mais plus lent."+ },"keyboardDiagnostic": {"title": "Diagnostic du clavier","description": "Vérifie si les événements clavier atteignent Handy. Seul le nombre d'événements est enregistré, jamais les touches sur lesquelles vous appuyez.",diff --git a/src/i18n/locales/he/translation.json b/src/i18n/locales/he/translation.jsonindex c88a1d33..f8756fcf 100644--- a/src/i18n/locales/he/translation.json+++ b/src/i18n/locales/he/translation.json@@ -356,7 +356,16 @@"description": "בחר את שפת זיהוי הדיבור. מצב אוטומטי יזהה את השפה לבד, בעוד שבחירת שפה מסוימת יכולה לשפר את הדיוק עבורה.","searchPlaceholder": "חפש שפות...","noResults": "לא נמצאו שפות",- "auto": "אוטומטי"+ "auto": "אוטומטי",+ "autoUnavailable": {+ "title": "אוטומטי מושבת",+ "oneLanguage": "רק אחת מהשפות שלך עובדת עם המודל הזה",+ "undetectable": "לא זמין עם {{languages}}",+ "noMatch": "אף אחת מהשפות שלך לא עובדת עם המודל הזה"+ },+ "detectorMissingTitle": "אוטומטי דורש הורדה נפרדת",+ "detectorMissing": "המודל הזה לא יכול לזהות באיזו שפה מדברים. אוטומטי צריך גלאי שפה קטן כדי לזהות אותה",+ "stopDetectorDownload": "עצירת ההורדה של גלאי השפה"},"preferredLanguages": {"title": "שפות מועדפות",@@ -583,6 +592,12 @@"title": "פיצול שמע ארוך","description": "מפצל הקלטות ארוכות בהפסקות לפני התמלול, מה שבדרך כלל משפר את איכות התמלול. קבצים מתומללים ותמלולים חוזרים ארוכים מפוצלים תמיד."},+ "languageDetection": {+ "title": "הגבלת אוטומטי לשפות שלי",+ "description": "אוטומטי בוחר רק מתוך השפות המועדפות שלך, בעזרת גלאי שפה קטן. כדאי להפעיל אם אוטומטי ממשיך לבחור שפה שאינך מדבר",+ "downloadHint": "ההפעלה מורידה גלאי שפה קטן",+ "downloadingHint": "גלאי השפה בהורדה. כבו כדי לבטל"+ },"vadBackend": {"title": "מנוע זיהוי פעילות קולית","description": "בחרו את הגלאי המשמש לסינון שקט. Earshot ניסיוני; חזרו ל-Silero אם הדיבור נחתך או שרעש נשמר.",@@ -823,6 +838,10 @@"title": "באפר הקלטה נוסף","description": "זמן נוסף (במילישניות) להמשך הקלטה אחרי שחרור המקש, כדי ללכוד סוף דיבור. 0 = בלי באפר נוסף."},+ "languageDetectionWindow": {+ "title": "שמע לזיהוי שפה",+ "description": "כמה שניות דיבור גלאי השפה שומע. ארוך יותר מדויק יותר אך איטי יותר."+ },"keyboardDiagnostic": {"title": "אבחון מקלדת","description": "בודק אם אירועי מקלדת מגיעים ל-Handy. נרשם רק מספר האירועים — לעולם לא אילו מקשים הקשת.",diff --git a/src/i18n/locales/hi/translation.json b/src/i18n/locales/hi/translation.jsonindex 2108622d..57026ec6 100644--- a/src/i18n/locales/hi/translation.json+++ b/src/i18n/locales/hi/translation.json@@ -356,7 +356,16 @@"description": "बोली पहचानने के लिए भाषा चुनें. 'ऑटो' अपने आप भाषा पहचान लेता है, जबकि कोई खास भाषा चुनने से उस भाषा की सटीकता बेहतर हो सकती है.","searchPlaceholder": "भाषाएं खोजें...","noResults": "कोई भाषा नहीं मिली",- "auto": "ऑटो"+ "auto": "ऑटो",+ "autoUnavailable": {+ "title": "ऑटो बंद है",+ "oneLanguage": "आपकी भाषाओं में से केवल एक ही इस मॉडल के साथ काम करती है",+ "undetectable": "{{languages}} के साथ उपलब्ध नहीं",+ "noMatch": "आपकी कोई भी भाषा इस मॉडल के साथ काम नहीं करती"+ },+ "detectorMissingTitle": "ऑटो के लिए अलग डाउनलोड चाहिए",+ "detectorMissing": "यह मॉडल नहीं पहचान सकता कि आप कौन-सी भाषा बोल रहे हैं। ऑटो को इसे पहचानने के लिए एक छोटे भाषा पहचानकर्ता की ज़रूरत है",+ "stopDetectorDownload": "भाषा पहचानकर्ता का डाउनलोड रोकें"},"preferredLanguages": {"title": "पसंदीदा भाषाएं",@@ -583,6 +592,12 @@"title": "लंबे ऑडियो का विभाजन","description": "ट्रांसक्राइब करने से पहले लंबी रिकॉर्डिंग को विरामों पर विभाजित करता है, जिससे आमतौर पर ट्रांसक्रिप्शन बेहतर होता है। ट्रांसक्राइब की गई फ़ाइलें और लंबे पुनः ट्रांसक्रिप्शन हमेशा विभाजित किए जाते हैं।"},+ "languageDetection": {+ "title": "ऑटो को मेरी भाषाओं तक सीमित करें",+ "description": "ऑटो एक छोटे भाषा पहचानकर्ता की मदद से सिर्फ़ आपकी पसंदीदा भाषाओं में से चुनता है। अगर ऑटो बार-बार ऐसी भाषा चुनता है जो आप नहीं बोलते, तो इसे चालू करें",+ "downloadHint": "इसे चालू करने पर एक छोटा भाषा पहचानकर्ता डाउनलोड होता है",+ "downloadingHint": "भाषा पहचानकर्ता डाउनलोड हो रहा है। रद्द करने के लिए इसे बंद करें"+ },"vadBackend": {"title": "वॉइस एक्टिविटी बैकएंड","description": "मौन को फ़िल्टर करने के लिए उपयोग किया जाने वाला डिटेक्टर चुनें। Earshot प्रायोगिक है; यदि बोली कट रही हो या शोर बना रहे तो Silero पर वापस जाएँ।",@@ -823,6 +838,10 @@"title": "अतिरिक्त रिकॉर्डिंग बफ़र","description": "बटन छोड़ने के बाद भी रिकॉर्डिंग जारी रखने का अतिरिक्त समय (मिलीसेकंड में), ताकि आखिरी हिस्से का ऑडियो कैप्चर हो सके. 0 = कोई अतिरिक्त बफ़र नहीं."},+ "languageDetectionWindow": {+ "title": "भाषा पहचान ऑडियो",+ "description": "भाषा पहचानकर्ता कितने सेकंड की आवाज़ सुनता है। लंबा अधिक सटीक है पर धीमा।"+ },"keyboardDiagnostic": {"title": "कीबोर्ड डायग्नोस्टिक","description": "जाँचता है कि कीबोर्ड इवेंट Handy तक पहुँच रहे हैं या नहीं. सिर्फ़ इवेंट की गिनती रिकॉर्ड होती है — कभी नहीं कि आपने कौन-सी कुंजियाँ दबाईं.",diff --git a/src/i18n/locales/id/translation.json b/src/i18n/locales/id/translation.jsonindex 229932ac..d24ca285 100644--- a/src/i18n/locales/id/translation.json+++ b/src/i18n/locales/id/translation.json@@ -356,7 +356,16 @@"description": "Pilih bahasa untuk pengenalan ucapan. Opsi Otomatis akan mendeteksi bahasa, sedangkan memilih bahasa tertentu dapat meningkatkan akurasi untuk bahasa tersebut.","searchPlaceholder": "Cari bahasa...","noResults": "Bahasa tidak ditemukan",- "auto": "Otomatis"+ "auto": "Otomatis",+ "autoUnavailable": {+ "title": "Otomatis dinonaktifkan",+ "oneLanguage": "Hanya satu bahasa Anda yang berfungsi dengan model ini",+ "undetectable": "Tidak tersedia untuk {{languages}}",+ "noMatch": "Tidak ada bahasa Anda yang berfungsi dengan model ini"+ },+ "detectorMissingTitle": "Otomatis memerlukan unduhan terpisah",+ "detectorMissing": "Model ini tidak dapat mengenali bahasa yang Anda ucapkan. Otomatis memerlukan pendeteksi bahasa kecil untuk mengenalinya",+ "stopDetectorDownload": "Hentikan unduhan pendeteksi bahasa"},"preferredLanguages": {"title": "Bahasa Pilihan",@@ -583,6 +592,12 @@"title": "Pemisahan Audio Panjang","description": "Memisahkan rekaman panjang pada jeda sebelum ditranskripsi, yang biasanya meningkatkan kinerja transkripsi. File yang ditranskripsi dan transkripsi ulang yang panjang selalu dipisahkan."},+ "languageDetection": {+ "title": "Batasi Otomatis ke bahasa saya",+ "description": "Otomatis hanya memilih dari bahasa pilihan Anda, menggunakan pendeteksi bahasa kecil. Aktifkan jika Otomatis terus memilih bahasa yang tidak Anda gunakan",+ "downloadHint": "Mengaktifkan ini akan mengunduh pendeteksi bahasa kecil",+ "downloadingHint": "Mengunduh pendeteksi bahasa. Nonaktifkan untuk membatalkan"+ },"vadBackend": {"title": "Backend Deteksi Aktivitas Suara","description": "Pilih detektor yang digunakan untuk menyaring keheningan. Earshot bersifat eksperimental; kembali ke Silero jika ucapan terpotong atau kebisingan tetap terekam.",@@ -823,6 +838,10 @@"title": "Buffer Perekaman Tambahan","description": "Waktu tambahan (dalam milidetik) untuk terus merekam setelah Anda melepas tombol agar audio di bagian akhir tetap tertangkap. 0 = tanpa buffer tambahan."},+ "languageDetectionWindow": {+ "title": "Audio Deteksi Bahasa",+ "description": "Detik ucapan yang didengar pendeteksi bahasa. Lebih lama lebih akurat tetapi lebih lambat."+ },"keyboardDiagnostic": {"title": "Diagnostik Keyboard","description": "Memeriksa apakah peristiwa keyboard mencapai Handy. Hanya jumlah peristiwa yang dicatat — bukan tombol yang Anda tekan.",diff --git a/src/i18n/locales/it/translation.json b/src/i18n/locales/it/translation.jsonindex 7515cee5..fef0b31b 100644--- a/src/i18n/locales/it/translation.json+++ b/src/i18n/locales/it/translation.json@@ -356,7 +356,16 @@"description": "Scegli la lingua per il riconoscimento vocale. Auto la determinerà automaticamente, mentre scegliere una lingua specifica può migliorare l'accuratezza per quella lingua.","searchPlaceholder": "Cerca lingue...","noResults": "Nessuna lingua trovata",- "auto": "Automatico"+ "auto": "Automatico",+ "autoUnavailable": {+ "title": "Automatico è disattivato",+ "oneLanguage": "Solo una delle tue lingue funziona con questo modello",+ "undetectable": "Non disponibile con {{languages}}",+ "noMatch": "Nessuna delle tue lingue funziona con questo modello"+ },+ "detectorMissingTitle": "Automatico richiede un download separato",+ "detectorMissing": "Questo modello non riesce a capire quale lingua stai parlando. Automatico ha bisogno di un piccolo rilevatore di lingua per capirlo",+ "stopDetectorDownload": "Interrompi il download del rilevatore di lingua"},"preferredLanguages": {"title": "Lingue preferite",@@ -583,6 +592,12 @@"title": "Suddivisione dell'audio lungo","description": "Suddivide le registrazioni lunghe in corrispondenza delle pause prima della trascrizione, il che di solito migliora le prestazioni della trascrizione. I file trascritti e le ri-trascrizioni lunghe vengono sempre suddivisi."},+ "languageDetection": {+ "title": "Limita Automatico alle mie lingue",+ "description": "Automatico sceglie solo tra le tue lingue preferite, usando un piccolo rilevatore di lingua. Attivalo se Automatico continua a scegliere una lingua che non parli",+ "downloadHint": "Attivandolo si scarica un piccolo rilevatore di lingua",+ "downloadingHint": "Download del rilevatore di lingua in corso. Disattiva per annullare"+ },"vadBackend": {"title": "Backend di rilevamento vocale","description": "Scegli il rilevatore usato per filtrare il silenzio. Earshot è sperimentale; torna a Silero se il parlato viene tagliato o il rumore viene mantenuto.",@@ -823,6 +838,10 @@"title": "Buffer di registrazione extra","description": "Tempo extra (in millisecondi) per continuare a registrare dopo aver rilasciato il tasto, per catturare l'audio finale. 0 = nessun buffer extra."},+ "languageDetectionWindow": {+ "title": "Audio per il rilevamento della lingua",+ "description": "Secondi di parlato ascoltati dal rilevatore di lingua. Più lungo è più preciso ma più lento."+ },"keyboardDiagnostic": {"title": "Diagnostica tastiera","description": "Verifica se gli eventi della tastiera arrivano a Handy. Viene registrato solo il numero di eventi, mai quali tasti premi.",diff --git a/src/i18n/locales/ja/translation.json b/src/i18n/locales/ja/translation.jsonindex 8ec64a3b..f3901c33 100644--- a/src/i18n/locales/ja/translation.json+++ b/src/i18n/locales/ja/translation.json@@ -356,7 +356,16 @@"description": "音声認識の言語を選択してください。自動を選択すると言語を自動的に判定します。特定の言語を選択すると、その言語の精度が向上する場合があります。","searchPlaceholder": "言語を検索…","noResults": "言語が見つかりません",- "auto": "自動"+ "auto": "自動",+ "autoUnavailable": {+ "title": "自動は無効です",+ "oneLanguage": "このモデルで使えるのはあなたの言語のうち1つだけです",+ "undetectable": "{{languages}}では利用できません",+ "noMatch": "あなたの言語はどれもこのモデルで使えません"+ },+ "detectorMissingTitle": "自動には別のダウンロードが必要です",+ "detectorMissing": "このモデルは話している言語を判別できません。自動では小さな言語検出を使って判別します",+ "stopDetectorDownload": "言語検出のダウンロードを停止"},"preferredLanguages": {"title": "使用する言語",@@ -583,6 +592,12 @@"title": "長い音声の分割","description": "文字起こしの前に長い録音を無音部分で分割します。通常、文字起こしの精度が向上します。ファイルの文字起こしと長い再文字起こしは常に分割されます。"},+ "languageDetection": {+ "title": "自動を自分の言語に限定",+ "description": "自動は小さな言語検出を使い、優先言語の中からだけ選びます。自動が話していない言語を選び続ける場合はオンにしてください",+ "downloadHint": "オンにすると小さな言語検出がダウンロードされます",+ "downloadingHint": "言語検出をダウンロード中です。キャンセルするにはオフにしてください"+ },"vadBackend": {"title": "音声区間検出バックエンド","description": "無音のフィルタリングに使用する検出器を選択します。Earshot は実験的機能です。音声が途切れたりノイズが残る場合は Silero に戻してください。",@@ -823,6 +838,10 @@"title": "追加録音バッファ","description": "キーを離した後に録音を続ける追加時間(ミリ秒)。末尾の音声を捕捉するため。0 = 追加バッファなし。"},+ "languageDetectionWindow": {+ "title": "言語検出の音声",+ "description": "言語検出が聞く音声の秒数です。長いほど正確ですが遅くなります。"+ },"keyboardDiagnostic": {"title": "キーボード診断","description": "キーボードイベントが Handy に届いているかを確認します。記録されるのはイベント数のみで、押したキーの内容は記録されません。",diff --git a/src/i18n/locales/ko/translation.json b/src/i18n/locales/ko/translation.jsonindex 54a20196..10774627 100644--- a/src/i18n/locales/ko/translation.json+++ b/src/i18n/locales/ko/translation.json@@ -356,7 +356,16 @@"description": "음성 인식 언어를 선택하세요. 자동은 언어를 자동으로 감지하며, 특정 언어를 선택하면 해당 언어의 정확도가 향상될 수 있습니다.","searchPlaceholder": "언어 검색...","noResults": "언어를 찾을 수 없습니다",- "auto": "자동"+ "auto": "자동",+ "autoUnavailable": {+ "title": "자동이 꺼져 있습니다",+ "oneLanguage": "이 모델에서는 사용자 언어 중 하나만 사용할 수 있습니다",+ "undetectable": "{{languages}}에서는 사용할 수 없습니다",+ "noMatch": "이 모델에서 사용할 수 있는 언어가 없습니다"+ },+ "detectorMissingTitle": "자동을 사용하려면 별도 다운로드가 필요합니다",+ "detectorMissing": "이 모델은 어떤 언어로 말하는지 구별할 수 없습니다. 자동은 작은 언어 감지기로 언어를 알아냅니다",+ "stopDetectorDownload": "언어 감지기 다운로드 중지"},"preferredLanguages": {"title": "선호 언어",@@ -583,6 +592,12 @@"title": "긴 오디오 분할","description": "전사하기 전에 긴 녹음을 쉬는 구간에서 나눕니다. 일반적으로 전사 성능이 향상됩니다. 파일 전사와 긴 재전사는 항상 나누어 처리됩니다."},+ "languageDetection": {+ "title": "자동을 내 언어로 제한",+ "description": "자동이 작은 언어 감지기를 사용해 선호 언어 중에서만 고릅니다. 자동이 사용하지 않는 언어를 계속 고르면 켜세요",+ "downloadHint": "켜면 작은 언어 감지기를 다운로드합니다",+ "downloadingHint": "언어 감지기를 다운로드하는 중입니다. 취소하려면 끄세요"+ },"vadBackend": {"title": "음성 활동 감지 백엔드","description": "무음을 필터링하는 데 사용할 감지기를 선택합니다. Earshot은 실험적 기능입니다. 음성이 잘리거나 소음이 남는 경우 Silero로 되돌리세요.",@@ -823,6 +838,10 @@"title": "추가 녹음 버퍼","description": "키를 놓은 후 추가로 녹음을 계속하는 시간(밀리초). 후행 오디오를 캡처하기 위함. 0 = 추가 버퍼 없음."},+ "languageDetectionWindow": {+ "title": "언어 감지 오디오",+ "description": "언어 감지기가 듣는 음성의 초 단위 길이입니다. 길수록 정확하지만 느립니다."+ },"keyboardDiagnostic": {"title": "키보드 진단","description": "키보드 이벤트가 Handy에 도달하는지 확인합니다. 이벤트 개수만 기록되며, 어떤 키를 눌렀는지는 절대 기록되지 않습니다.",diff --git a/src/i18n/locales/ne/translation.json b/src/i18n/locales/ne/translation.jsonindex 8263f624..5c6dbe34 100644--- a/src/i18n/locales/ne/translation.json+++ b/src/i18n/locales/ne/translation.json@@ -356,7 +356,16 @@"description": "वाक् पहिचानका लागि भाषा चयन गर्नुहोस्। Auto ले भाषा स्वतः निर्धारण गर्छ, भने कुनै निश्चित भाषा चयन गर्दा त्यस भाषाको शुद्धता सुधार हुन सक्छ।","searchPlaceholder": "भाषाहरू खोज्नुहोस्...","noResults": "कुनै भाषा भेटिएन",- "auto": "स्वतः"+ "auto": "स्वतः",+ "autoUnavailable": {+ "title": "स्वतः बन्द छ",+ "oneLanguage": "तपाईंका भाषाहरूमध्ये एउटा मात्र यो मोडेलसँग काम गर्छ",+ "undetectable": "{{languages}} सँग उपलब्ध छैन",+ "noMatch": "तपाईंका कुनै पनि भाषा यो मोडेलसँग काम गर्दैनन्"+ },+ "detectorMissingTitle": "स्वतःका लागि छुट्टै डाउनलोड चाहिन्छ",+ "detectorMissing": "यो मोडेलले तपाईं कुन भाषा बोल्दै हुनुहुन्छ भनेर चिन्न सक्दैन। स्वतःलाई त्यो पत्ता लगाउन एउटा सानो भाषा पहिचानकर्ता चाहिन्छ",+ "stopDetectorDownload": "भाषा पहिचानकर्ताको डाउनलोड रोक्नुहोस्"},"preferredLanguages": {"title": "मनपर्ने भाषाहरू",@@ -583,6 +592,12 @@"title": "लामो अडियो विभाजन","description": "ट्रान्सक्राइब गर्नुअघि लामो रेकर्डिङलाई विरामहरूमा विभाजन गर्छ, जसले सामान्यतया ट्रान्सक्रिप्सन सुधार गर्छ। ट्रान्सक्राइब गरिएका फाइलहरू र लामो पुनः ट्रान्सक्रिप्सनहरू सधैं विभाजन गरिन्छन्।"},+ "languageDetection": {+ "title": "स्वतःलाई मेरा भाषाहरूमा सीमित गर्नुहोस्",+ "description": "स्वतःले सानो भाषा पहिचानकर्ता प्रयोग गरेर तपाईंका रुचाइएका भाषाहरूबाट मात्र छान्छ। स्वतःले तपाईंले नबोल्ने भाषा छानिरहेमा यो खोल्नुहोस्",+ "downloadHint": "यो खोल्दा सानो भाषा पहिचानकर्ता डाउनलोड हुन्छ",+ "downloadingHint": "भाषा पहिचानकर्ता डाउनलोड हुँदैछ। रद्द गर्न यो बन्द गर्नुहोस्"+ },"vadBackend": {"title": "भ्वाइस एक्टिभिटी ब्याकएन्ड","description": "मौनता फिल्टर गर्न प्रयोग हुने डिटेक्टर छान्नुहोस्। Earshot प्रयोगात्मक हो; बोली काटिएमा वा आवाज रहिरहेमा Silero मा फर्कनुहोस्।",@@ -823,6 +838,10 @@"title": "अतिरिक्त रेकर्डिङ बफर","description": "कि छोडेपछि अन्तिम अडियो समात्न रेकर्डिङ जारी राख्ने अतिरिक्त समय (मिलिसेकेन्डमा)। 0 = कुनै अतिरिक्त बफर छैन।"},+ "languageDetectionWindow": {+ "title": "भाषा पहिचान अडियो",+ "description": "भाषा पहिचानकर्ताले सुन्ने बोलीका सेकेन्ड। लामो बढी सही तर ढिलो हुन्छ।"+ },"keyboardDiagnostic": {"title": "किबोर्ड डायग्नोस्टिक","description": "किबोर्ड इभेन्टहरू Handy सम्म पुग्छन् कि पुग्दैनन् भनी जाँच्छ। इभेन्टको संख्या मात्र रेकर्ड हुन्छ — तपाईंले कुन कुञ्जी थिच्नुभयो भन्ने कहिल्यै होइन।",diff --git a/src/i18n/locales/nl/translation.json b/src/i18n/locales/nl/translation.jsonindex 5d177a17..605429ba 100644--- a/src/i18n/locales/nl/translation.json+++ b/src/i18n/locales/nl/translation.json@@ -356,7 +356,16 @@"description": "Selecteer de taal voor spraakherkenning. 'Automatisch' detecteert de taal vanzelf, terwijl het kiezen van een specifieke taal de nauwkeurigheid voor die taal kan verbeteren.","searchPlaceholder": "Talen zoeken...","noResults": "Geen talen gevonden",- "auto": "Automatisch"+ "auto": "Automatisch",+ "autoUnavailable": {+ "title": "Automatisch is uitgeschakeld",+ "oneLanguage": "Maar één van je talen werkt met dit model",+ "undetectable": "Niet beschikbaar met {{languages}}",+ "noMatch": "Geen van je talen werkt met dit model"+ },+ "detectorMissingTitle": "Automatisch heeft een aparte download nodig",+ "detectorMissing": "Dit model kan niet bepalen welke taal je spreekt. Automatisch heeft een kleine taaldetector nodig om dat uit te zoeken",+ "stopDetectorDownload": "Downloaden van de taaldetector stoppen"},"preferredLanguages": {"title": "Voorkeurstalen",@@ -583,6 +592,12 @@"title": "Lange audio opsplitsen","description": "Splitst lange opnames bij pauzes op voordat ze worden getranscribeerd, wat de transcriptie doorgaans verbetert. Getranscribeerde bestanden en lange hertranscripties worden altijd opgesplitst."},+ "languageDetection": {+ "title": "Automatisch beperken tot mijn talen",+ "description": "Automatisch kiest alleen uit je voorkeurstalen, met een kleine taaldetector. Zet dit aan als Automatisch steeds een taal kiest die je niet spreekt",+ "downloadHint": "Aanzetten downloadt een kleine taaldetector",+ "downloadingHint": "De taaldetector wordt gedownload. Zet dit uit om te annuleren"+ },"vadBackend": {"title": "VAD-backend","description": "Kies de detector die stilte filtert. Earshot is experimenteel; schakel terug naar Silero als spraak wordt afgekapt of ruis behouden blijft.",@@ -823,6 +838,10 @@"title": "Extra opnamebuffer","description": "Extra tijd (in milliseconden) om te blijven opnemen nadat je de toets loslaat, om naloopaudio op te vangen. 0 = geen extra buffer."},+ "languageDetectionWindow": {+ "title": "Audio voor taaldetectie",+ "description": "Seconden spraak die de taaldetector hoort. Langer is nauwkeuriger maar trager."+ },"keyboardDiagnostic": {"title": "Toetsenborddiagnose","description": "Controleert of toetsenbordgebeurtenissen Handy bereiken. Alleen het aantal gebeurtenissen wordt vastgelegd — nooit welke toetsen je indrukt.",diff --git a/src/i18n/locales/pl/translation.json b/src/i18n/locales/pl/translation.jsonindex ab99d234..f90ca482 100644--- a/src/i18n/locales/pl/translation.json+++ b/src/i18n/locales/pl/translation.json@@ -356,7 +356,16 @@"description": "Wybierz język rozpoznawania mowy. Opcja Auto automatycznie określi język, a wybór konkretnego języka może poprawić dokładność.","searchPlaceholder": "Szukaj języka...","noResults": "Nie znaleziono języków",- "auto": "Automatycznie"+ "auto": "Automatycznie",+ "autoUnavailable": {+ "title": "Automatycznie jest wyłączone",+ "oneLanguage": "Z tym modelem działa tylko jeden z twoich języków",+ "undetectable": "Niedostępne dla {{languages}}",+ "noMatch": "Żaden z twoich języków nie działa z tym modelem"+ },+ "detectorMissingTitle": "Tryb automatyczny wymaga osobnego pobrania",+ "detectorMissing": "Ten model nie rozpozna, w jakim języku mówisz. Tryb automatyczny potrzebuje małego detektora języka, żeby to ustalić",+ "stopDetectorDownload": "Zatrzymaj pobieranie detektora języka"},"preferredLanguages": {"title": "Preferowane języki",@@ -583,6 +592,12 @@"title": "Dzielenie długich nagrań","description": "Dzieli długie nagrania w miejscach pauz przed transkrypcją, co zwykle poprawia jakość transkrypcji. Transkrybowane pliki i długie ponowne transkrypcje są zawsze dzielone."},+ "languageDetection": {+ "title": "Ogranicz tryb automatyczny do moich języków",+ "description": "Tryb automatyczny wybiera tylko spośród preferowanych języków, korzystając z małego detektora języka. Włącz to, jeśli tryb automatyczny wciąż wybiera język, którym nie mówisz",+ "downloadHint": "Włączenie pobiera mały detektor języka",+ "downloadingHint": "Pobieranie detektora języka. Wyłącz, aby anulować"+ },"vadBackend": {"title": "Backend wykrywania głosu","description": "Wybierz detektor używany do filtrowania ciszy. Earshot jest eksperymentalny; wróć do Silero, jeśli mowa jest ucinana lub szum jest zachowywany.",@@ -823,6 +838,10 @@"title": "Dodatkowy bufor nagrywania","description": "Dodatkowy czas (w milisekundach) na kontynuowanie nagrywania po zwolnieniu klawisza, aby przechwycić końcowy dźwięk. 0 = brak dodatkowego bufora."},+ "languageDetectionWindow": {+ "title": "Dźwięk do wykrywania języka",+ "description": "Ile sekund mowy słyszy detektor języka. Dłużej znaczy dokładniej, ale wolniej."+ },"keyboardDiagnostic": {"title": "Diagnostyka klawiatury","description": "Sprawdza, czy zdarzenia klawiatury docierają do Handy. Zapisywana jest tylko liczba zdarzeń — nigdy to, które klawisze naciskasz.",diff --git a/src/i18n/locales/pt/translation.json b/src/i18n/locales/pt/translation.jsonindex 3b131a7b..59363763 100644--- a/src/i18n/locales/pt/translation.json+++ b/src/i18n/locales/pt/translation.json@@ -356,7 +356,16 @@"description": "Selecione o idioma para reconhecimento de fala. Auto detectará automaticamente o idioma, enquanto selecionar um idioma específico pode melhorar a precisão para esse idioma.","searchPlaceholder": "Buscar idiomas...","noResults": "Nenhum idioma encontrado",- "auto": "Automático"+ "auto": "Automático",+ "autoUnavailable": {+ "title": "Automático está desativado",+ "oneLanguage": "Apenas um dos seus idiomas funciona com este modelo",+ "undetectable": "Indisponível com {{languages}}",+ "noMatch": "Nenhum dos seus idiomas funciona com este modelo"+ },+ "detectorMissingTitle": "Automático precisa de um download separado",+ "detectorMissing": "Este modelo não consegue identificar o idioma que você está falando. O Automático precisa de um pequeno detector de idioma para descobrir",+ "stopDetectorDownload": "Parar o download do detector de idioma"},"preferredLanguages": {"title": "Idiomas preferidos",@@ -583,6 +592,12 @@"title": "Divisão de áudio longo","description": "Divide gravações longas nas pausas antes da transcrição, o que normalmente melhora o desempenho da transcrição. Arquivos transcritos e re-transcrições longas são sempre divididos."},+ "languageDetection": {+ "title": "Limitar o Automático aos meus idiomas",+ "description": "O Automático só escolhe entre seus idiomas preferidos, usando um pequeno detector de idioma. Ative se o Automático continuar escolhendo um idioma que você não fala",+ "downloadHint": "Ativar isto baixa um pequeno detector de idioma",+ "downloadingHint": "Baixando o detector de idioma. Desative para cancelar"+ },"vadBackend": {"title": "Backend de detecção de voz","description": "Escolha o detector usado para filtrar o silêncio. O Earshot é experimental; volte para o Silero se a fala for cortada ou o ruído for mantido.",@@ -823,6 +838,10 @@"title": "Buffer de gravação extra","description": "Tempo extra (em milissegundos) para continuar gravando após soltar a tecla, para capturar áudio restante. 0 = sem buffer extra."},+ "languageDetectionWindow": {+ "title": "Áudio de detecção de idioma",+ "description": "Segundos de fala que o detector de idioma ouve. Mais longo é mais preciso, porém mais lento."+ },"keyboardDiagnostic": {"title": "Diagnóstico do teclado","description": "Verifica se os eventos de teclado chegam ao Handy. Apenas a contagem de eventos é registrada — nunca quais teclas você pressiona.",diff --git a/src/i18n/locales/ru/translation.json b/src/i18n/locales/ru/translation.jsonindex 75e1e3fe..28b6123c 100644--- a/src/i18n/locales/ru/translation.json+++ b/src/i18n/locales/ru/translation.json@@ -356,7 +356,16 @@"description": "Выберите язык для распознавания речи. «Авто» автоматически определит язык, а выбор конкретного языка может повысить точность определения этого языка.","searchPlaceholder": "Поиск языков...","noResults": "Языки не найдены",- "auto": "Авто"+ "auto": "Авто",+ "autoUnavailable": {+ "title": "Авто отключено",+ "oneLanguage": "С этой моделью работает только один из ваших языков",+ "undetectable": "Недоступно для: {{languages}}",+ "noMatch": "Ни один из ваших языков не работает с этой моделью"+ },+ "detectorMissingTitle": "Для режима «Авто» нужна отдельная загрузка",+ "detectorMissing": "Эта модель не может определить, на каком языке вы говорите. Режиму «Авто» нужен небольшой определитель языка",+ "stopDetectorDownload": "Остановить загрузку определителя языка"},"preferredLanguages": {"title": "Предпочитаемые языки",@@ -583,6 +592,12 @@"title": "Разделение длинного аудио","description": "Разделяет длинные записи по паузам перед распознаванием, что обычно улучшает качество распознавания. Расшифровываемые файлы и длинные повторные расшифровки всегда разделяются."},+ "languageDetection": {+ "title": "Ограничить «Авто» моими языками",+ "description": "«Авто» выбирает только из ваших предпочитаемых языков с помощью небольшого определителя языка. Включите, если «Авто» продолжает выбирать язык, на котором вы не говорите",+ "downloadHint": "При включении загружается небольшой определитель языка",+ "downloadingHint": "Загружается определитель языка. Выключите, чтобы отменить"+ },"vadBackend": {"title": "Движок определения голоса","description": "Выберите детектор для фильтрации тишины. Earshot — экспериментальный; вернитесь к Silero, если речь обрезается или шум сохраняется.",@@ -823,6 +838,10 @@"title": "Дополнительный буфер записи","description": "Дополнительное время (в миллисекундах) для продолжения записи после отпускания клавиши, чтобы захватить завершающий звук. 0 = без дополнительного буфера."},+ "languageDetectionWindow": {+ "title": "Аудио для определения языка",+ "description": "Сколько секунд речи слышит определитель языка. Дольше — точнее, но медленнее."+ },"keyboardDiagnostic": {"title": "Диагностика клавиатуры","description": "Проверяет, доходят ли события клавиатуры до Handy. Записывается только количество событий — никогда то, какие клавиши вы нажимаете.",diff --git a/src/i18n/locales/sv/translation.json b/src/i18n/locales/sv/translation.jsonindex 18894620..3768deea 100644--- a/src/i18n/locales/sv/translation.json+++ b/src/i18n/locales/sv/translation.json@@ -356,7 +356,16 @@"description": "Välj språk för taligenkänning. Auto kommer automatiskt att bestämma språket, medan val av ett specifikt språk kan förbättra noggrannheten för det språket.","searchPlaceholder": "Sök språk...","noResults": "Inga språk hittades",- "auto": "Automatiskt"+ "auto": "Automatiskt",+ "autoUnavailable": {+ "title": "Automatiskt är avstängt",+ "oneLanguage": "Bara ett av dina språk fungerar med den här modellen",+ "undetectable": "Inte tillgängligt med {{languages}}",+ "noMatch": "Inget av dina språk fungerar med den här modellen"+ },+ "detectorMissingTitle": "Automatiskt kräver en separat nedladdning",+ "detectorMissing": "Den här modellen kan inte avgöra vilket språk du talar. Automatiskt behöver en liten språkidentifiering som tar reda på det",+ "stopDetectorDownload": "Stoppa nedladdningen av språkidentifieringen"},"preferredLanguages": {"title": "Föredragna språk",@@ -583,6 +592,12 @@"title": "Dela upp långt ljud","description": "Delar upp långa inspelningar vid pauser före transkribering, vilket oftast förbättrar transkriberingen. Transkriberade filer och långa omtranskriberingar delas alltid upp."},+ "languageDetection": {+ "title": "Begränsa Automatiskt till mina språk",+ "description": "Automatiskt väljer bara bland dina föredragna språk med hjälp av en liten språkidentifiering. Slå på det om Automatiskt fortsätter att välja ett språk du inte talar",+ "downloadHint": "När du slår på det laddas en liten språkidentifiering ned",+ "downloadingHint": "Språkidentifieringen laddas ned. Stäng av för att avbryta"+ },"vadBackend": {"title": "Backend för röstdetektering","description": "Välj detektorn som används för att filtrera bort tystnad. Earshot är experimentell; byt tillbaka till Silero om tal klipps eller brus behålls.",@@ -823,6 +838,10 @@"title": "Extra inspelningsbuffert","description": "Extra tid (i millisekunder) för att fortsätta spela in efter att du släppt tangenten, för att fånga upp avslutande ljud. 0 = ingen extra buffert."},+ "languageDetectionWindow": {+ "title": "Ljud för språkidentifiering",+ "description": "Sekunder tal som språkidentifieringen hör. Längre är noggrannare men långsammare."+ },"keyboardDiagnostic": {"title": "Tangentbordsdiagnostik","description": "Kontrollerar om tangentbordshändelser når Handy. Endast antalet händelser registreras — aldrig vilka tangenter du trycker på.",diff --git a/src/i18n/locales/tr/translation.json b/src/i18n/locales/tr/translation.jsonindex 88916568..a9f39999 100644--- a/src/i18n/locales/tr/translation.json+++ b/src/i18n/locales/tr/translation.json@@ -356,7 +356,16 @@"description": "Konuşma tanıma dilini seçin. 'Otomatik' seçeneği dili kendisi belirler, ancak belirli bir dil seçmek o dildeki doğruluğu artırabilir.","searchPlaceholder": "Dil ara...","noResults": "Dil bulunamadı",- "auto": "Otomatik"+ "auto": "Otomatik",+ "autoUnavailable": {+ "title": "Otomatik devre dışı",+ "oneLanguage": "Dillerinizden yalnızca biri bu modelle çalışıyor",+ "undetectable": "{{languages}} ile kullanılamaz",+ "noMatch": "Dillerinizden hiçbiri bu modelle çalışmıyor"+ },+ "detectorMissingTitle": "Otomatik için ayrı bir indirme gerekiyor",+ "detectorMissing": "Bu model hangi dili konuştuğunuzu anlayamıyor. Otomatik'in bunu anlamak için küçük bir dil algılayıcıya ihtiyacı var",+ "stopDetectorDownload": "Dil algılayıcının indirilmesini durdur"},"preferredLanguages": {"title": "Tercih Edilen Diller",@@ -583,6 +592,12 @@"title": "Uzun Sesi Bölme","description": "Uzun kayıtları yazıya dökmeden önce duraklamalardan böler; bu genellikle yazıya dökme performansını artırır. Yazıya dökülen dosyalar ve uzun yeniden transkripsiyonlar her zaman bölünür."},+ "languageDetection": {+ "title": "Otomatik'i dillerimle sınırla",+ "description": "Otomatik, küçük bir dil algılayıcı kullanarak yalnızca tercih ettiğiniz diller arasından seçer. Otomatik konuşmadığınız bir dili seçip duruyorsa bunu açın",+ "downloadHint": "Bunu açmak küçük bir dil algılayıcı indirir",+ "downloadingHint": "Dil algılayıcı indiriliyor. İptal etmek için kapatın"+ },"vadBackend": {"title": "Ses Etkinliği Arka Ucu","description": "Sessizliği filtrelemek için kullanılan algılayıcıyı seçin. Earshot deneyseldir; konuşma kesiliyorsa veya gürültü korunuyorsa Silero'ya geri dönün.",@@ -823,6 +838,10 @@"title": "Ekstra Kayıt Tamponu","description": "Tuşu bıraktıktan sonra arka plandaki sesi yakalamak için kaydı sürdürme süresi (milisaniye). 0 = ekstra tampon yok."},+ "languageDetectionWindow": {+ "title": "Dil Algılama Sesi",+ "description": "Dil algılayıcının duyduğu konuşma saniyesi. Daha uzun daha doğru ama daha yavaştır."+ },"keyboardDiagnostic": {"title": "Klavye Tanılaması","description": "Klavye olaylarının Handy'ye ulaşıp ulaşmadığını denetler. Yalnızca olay sayıları kaydedilir — hangi tuşlara bastığınız asla kaydedilmez.",diff --git a/src/i18n/locales/uk/translation.json b/src/i18n/locales/uk/translation.jsonindex 3b036ebf..6fa5c9ee 100644--- a/src/i18n/locales/uk/translation.json+++ b/src/i18n/locales/uk/translation.json@@ -356,7 +356,16 @@"description": "Оберіть мову для розпізнавання мовлення. Режим «Авто» визначить мову автоматично, а вибір конкретної мови може покращити точність.","searchPlaceholder": "Пошук мов...","noResults": "Мов не знайдено",- "auto": "Авто"+ "auto": "Авто",+ "autoUnavailable": {+ "title": "Авто вимкнено",+ "oneLanguage": "З цією моделлю працює лише одна з ваших мов",+ "undetectable": "Недоступно для: {{languages}}",+ "noMatch": "Жодна з ваших мов не працює з цією моделлю"+ },+ "detectorMissingTitle": "Для режиму «Авто» потрібне окреме завантаження",+ "detectorMissing": "Ця модель не може визначити, якою мовою ви говорите. Режиму «Авто» потрібен невеликий визначник мови",+ "stopDetectorDownload": "Зупинити завантаження визначника мови"},"preferredLanguages": {"title": "Бажані мови",@@ -583,6 +592,12 @@"title": "Поділ довгого аудіо","description": "Розділяє довгі записи за паузами перед розпізнаванням, що зазвичай покращує якість розпізнавання. Розшифровувані файли та довгі повторні розшифрування завжди розділяються."},+ "languageDetection": {+ "title": "Обмежити «Авто» моїми мовами",+ "description": "«Авто» обирає лише з ваших бажаних мов за допомогою невеликого визначника мови. Увімкніть, якщо «Авто» постійно обирає мову, якою ви не говорите",+ "downloadHint": "Увімкнення завантажує невеликий визначник мови",+ "downloadingHint": "Завантажується визначник мови. Вимкніть, щоб скасувати"+ },"vadBackend": {"title": "Рушій виявлення голосу","description": "Виберіть детектор для фільтрації тиші. Earshot — експериментальний; поверніться до Silero, якщо мовлення обрізається або шум зберігається.",@@ -823,6 +838,10 @@"title": "Додатковий буфер запису","description": "Додатковий час (у мілісекундах) для продовження запису після відпускання клавіші, щоб захопити завершальний звук. 0 = без додаткового буфера."},+ "languageDetectionWindow": {+ "title": "Аудіо для визначення мови",+ "description": "Скільки секунд мовлення чує визначник мови. Довше — точніше, але повільніше."+ },"keyboardDiagnostic": {"title": "Діагностика клавіатури","description": "Перевіряє, чи доходять події клавіатури до Handy. Записується лише кількість подій — ніколи те, які клавіші ви натискаєте.",diff --git a/src/i18n/locales/vi/translation.json b/src/i18n/locales/vi/translation.jsonindex 1235b039..9a66909f 100644--- a/src/i18n/locales/vi/translation.json+++ b/src/i18n/locales/vi/translation.json@@ -356,7 +356,16 @@"description": "Chọn ngôn ngữ để nhận dạng giọng nói. Tự động sẽ tự động xác định ngôn ngữ, trong khi chọn một ngôn ngữ cụ thể có thể cải thiện độ chính xác cho ngôn ngữ đó.","searchPlaceholder": "Tìm kiếm ngôn ngữ...","noResults": "Không tìm thấy ngôn ngữ",- "auto": "Tự động"+ "auto": "Tự động",+ "autoUnavailable": {+ "title": "Tự động đã tắt",+ "oneLanguage": "Chỉ một trong các ngôn ngữ của bạn hoạt động với mô hình này",+ "undetectable": "Không khả dụng với {{languages}}",+ "noMatch": "Không ngôn ngữ nào của bạn hoạt động với mô hình này"+ },+ "detectorMissingTitle": "Tự động cần tải xuống riêng",+ "detectorMissing": "Mô hình này không nhận biết được bạn đang nói ngôn ngữ nào. Tự động cần một trình nhận diện ngôn ngữ nhỏ để xác định",+ "stopDetectorDownload": "Dừng tải xuống trình nhận diện ngôn ngữ"},"preferredLanguages": {"title": "Ngôn ngữ ưa thích",@@ -583,6 +592,12 @@"title": "Chia nhỏ âm thanh dài","description": "Chia các bản ghi dài tại các khoảng ngắt trước khi chuyển thành văn bản, điều này thường cải thiện hiệu quả chuyển văn bản. Tệp được chép lời và các lần phiên âm lại dài luôn được chia nhỏ."},+ "languageDetection": {+ "title": "Giới hạn Tự động trong ngôn ngữ của tôi",+ "description": "Tự động chỉ chọn trong các ngôn ngữ ưu tiên của bạn, nhờ một trình nhận diện ngôn ngữ nhỏ. Bật lên nếu Tự động cứ chọn một ngôn ngữ bạn không nói",+ "downloadHint": "Bật lên sẽ tải xuống một trình nhận diện ngôn ngữ nhỏ",+ "downloadingHint": "Đang tải xuống trình nhận diện ngôn ngữ. Tắt để hủy"+ },"vadBackend": {"title": "Bộ phát hiện giọng nói","description": "Chọn bộ phát hiện dùng để lọc khoảng lặng. Earshot đang thử nghiệm; hãy chuyển về Silero nếu giọng nói bị cắt hoặc tiếng ồn vẫn còn.",@@ -823,6 +838,10 @@"title": "Bộ đệm ghi âm thêm","description": "Thời gian thêm (tính bằng mili giây) để tiếp tục ghi âm sau khi nhả phím, để thu âm thanh cuối. 0 = không có bộ đệm thêm."},+ "languageDetectionWindow": {+ "title": "Âm thanh nhận diện ngôn ngữ",+ "description": "Số giây giọng nói mà trình nhận diện ngôn ngữ nghe. Dài hơn thì chính xác hơn nhưng chậm hơn."+ },"keyboardDiagnostic": {"title": "Chẩn đoán bàn phím","description": "Kiểm tra xem các sự kiện bàn phím có đến được Handy hay không. Chỉ số lượng sự kiện được ghi lại — không bao giờ ghi lại bạn bấm phím nào.",diff --git a/src/i18n/locales/zh-TW/translation.json b/src/i18n/locales/zh-TW/translation.jsonindex 7a537fcb..0a6b7dbf 100644--- a/src/i18n/locales/zh-TW/translation.json+++ b/src/i18n/locales/zh-TW/translation.json@@ -356,7 +356,16 @@"description": "選擇語音辨識的語言。選擇自動將自動判定語言,選擇特定語言可以提高該語言的準確度","searchPlaceholder": "搜尋語言...","noResults": "未找到語言",- "auto": "自動"+ "auto": "自動",+ "autoUnavailable": {+ "title": "自動已停用",+ "oneLanguage": "你的語言中只有一種適用於此模型",+ "undetectable": "不支援{{languages}}",+ "noMatch": "你的語言都不適用於此模型"+ },+ "detectorMissingTitle": "自動模式需要另外下載",+ "detectorMissing": "此模型無法分辨你說的是哪種語言。自動模式需要一個小型語言偵測器來判斷",+ "stopDetectorDownload": "停止下載語言偵測器"},"preferredLanguages": {"title": "偏好語言",@@ -583,6 +592,12 @@"title": "長音訊分段","description": "在轉錄前依停頓處將長錄音分段,通常可以提升轉錄效果。轉錄檔案與較長的重新轉錄一律會分段。"},+ "languageDetection": {+ "title": "將自動模式限制為我的語言",+ "description": "自動模式會藉助一個小型語言偵測器,只從你的偏好語言中選擇。如果自動模式總是選到你不說的語言,請開啟此項",+ "downloadHint": "開啟後會下載一個小型語言偵測器",+ "downloadingHint": "正在下載語言偵測器。關閉此項即可取消"+ },"vadBackend": {"title": "語音活動偵測後端","description": "選擇用於過濾靜音的偵測器。Earshot 為實驗性功能;若語音被截斷或雜訊被保留,請切換回 Silero。",@@ -823,6 +838,10 @@"title": "額外錄音緩衝","description": "放開按鍵後繼續錄音的額外時間(毫秒),以捕捉尾音。0 = 無額外緩衝。"},+ "languageDetectionWindow": {+ "title": "語言偵測音訊",+ "description": "語言偵測器聆聽的語音秒數。越長越準確,但越慢。"+ },"keyboardDiagnostic": {"title": "鍵盤診斷","description": "檢查鍵盤事件是否能送達 Handy。只會記錄事件數量,絕不記錄您按了哪些按鍵。",diff --git a/src/i18n/locales/zh/translation.json b/src/i18n/locales/zh/translation.jsonindex 9e685c88..2e19ad2e 100644--- a/src/i18n/locales/zh/translation.json+++ b/src/i18n/locales/zh/translation.json@@ -356,7 +356,16 @@"description": "选择语音识别的语言。自动将自动确定语言,选择特定语言可以提高该语言的准确度。","searchPlaceholder": "搜索语言...","noResults": "未找到语言",- "auto": "自动"+ "auto": "自动",+ "autoUnavailable": {+ "title": "自动已停用",+ "oneLanguage": "你的语言中只有一种适用于此模型",+ "undetectable": "不支持{{languages}}",+ "noMatch": "你的语言都不适用于此模型"+ },+ "detectorMissingTitle": "自动模式需要单独下载",+ "detectorMissing": "此模型无法分辨你说的是哪种语言。自动模式需要一个小型语言检测器来判断",+ "stopDetectorDownload": "停止下载语言检测器"},"preferredLanguages": {"title": "常用语言",@@ -583,6 +592,12 @@"title": "长音频分段","description": "在转录前按停顿处将长录音分段,通常可以提升转录效果。转录文件与较长的重新转录始终会分段。"},+ "languageDetection": {+ "title": "将自动模式限制为我的语言",+ "description": "自动模式会借助一个小型语言检测器,只从你的首选语言中选择。如果自动模式总是选中你不说的语言,请打开此项",+ "downloadHint": "打开后会下载一个小型语言检测器",+ "downloadingHint": "正在下载语言检测器。关闭此项即可取消"+ },"vadBackend": {"title": "语音活动检测后端","description": "选择用于过滤静音的检测器。Earshot 为实验性功能;如果语音被截断或噪音被保留,请切换回 Silero。",@@ -823,6 +838,10 @@"title": "额外录音缓冲","description": "放开按键后继续录音的额外时间(毫秒),以捕捉尾音。0 = 无额外缓冲。"},+ "languageDetectionWindow": {+ "title": "语言检测音频",+ "description": "语言检测器聆听的语音秒数。越长越准确,但越慢。"+ },"keyboardDiagnostic": {"title": "键盘诊断","description": "检查键盘事件是否能到达 Handy。仅记录事件数量,绝不记录您按了哪些键。",diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 2454f17b..1baff40a 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -9,6 +9,7 @@ import type {TranscribeAcceleratorSetting,ShortcutActivation,VadBackend,+ LanguageDetectionMode,} from "@/bindings";import { commands } from "@/bindings";import { toast } from "sonner";@@ -203,6 +204,10 @@ const settingUpdaters: {commands.changeTranscribeGpuDevice(value as string | null),extra_recording_buffer_ms: (value) =>commands.changeExtraRecordingBufferSetting(value as number),+ language_detection: (value) =>+ commands.changeLanguageDetectionSetting(value as LanguageDetectionMode),+ language_detection_window_secs: (value) =>+ commands.changeLanguageDetectionWindowSetting(value as number),};export const useSettingsStore = create<SettingsStore>()(