Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(voice): Parakeet TDT as a second dictation engine (#233)

purpleacdb9ce0747a
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.ts
index 2212d1ae..0a64bbe9 100644
--- a/dev-server/remote-stubs.ts
+++ b/dev-server/remote-stubs.ts
@@ -104,6 +104,7 @@ export function registerRemoteStubs(routes: RouteMount): void {
'/local-api/comfy-model-reveal',
'/local-api/bundled-model-delete-plan',
'/local-api/trash-model-file', '/local-api/set-engine-idle-unload', '/local-api/transcribe-external',
+ '/local-api/parakeet-status', '/local-api/parakeet-install', '/local-api/parakeet-cancel', '/local-api/parakeet-stop', '/local-api/parakeet-transcribe',
'/local-api/set-gpu-roles', '/local-api/describe-gpu-roles',
'/local-api/abliterate-plan', '/local-api/abliterate-start', '/local-api/abliterate-status',
'/local-api/abliterate-cancel', '/local-api/abliterate-dismiss', '/local-api/abliterate-runs',
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 35864880..aace8df2 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -131,6 +131,10 @@ pub mod funnel;
#[cfg(desktop)]
pub mod gallery_files;
pub mod whisper;
+// Parakeet dictation (#233). A native runtime fetched for this machine; a
+// phone has neither the runtime nor the room for the model.
+#[cfg(desktop)]
+pub mod parakeet;
// ── the web app-compat error helpers ────────────────────────────────────────
//
diff --git a/src-tauri/src/commands/parakeet.rs b/src-tauri/src/commands/parakeet.rs
new file mode 100644
index 00000000..7c3c2134
--- /dev/null
+++ b/src-tauri/src/commands/parakeet.rs
@@ -0,0 +1,718 @@
+//! Parakeet dictation (GitHub #233): NVIDIA Parakeet TDT 0.6B v3 as a second
+//! speech-to-text engine next to faster-whisper.
+//!
+//! It runs on NVIDIA's own runtime, NeMo-Speech.cpp, a native program without
+//! Python. LU fetches the release archive for this machine and the model file
+//! once, keeps each only when size and sha256 match the pins in
+//! `parakeet/manifest.json`, and starts `nemo-speech serve` on 127.0.0.1 the
+//! first time a take is transcribed. The server listens on a free port and
+//! answers only with a key made for that run, so no other program on the
+//! machine can use it. A take goes to its OpenAI-compatible
+//! `/v1/audio/transcriptions` as the WAV the recorder writes.
+//!
+//! Everything lives below `data_dir()/parakeet`:
+//! runtime/<release dir>/bin/nemo-speech[.exe] the unpacked release
+//! models/parakeet-tdt-0.6b-v3.q8_0.gguf the model
+//! installed.json what was verified
+//! A file under its real name is always a verified one: downloads go to a
+//! `.download` twin first (`voice_loop::fetch`).
+
+use std::io::{BufRead, BufReader};
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use base64::Engine;
+use serde::{Deserialize, Serialize};
+
+use crate::commands::voice_loop::fetch::{fetch_verified, http_client, FetchError};
+use crate::commands::voice_loop::manifest::RemoteFile;
+use crate::os_error;
+
+const MANIFEST_TEXT: &str = include_str!("parakeet/manifest.json");
+const SUPPORTED_SCHEMA: u32 = 1;
+/// The model loads in about a second; the first take on a Mac also compiles
+/// the Metal shaders once, which took 16 s on an M-series Mac.
+const READY_TIMEOUT: Duration = Duration::from_secs(120);
+const TRANSCRIBE_TIMEOUT: Duration = Duration::from_secs(300);
+
+// ── manifest ────────────────────────────────────────────────────────────────
+
+#[derive(Deserialize, Clone, Debug)]
+pub struct Build {
+ pub target: String,
+ /// The single top-level directory of the archive.
+ pub dir: String,
+ #[serde(flatten)]
+ pub remote: RemoteFile,
+}
+
+#[derive(Deserialize, Clone, Debug)]
+pub struct Runtime {
+ pub name: String,
+ pub version: String,
+ pub license: String,
+ pub source: String,
+ pub builds: Vec<Build>,
+}
+
+#[derive(Deserialize, Clone, Debug)]
+pub struct Model {
+ pub id: String,
+ pub name: String,
+ pub license: String,
+ pub attribution: String,
+ pub source: String,
+ pub revision: String,
+ pub file: String,
+ #[serde(flatten)]
+ pub remote: RemoteFile,
+}
+
+#[derive(Deserialize, Clone, Debug)]
+pub struct Manifest {
+ schema: u32,
+ pub runtime: Runtime,
+ pub model: Model,
+}
+
+fn is_hex_digest(s: &str) -> bool {
+ s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
+}
+
+/// A name that stays one plain path component on every system.
+fn is_plain_name(s: &str) -> bool {
+ !s.is_empty()
+ && s.len() <= 120
+ && s != "."
+ && s != ".."
+ && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
+}
+
+impl Manifest {
+ pub fn parse(text: &str) -> Result<Self, String> {
+ let m: Manifest = serde_json::from_str(text).map_err(|e| format!("The Parakeet manifest could not be read: {e}."))?;
+ if m.schema != SUPPORTED_SCHEMA {
+ return Err(format!("The Parakeet manifest has schema {}, this LU reads {SUPPORTED_SCHEMA}.", m.schema));
+ }
+ let remotes = m.runtime.builds.iter().map(|b| (&b.remote, b.dir.as_str())).chain(std::iter::once((&m.model.remote, m.model.file.as_str())));
+ for (remote, name) in remotes {
+ if !remote.url.starts_with("https://") || remote.size == 0 || !is_hex_digest(&remote.sha256) || !is_plain_name(name) {
+ return Err(format!("The Parakeet manifest has an entry it cannot use: {name}."));
+ }
+ }
+ if !m.runtime.source.starts_with("https://") || !m.model.source.starts_with("https://") {
+ return Err("The Parakeet manifest names a source that is not https.".to_string());
+ }
+ if m.model.revision.len() != 40 || !m.model.remote.url.contains(&format!("/resolve/{}/", m.model.revision)) {
+ return Err("The Parakeet model is not fetched by its pinned revision.".to_string());
+ }
+ Ok(m)
+ }
+
+ /// "NeMo-Speech.cpp 0.3.0", for the log and the settings.
+ pub fn runtime_label(&self) -> String {
+ format!("{} {}", self.runtime.name, self.runtime.version)
+ }
+
+ pub fn build_for(&self, target: &str) -> Option<&Build> {
+ self.runtime.builds.iter().find(|b| b.target == target)
+ }
+}
+
+pub fn manifest() -> &'static Manifest {
+ static M: OnceLock<Manifest> = OnceLock::new();
+ M.get_or_init(|| Manifest::parse(MANIFEST_TEXT).expect("the bundled Parakeet manifest is checked by a test"))
+}
+
+/// The release target of this machine, or the sentence that says why
+/// Parakeet cannot run here.
+pub fn target_for(os: &str, arch: &str) -> Result<&'static str, String> {
+ match (os, arch) {
+ ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
+ ("macos", "x86_64") => Ok("x86_64-apple-darwin"),
+ ("windows", "x86_64") => Ok("x86_64-pc-windows-msvc"),
+ ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu"),
+ ("windows", _) | ("linux", _) => Err(format!(
+ "Parakeet needs a 64-bit Intel or AMD processor on this system. This machine reports {arch}."
+ )),
+ _ => Err("Parakeet is not available on this system.".to_string()),
+ }
+}
+
+fn this_target() -> Result<&'static str, String> {
+ target_for(std::env::consts::OS, std::env::consts::ARCH)
+}
+
+// ── layout ──────────────────────────────────────────────────────────────────
+
+#[derive(Clone, Debug)]
+pub struct Dirs {
+ pub root: PathBuf,
+}
+
+impl Dirs {
+ pub fn current() -> Self {
+ Self { root: crate::os_paths::data_dir().join("parakeet") }
+ }
+ pub fn runtime(&self) -> PathBuf {
+ self.root.join("runtime")
+ }
+ pub fn release(&self, build: &Build) -> PathBuf {
+ self.runtime().join(&build.dir)
+ }
+ pub fn exe(&self, build: &Build, windows: bool) -> PathBuf {
+ self.release(build).join("bin").join(if windows { "nemo-speech.exe" } else { "nemo-speech" })
+ }
+ pub fn archive(&self, build: &Build) -> PathBuf {
+ let ext = if build.remote.url.ends_with(".zip") { "zip" } else { "tar.gz" };
+ self.root.join("downloads").join(format!("{}.{ext}", build.dir))
+ }
+ pub fn model(&self, model: &Model) -> PathBuf {
+ self.root.join("models").join(&model.file)
+ }
+ pub fn marker(&self) -> PathBuf {
+ self.root.join("installed.json")
+ }
+}
+
+/// What a finished install verified. Read on every status, so it stays small:
+/// hashing the 714 MB model on each look would cost seconds.
+#[derive(Serialize, Deserialize, Default, Debug, PartialEq)]
+pub struct Marker {
+ pub runtime_sha256: String,
+ pub model_sha256: String,
+}
+
+impl Marker {
+ fn load(dirs: &Dirs) -> Marker {
+ std::fs::read_to_string(dirs.marker()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
+ }
+ fn save(&self, dirs: &Dirs) -> Result<(), String> {
+ let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
+ std::fs::write(dirs.marker(), text).map_err(|e| format!("The Parakeet install record could not be written: {}.", os_error::io_english(&e)))
+ }
+}
+
+/// Is the pinned runtime and model in place for `build`? The marker says both
+/// were verified; the sizes catch a file that was replaced or cut since.
+pub fn is_installed(dirs: &Dirs, m: &Manifest, build: &Build, windows: bool) -> bool {
+ let marker = Marker::load(dirs);
+ let model_ok = std::fs::metadata(dirs.model(&m.model)).map(|md| md.is_file() && md.len() == m.model.remote.size).unwrap_or(false);
+ marker.runtime_sha256 == build.remote.sha256
+ && marker.model_sha256 == m.model.remote.sha256
+ && model_ok
+ && dirs.exe(build, windows).is_file()
+}
+
+// ── unpacking ───────────────────────────────────────────────────────────────
+
+/// Unpack a release archive into `into`. Both readers refuse entries that
+/// would land outside it.
+pub fn unpack(archive: &Path, into: &Path) -> Result<(), String> {
+ let fail = |e: &dyn std::fmt::Display| format!("The Parakeet runtime could not be unpacked: {e}.");
+ std::fs::create_dir_all(into).map_err(|e| fail(&os_error::io_english(&e)))?;
+ let file = std::fs::File::open(archive).map_err(|e| fail(&os_error::io_english(&e)))?;
+ let name = archive.to_string_lossy();
+ if name.ends_with(".zip") {
+ let mut zip = zip::ZipArchive::new(std::io::BufReader::new(file)).map_err(|e| fail(&e))?;
+ for i in 0..zip.len() {
+ let mut entry = zip.by_index(i).map_err(|e| fail(&e))?;
+ let Some(rel) = entry.enclosed_name() else {
+ return Err(fail(&"an entry points outside the folder"));
+ };
+ let out = into.join(rel);
+ if entry.is_dir() {
+ std::fs::create_dir_all(&out).map_err(|e| fail(&os_error::io_english(&e)))?;
+ continue;
+ }
+ if let Some(parent) = out.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| fail(&os_error::io_english(&e)))?;
+ }
+ let mut w = std::fs::File::create(&out).map_err(|e| fail(&os_error::io_english(&e)))?;
+ std::io::copy(&mut entry, &mut w).map_err(|e| fail(&os_error::io_english(&e)))?;
+ }
+ Ok(())
+ } else {
+ let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(std::io::BufReader::new(file)));
+ tar.set_overwrite(true);
+ tar.unpack(into).map_err(|e| fail(&os_error::io_english(&e)))
+ }
+}
+
+fn remove_tree(path: &Path) -> Result<(), String> {
+ match std::fs::remove_dir_all(path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(format!("{} could not be removed: {}.", path.display(), os_error::io_english(&e))),
+ }
+}
+
+// ── install job ─────────────────────────────────────────────────────────────
+
+#[derive(Serialize, Clone, Default, Debug)]
+pub struct JobView {
+ pub running: bool,
+ pub done_bytes: u64,
+ pub total_bytes: u64,
+ pub error: Option<String>,
+}
+
+#[derive(Default)]
+struct Job {
+ view: Mutex<JobView>,
+ cancel: AtomicBool,
+}
+
+fn job() -> &'static Job {
+ static J: OnceLock<Job> = OnceLock::new();
+ J.get_or_init(Job::default)
+}
+
+async fn install_into(dirs: &Dirs, m: &Manifest, build: &Build, windows: bool) -> Result<(), String> {
+ let j = job();
+ let client = http_client()?;
+ let runtime_bytes = build.remote.size;
+ let total = runtime_bytes + m.model.remote.size;
+ j.view.lock().unwrap().total_bytes = total;
+ let what = |e: FetchError, name: &str| if e == FetchError::Cancelled { "cancelled".to_string() } else { e.user_message(name) };
+
+ if !dirs.exe(build, windows).is_file() || Marker::load(dirs).runtime_sha256 != build.remote.sha256 {
+ let archive = dirs.archive(build);
+ let mut progress = |n: u64| j.view.lock().unwrap().done_bytes = n.min(runtime_bytes);
+ fetch_verified(&client, &build.remote, &archive, &j.cancel, &mut progress)
+ .await
+ .map_err(|e| what(e, "the Parakeet runtime"))?;
+ // Unpack beside the final place, then move: a half unpacked release
+ // is never under the name the server is started from.
+ let staging = dirs.runtime().join(".unpacking");
+ remove_tree(&staging)?;
+ unpack(&archive, &staging)?;
+ let unpacked = staging.join(&build.dir);
+ if !unpacked.is_dir() {
+ return Err("The Parakeet runtime archive did not hold the expected folder.".to_string());
+ }
+ remove_tree(&dirs.release(build))?;
+ std::fs::rename(&unpacked, dirs.release(build))
+ .map_err(|e| format!("The Parakeet runtime could not be moved into place: {}.", os_error::io_english(&e)))?;
+ remove_tree(&staging)?;
+ let _ = std::fs::remove_file(&archive);
+ let mut marker = Marker::load(dirs);
+ marker.runtime_sha256 = build.remote.sha256.clone();
+ std::fs::create_dir_all(&dirs.root).map_err(|e| os_error::io_english(&e))?;
+ marker.save(dirs)?;
+ }
+ j.view.lock().unwrap().done_bytes = runtime_bytes;
+
+ let mut progress = |n: u64| j.view.lock().unwrap().done_bytes = runtime_bytes + n;
+ fetch_verified(&client, &m.model.remote, &dirs.model(&m.model), &j.cancel, &mut progress)
+ .await
+ .map_err(|e| what(e, "the Parakeet model"))?;
+ let mut marker = Marker::load(dirs);
+ marker.runtime_sha256 = build.remote.sha256.clone();
+ marker.model_sha256 = m.model.remote.sha256.clone();
+ marker.save(dirs)?;
+ j.view.lock().unwrap().done_bytes = total;
+ Ok(())
+}
+
+// ── server ──────────────────────────────────────────────────────────────────
+
+struct Running {
+ child: Child,
+ port: u16,
+ key: String,
+}
+
+fn server() -> &'static Mutex<Option<Running>> {
+ static S: OnceLock<Mutex<Option<Running>>> = OnceLock::new();
+ S.get_or_init(|| Mutex::new(None))
+}
+
+/// One start at a time: two takes in quick succession must not start two
+/// servers.
+fn start_gate() -> &'static tokio::sync::Mutex<()> {
+ static G: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
+ G.get_or_init(|| tokio::sync::Mutex::new(()))
+}
+
+/// The arguments `nemo-speech serve` is started with. Loopback only, no
+/// browser playground, and a key on every request.
+pub fn serve_args(model: &Path, port: u16, key: &str) -> Vec<String> {
+ vec![
+ "serve".into(),
+ "--host".into(),
+ "127.0.0.1".into(),
+ "--port".into(),
+ port.to_string(),
+ "--no-ui".into(),
+ "--api-key".into(),
+ key.into(),
+ "--asr-model".into(),
+ model.to_string_lossy().into_owned(),
+ ]
+}
+
+fn free_port() -> Result<u16, String> {
+ let l = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(|e| format!("No free local port for Parakeet: {}.", os_error::io_english(&e)))?;
+ l.local_addr().map(|a| a.port()).map_err(|e| os_error::io_english(&e))
+}
+
+/// The address and key of a running server, if there is one that is alive.
+fn live() -> Option<(u16, String)> {
+ let mut slot = server().lock().unwrap();
+ let alive = match slot.as_mut() {
+ Some(r) => matches!(r.child.try_wait(), Ok(None)),
+ None => false,
+ };
+ if !alive {
+ if let Some(mut r) = slot.take() {
+ let _ = r.child.kill();
+ let _ = r.child.wait();
+ }
+ return None;
+ }
+ slot.as_ref().map(|r| (r.port, r.key.clone()))
+}
+
+fn spawn(exe: &Path, model: &Path) -> Result<(u16, String), String> {
+ let port = free_port()?;
+ let key = uuid::Uuid::new_v4().simple().to_string();
+ let mut cmd = Command::new(exe);
+ cmd.args(serve_args(model, port, &key))
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ if let Some(bin) = exe.parent() {
+ cmd.current_dir(bin);
+ }
+ crate::process_util::suppress_window(&mut cmd);
+ let mut child = cmd.spawn().map_err(|e| format!("Parakeet could not be started: {}.", os_error::english(&e)))?;
+ crate::commands::process::tie_child_to_app_lifetime(child.id());
+ for pipe in [child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>), child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>)].into_iter().flatten() {
+ std::thread::spawn(move || {
+ for line in BufReader::new(pipe).lines().map_while(Result::ok) {
+ if !line.trim().is_empty() {
+ tracing::info!(target: "parakeet", "{}", line.trim());
+ }
+ }
+ });
+ }
+ *server().lock().unwrap() = Some(Running { child, port, key: key.clone() });
+ Ok((port, key))
+}
+
+async fn wait_ready(port: u16, key: &str) -> Result<(), String> {
+ let client = reqwest::Client::builder().timeout(Duration::from_secs(2)).no_proxy().build().map_err(|e| e.to_string())?;
+ let url = format!("http://127.0.0.1:{port}/ready");
+ let start = Instant::now();
+ while start.elapsed() < READY_TIMEOUT {
+ if live().is_none() {
+ return Err("Parakeet stopped while it was loading the model. The app log has its last lines.".to_string());
+ }
+ if let Ok(r) = client.get(&url).bearer_auth(key).send().await {
+ if let Ok(v) = r.json::<serde_json::Value>().await {
+ if v.get("ready").and_then(|b| b.as_bool()) == Some(true) {
+ return Ok(());
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ stop();
+ Err("Parakeet did not finish loading the model in time.".to_string())
+}
+
+async fn ensure_running() -> Result<(u16, String), String> {
+ let _gate = start_gate().lock().await;
+ if let Some(found) = live() {
+ return Ok(found);
+ }
+ let m = manifest();
+ let target = this_target()?;
+ let build = m.build_for(target).ok_or_else(|| "Parakeet is not available on this system.".to_string())?;
+ let dirs = Dirs::current();
+ let windows = cfg!(windows);
+ if !is_installed(&dirs, m, build, windows) {
+ return Err("Parakeet is not installed. Get it in Settings, Voice.".to_string());
+ }
+ let started = Instant::now();
+ let (port, key) = spawn(&dirs.exe(build, windows), &dirs.model(&m.model))?;
+ wait_ready(port, &key).await?;
+ tracing::info!(target: "parakeet", "server ready on port {port} after {} ms", started.elapsed().as_millis());
+ Ok((port, key))
+}
+
+/// Stop the server, if one runs. Called on quit and when dictation leaves
+/// Parakeet, so the model does not stay in memory for nothing.
+pub fn stop() {
+ if let Ok(mut slot) = server().lock() {
+ if let Some(mut r) = slot.take() {
+ let _ = r.child.kill();
+ let _ = r.child.wait();
+ }
+ }
+}
+
+async fn post_take(port: u16, key: &str, audio: Vec<u8>) -> Result<reqwest::Response, reqwest::Error> {
+ let part = reqwest::multipart::Part::bytes(audio).file_name("take.wav").mime_str("audio/wav")?;
+ let form = reqwest::multipart::Form::new().part("file", part).text("response_format", "json");
+ reqwest::Client::builder()
+ .timeout(TRANSCRIBE_TIMEOUT)
+ .no_proxy()
+ .build()?
+ .post(format!("http://127.0.0.1:{port}/v1/audio/transcriptions"))
+ .bearer_auth(key)
+ .multipart(form)
+ .send()
+ .await
+}
+
+// ── commands ────────────────────────────────────────────────────────────────
+
+#[derive(Serialize, Debug)]
+pub struct Status {
+ pub supported: bool,
+ /// Why not, when `supported` is false.
+ pub reason: Option<String>,
+ pub installed: bool,
+ pub running: bool,
+ pub download_bytes: u64,
+ pub model: String,
+ pub license: String,
+ pub attribution: String,
+ pub runtime: String,
+ pub runtime_license: String,
+ pub job: JobView,
+}
+
+#[tauri::command]
+pub fn parakeet_status() -> Status {
+ let m = manifest();
+ let job = job().view.lock().unwrap().clone();
+ let running = live().is_some();
+ let base = |supported, reason, installed, download_bytes| Status {
+ supported,
+ reason,
+ installed,
+ running,
+ download_bytes,
+ model: m.model.name.clone(),
+ license: m.model.license.clone(),
+ attribution: m.model.attribution.clone(),
+ runtime: m.runtime_label(),
+ runtime_license: m.runtime.license.clone(),
+ job: job.clone(),
+ };
+ match this_target().and_then(|t| m.build_for(t).ok_or_else(|| "Parakeet is not available on this system.".to_string())) {
+ Err(reason) => base(false, Some(reason), false, 0),
+ Ok(build) => {
+ let installed = is_installed(&Dirs::current(), m, build, cfg!(windows));
+ base(true, None, installed, build.remote.size + m.model.remote.size)
+ }
+ }
+}
+
+#[tauri::command]
+pub fn parakeet_install() -> Result<(), String> {
+ let m = manifest();
+ let build = m.build_for(this_target()?).ok_or_else(|| "Parakeet is not available on this system.".to_string())?.clone();
+ {
+ let mut v = job().view.lock().unwrap();
+ if v.running {
+ return Ok(());
+ }
+ *v = JobView { running: true, ..JobView::default() };
+ }
+ job().cancel.store(false, Ordering::SeqCst);
+ tauri::async_runtime::spawn(async move {
+ let dirs = Dirs::current();
+ let result = install_into(&dirs, manifest(), &build, cfg!(windows)).await;
+ match &result {
+ Ok(()) => tracing::info!(target: "parakeet", "installed {} ({}) and {} at {}", manifest().runtime_label(), build.dir, manifest().model.id, manifest().model.revision),
+ Err(e) => tracing::warn!(target: "parakeet", "install stopped: {e}"),
+ }
+ let mut v = job().view.lock().unwrap();
+ v.running = false;
+ v.error = result.err().filter(|e| e != "cancelled");
+ });
+ Ok(())
+}
+
+#[tauri::command]
+pub fn parakeet_cancel() {
+ job().cancel.store(true, Ordering::SeqCst);
+}
+
+#[tauri::command]
+pub fn parakeet_stop() {
+ stop();
+}
+
+/// One dictation take, a WAV as base64, to text.
+#[tauri::command]
+pub async fn parakeet_transcribe(audio_base64: String) -> Result<serde_json::Value, String> {
+ let audio = base64::engine::general_purpose::STANDARD.decode(&audio_base64).map_err(|e| format!("base64 decode: {e}"))?;
+ if audio.is_empty() {
+ return Err("Empty audio data".to_string());
+ }
+ let started = Instant::now();
+ let (port, key) = ensure_running().await?;
+ let resp = match post_take(port, &key, audio.clone()).await {
+ Ok(r) => r,
+ // The server went away between the check and the request. One fresh
+ // start, the same take again.
+ Err(e) if e.is_connect() => {
+ stop();
+ let (port, key) = ensure_running().await?;
+ post_take(port, &key, audio).await.map_err(|e| format!("Parakeet did not answer: {}", os_error::english(&e)))?
+ }
+ Err(e) => return Err(format!("Parakeet did not answer: {}", os_error::english(&e))),
+ };
+ if !resp.status().is_success() {
+ let code = resp.status().as_u16();
+ let detail: String = resp.text().await.unwrap_or_default().chars().take(200).collect();
+ return Err(format!("Parakeet answered HTTP {code}: {detail}"));
+ }
+ let answer: serde_json::Value = resp.json().await.map_err(|e| format!("Parakeet's answer was not JSON: {e}"))?;
+ let text = answer.get("text").and_then(|t| t.as_str()).map(|t| t.trim().to_string()).ok_or("Parakeet's answer carried no text")?;
+ tracing::info!(target: "parakeet", "take transcribed in {} ms", started.elapsed().as_millis());
+ Ok(serde_json::json!({ "transcript": text }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_bundled_manifest_reads_and_pins_every_desktop_target() {
+ let m = Manifest::parse(MANIFEST_TEXT).unwrap();
+ for target in ["aarch64-apple-darwin", "x86_64-apple-darwin", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu"] {
+ let b = m.build_for(target).unwrap_or_else(|| panic!("no build for {target}"));
+ assert!(b.remote.url.starts_with("https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.0/"), "{}", b.remote.url);
+ assert!(b.remote.url.contains(&b.dir), "{} does not name {}", b.remote.url, b.dir);
+ }
+ assert!(m.model.remote.url.starts_with("https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3/resolve/"));
+ assert!(m.model.remote.url.contains(&m.model.revision), "the model is fetched by its pinned revision");
+ assert_eq!(m.model.license, "CC-BY-4.0");
+ assert_eq!(m.runtime.license, "Apache-2.0");
+ }
+
+ #[test]
+ fn a_manifest_with_a_loose_entry_is_refused() {
+ let bad_digest = MANIFEST_TEXT.replace("e3880d0aaaaf2c308ea2c35016b2b895c423eb3fda924c1b463d1c19b7f4d32e", "abc");
+ assert!(Manifest::parse(&bad_digest).is_err());
+ let plain_http = MANIFEST_TEXT.replacen("\"url\": \"https://github.com", "\"url\": \"http://github.com", 1);
+ assert!(Manifest::parse(&plain_http).is_err());
+ let escaping = MANIFEST_TEXT.replace("\"dir\": \"nemo-speech-0.3.0-macos-aarch64-metal\"", "\"dir\": \"..\"");
+ assert!(Manifest::parse(&escaping).is_err());
+ let floating = MANIFEST_TEXT.replace("/resolve/541d1f99c6b0c3cd0b11a95167540bb8edefd82b/", "/resolve/main/");
+ assert!(Manifest::parse(&floating).is_err(), "a model on a moving branch is refused");
+ }
+
+ #[test]
+ fn every_desktop_system_has_a_target_and_others_get_a_sentence() {
+ assert_eq!(target_for("macos", "aarch64").unwrap(), "aarch64-apple-darwin");
+ assert_eq!(target_for("windows", "x86_64").unwrap(), "x86_64-pc-windows-msvc");
+ assert_eq!(target_for("linux", "x86_64").unwrap(), "x86_64-unknown-linux-gnu");
+ assert!(target_for("windows", "aarch64").unwrap_err().contains("aarch64"));
+ assert!(target_for("android", "aarch64").is_err());
+ }
+
+ #[test]
+ fn the_server_listens_on_loopback_without_playground_and_with_a_key() {
+ let a = serve_args(Path::new("/m/p.gguf"), 4321, "k1");
+ let pair = |flag: &str| a.iter().position(|x| x == flag).map(|i| a[i + 1].clone());
+ assert_eq!(pair("--host").as_deref(), Some("127.0.0.1"));
+ assert_eq!(pair("--port").as_deref(), Some("4321"));
+ assert_eq!(pair("--api-key").as_deref(), Some("k1"));
+ assert_eq!(pair("--asr-model").as_deref(), Some("/m/p.gguf"));
+ assert!(a.contains(&"--no-ui".to_string()));
+ }
+
+ fn tmp(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("lu-parakeet-test-{name}-{}", uuid::Uuid::new_v4().simple()));
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn installed_needs_the_marker_the_exe_and_a_model_of_the_pinned_size() {
+ let root = tmp("installed");
+ let dirs = Dirs { root: root.clone() };
+ let mut m = Manifest::parse(MANIFEST_TEXT).unwrap();
+ m.model.remote.size = 5;
+ let build = m.build_for("aarch64-apple-darwin").unwrap().clone();
+ assert!(!is_installed(&dirs, &m, &build, false));
+
+ let exe = dirs.exe(&build, false);
+ std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
+ std::fs::write(&exe, b"x").unwrap();
+ std::fs::create_dir_all(dirs.model(&m.model).parent().unwrap()).unwrap();
+ std::fs::write(dirs.model(&m.model), b"12345").unwrap();
+ assert!(!is_installed(&dirs, &m, &build, false), "no marker, nothing was verified");
+
+ Marker { runtime_sha256: build.remote.sha256.clone(), model_sha256: m.model.remote.sha256.clone() }.save(&dirs).unwrap();
+ assert!(is_installed(&dirs, &m, &build, false));
+
+ std::fs::write(dirs.model(&m.model), b"1234").unwrap();
+ assert!(!is_installed(&dirs, &m, &build, false), "a cut model is not installed");
+
+ std::fs::write(dirs.model(&m.model), b"12345").unwrap();
+ Marker { runtime_sha256: "0".repeat(64), model_sha256: m.model.remote.sha256.clone() }.save(&dirs).unwrap();
+ assert!(!is_installed(&dirs, &m, &build, false), "another runtime release is not this one");
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn a_tar_release_unpacks_with_its_links_and_a_zip_one_without_escaping() {
+ let root = tmp("unpack");
+ // tar.gz with a file and a relative link, as the macOS and Linux releases have.
+ let tgz = root.join("r.tar.gz");
+ {
+ let gz = flate2::write::GzEncoder::new(std::fs::File::create(&tgz).unwrap(), flate2::Compression::fast());
+ let mut b = tar::Builder::new(gz);
+ let mut h = tar::Header::new_gnu();
+ h.set_size(3);
+ h.set_mode(0o755);
+ h.set_cksum();
+ b.append_data(&mut h, "rel/bin/nemo-speech", &b"abc"[..]).unwrap();
+ let mut l = tar::Header::new_gnu();
+ l.set_entry_type(tar::EntryType::Symlink);
+ l.set_size(0);
+ l.set_cksum();
+ b.append_link(&mut l, "rel/lib/libx.dylib", "libx.0.dylib").unwrap();
+ b.into_inner().unwrap().finish().unwrap();
+ }
+ let out = root.join("out");
+ unpack(&tgz, &out).unwrap();
+ assert_eq!(std::fs::read(out.join("rel/bin/nemo-speech")).unwrap(), b"abc");
+ assert!(std::fs::symlink_metadata(out.join("rel/lib/libx.dylib")).unwrap().file_type().is_symlink());
+
+ // zip as on Windows; an entry that climbs out is refused.
+ let zp = root.join("r.zip");
+ {
+ let mut z = zip::ZipWriter::new(std::fs::File::create(&zp).unwrap());
+ let o = zip::write::SimpleFileOptions::default();
+ z.start_file("rel/bin/nemo-speech.exe", o).unwrap();
+ std::io::Write::write_all(&mut z, b"exe").unwrap();
+ z.finish().unwrap();
+ }
+ let out2 = root.join("out2");
+ unpack(&zp, &out2).unwrap();
+ assert_eq!(std::fs::read(out2.join("rel/bin/nemo-speech.exe")).unwrap(), b"exe");
+
+ let evil = root.join("evil.zip");
+ {
+ let mut z = zip::ZipWriter::new(std::fs::File::create(&evil).unwrap());
+ z.start_file("../outside.txt", zip::write::SimpleFileOptions::default()).unwrap();
+ std::io::Write::write_all(&mut z, b"no").unwrap();
+ z.finish().unwrap();
+ }
+ assert!(unpack(&evil, &root.join("out3")).is_err());
+ assert!(!root.join("outside.txt").exists());
+ let _ = std::fs::remove_dir_all(root);
+ }
+}
diff --git a/src-tauri/src/commands/parakeet/manifest.json b/src-tauri/src/commands/parakeet/manifest.json
new file mode 100644
index 00000000..6af95258
--- /dev/null
+++ b/src-tauri/src/commands/parakeet/manifest.json
@@ -0,0 +1,52 @@
+{
+ "schema": 1,
+ "note": "Parakeet dictation (#233). The runtime is NVIDIA's own NeMo-Speech.cpp release, the model NVIDIA's own GGUF. Both are fetched by pinned version or revision and kept only when size and sha256 match. Runtime digests come from the release's SHA256SUMS file; the model digest is the one the runtime's own model-index.json pins for this revision.",
+ "runtime": {
+ "name": "NeMo-Speech.cpp",
+ "version": "0.3.0",
+ "license": "Apache-2.0",
+ "source": "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/tag/v0.3.0",
+ "builds": [
+ {
+ "target": "aarch64-apple-darwin",
+ "dir": "nemo-speech-0.3.0-macos-aarch64-metal",
+ "url": "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.0/nemo-speech-0.3.0-macos-aarch64-metal.tar.gz",
+ "size": 7239335,
+ "sha256": "2b972ed8b5dba07492212acf8cb75cbf34ecb141198ffa1997febe84b7c4d9ed"
+ },
+ {
+ "target": "x86_64-apple-darwin",
+ "dir": "nemo-speech-0.3.0-macos-x86_64-cpu",
+ "url": "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.0/nemo-speech-0.3.0-macos-x86_64-cpu.tar.gz",
+ "size": 7742012,
+ "sha256": "97e98aa5eb82dffa4f513f26336b5301d792c9fb43f720ac8f9520a0e92ffe3f"
+ },
+ {
+ "target": "x86_64-pc-windows-msvc",
+ "dir": "nemo-speech-0.3.0-windows-x86_64-cpu",
+ "url": "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.0/nemo-speech-0.3.0-windows-x86_64-cpu.zip",
+ "size": 8694509,
+ "sha256": "4ed9740e361e4653f56c3dce7d1e81883a1c8b831c1bd7d01567fff1130b5b05"
+ },
+ {
+ "target": "x86_64-unknown-linux-gnu",
+ "dir": "nemo-speech-0.3.0-linux-x86_64-cpu",
+ "url": "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.0/nemo-speech-0.3.0-linux-x86_64-cpu.tar.gz",
+ "size": 9605101,
+ "sha256": "255f12b722ab15b2a38a51cf125d56e3fa97058b528f7e895b39d6a473deb06e"
+ }
+ ]
+ },
+ "model": {
+ "id": "parakeet-tdt-0.6b-v3",
+ "name": "Parakeet TDT 0.6B v3",
+ "license": "CC-BY-4.0",
+ "attribution": "Parakeet TDT 0.6B v3 by NVIDIA, licensed under CC BY 4.0.",
+ "source": "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3",
+ "revision": "541d1f99c6b0c3cd0b11a95167540bb8edefd82b",
+ "file": "parakeet-tdt-0.6b-v3.q8_0.gguf",
+ "url": "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3/resolve/541d1f99c6b0c3cd0b11a95167540bb8edefd82b/parakeet-tdt-0.6b-v3.q8_0.gguf",
+ "size": 713975456,
+ "sha256": "e3880d0aaaaf2c308ea2c35016b2b895c423eb3fda924c1b463d1c19b7f4d32e"
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e02067f3..ace6a270 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -842,6 +842,17 @@ pub fn run() {
commands::tts::synthesize,
commands::tts::synthesize_external,
commands::tts::transcribe_external,
+ // Parakeet dictation (#233), NVIDIA's own runtime, desktop only
+ #[cfg(desktop)]
+ commands::parakeet::parakeet_status,
+ #[cfg(desktop)]
+ commands::parakeet::parakeet_install,
+ #[cfg(desktop)]
+ commands::parakeet::parakeet_cancel,
+ #[cfg(desktop)]
+ commands::parakeet::parakeet_stop,
+ #[cfg(desktop)]
+ commands::parakeet::parakeet_transcribe,
commands::tts::download_voice,
commands::tts::installed_piper_voices,
// Agent tools (legacy)
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 0b0e89d9..16f53dd0 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -799,6 +799,9 @@ impl AppState {
if let Ok(mut whisper) = self.whisper.lock() {
whisper.stop();
}
+ // Parakeet dictation's server (#233), when it was started.
+ #[cfg(desktop)]
+ crate::commands::parakeet::stop();
// The voice loop sidecar. It would leave by itself once its stdin
// closes with this process; stopping it here means quit does not
diff --git a/src/App.tsx b/src/App.tsx
index d3de2d71..1e9e331d 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -70,10 +70,14 @@ function App() {
// previously never called anywhere → isSpeechRecognitionSupported() stayed
// false forever → the mic was permanently disabled even with faster-whisper
// installed and running. Fire-and-forget; never blocks first render.
- import('./api/voice').then(({ initWhisperCheck, initTtsCheck }) => {
+ import('./api/voice').then(({ initWhisperCheck, initTtsCheck, parakeetStatus }) => {
initWhisperCheck()
.then((ok) => useVoiceStore.getState().setSttAvailable(ok))
.catch(() => {})
+ // Parakeet dictation (#233): installed means the microphone works with it.
+ parakeetStatus()
+ .then((s) => useVoiceStore.getState().setParakeetReady(!!s?.installed))
+ .catch(() => {})
// Same one-shot probe for local neural TTS (Piper) so the speaker
// buttons reflect real availability and light up after the install.
initTtsCheck()
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 98af7ffb..ada49282 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -649,6 +649,12 @@ export async function backendCall<T = unknown>(
computer_surface_corner: { path: "/local-api/computer-surface-corner", method: "POST" },
transcribe: { path: "/local-api/transcribe", method: "POST" },
transcribe_external: { path: "/local-api/transcribe-external", method: "POST" },
+ // Parakeet dictation (#233) is desktop only; the dev server answers 501.
+ parakeet_status: { path: "/local-api/parakeet-status" },
+ parakeet_install: { path: "/local-api/parakeet-install", method: "POST" },
+ parakeet_cancel: { path: "/local-api/parakeet-cancel", method: "POST" },
+ parakeet_stop: { path: "/local-api/parakeet-stop", method: "POST" },
+ parakeet_transcribe: { path: "/local-api/parakeet-transcribe", method: "POST" },
execute_code: { path: "/local-api/execute-code", method: "POST" },
// file_read / file_write: ABSICHTLICH NICHT HIER. Die beiden Dev-Endpunkte
// sind entfernt (siehe vite.config.ts), weil sie keinen Aufrufer mehr
diff --git a/src/api/voice.ts b/src/api/voice.ts
index 372c9dc0..7f528531 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -328,6 +328,46 @@ export async function transcribeExternal(audioBlob: Blob, url: string, model: st
return asString(prop(data, "transcript")) ?? "";
}
+// --- Parakeet dictation (#233) ---
+
+/** What the desktop knows about Parakeet: whether it can run here, whether it
+ * is installed, and the download in progress. Written by commands/parakeet.rs. */
+export interface ParakeetStatus {
+ supported: boolean;
+ reason: string | null;
+ installed: boolean;
+ running: boolean;
+ download_bytes: number;
+ model: string;
+ license: string;
+ /** The credit CC BY 4.0 asks for, shown next to the choice. */
+ attribution: string;
+ /** "NeMo-Speech.cpp 0.3.0" and its licence. */
+ runtime: string;
+ runtime_license: string;
+ job: { running: boolean; done_bytes: number; total_bytes: number; error: string | null };
+}
+
+/** Parakeet's status, or null where there is none (a phone, the browser dev server). */
+export async function parakeetStatus(): Promise<ParakeetStatus | null> {
+ if (!isTauri()) return null;
+ try {
+ const data: unknown = await backendCall("parakeet_status");
+ return data && typeof data === "object" && "installed" in data ? (data as ParakeetStatus) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** One take through Parakeet. The desktop starts its server on first use. */
+export async function transcribeParakeet(audioBlob: Blob): Promise<string> {
+ const bytes = new Uint8Array(await audioBlob.arrayBuffer());
+ let binary = "";
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
+ const data: unknown = await backendCall("parakeet_transcribe", { audioBase64: btoa(binary) });
+ return asString(prop(data, "transcript")) ?? "";
+}
+
/** The Ollama addresses for speech in and speech out, from its base URL. */
export function ollamaSpeechUrls(base: string): { stt: string; tts: string } {
const b = base.replace(/\/+$/, "");
diff --git a/src/components/settings/ParakeetSetting.tsx b/src/components/settings/ParakeetSetting.tsx
new file mode 100644
index 00000000..7eaa5bb3
--- /dev/null
+++ b/src/components/settings/ParakeetSetting.tsx
@@ -0,0 +1,100 @@
+import { useCallback, useEffect, useState } from 'react'
+import { Check, Download, Loader2, X } from 'lucide-react'
+import { backendCall } from '../../api/backend'
+import { parakeetStatus, type ParakeetStatus } from '../../api/voice'
+import { HINWEIS_TEXT } from '../../lib/hinweis'
+import { useVoiceStore } from '../../stores/voiceStore'
+
+/**
+ * Parakeet dictation (GitHub #233), one line under the dictation switch:
+ * what it is, and either its download or that it is ready. The download is
+ * NVIDIA's runtime for this machine plus the model, verified by checksum in
+ * commands/parakeet.rs.
+ */
+
+export function sizeText(bytes: number): string {
+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`
+}
+
+/** The percentage of a running download, 0 to 100. */
+export function percentOf(done: number, total: number): number {
+ return total > 0 ? Math.min(100, Math.floor((done / total) * 100)) : 0
+}
+
+export function ParakeetSetting() {
+ const [status, setStatus] = useState<ParakeetStatus | null>(null)
+ const [startError, setStartError] = useState<string | null>(null)
+ const setReady = useVoiceStore((s) => s.setParakeetReady)
+
+ const refresh = useCallback(
+ () => parakeetStatus().then((s) => {
+ setStatus(s)
+ setReady(!!s?.installed)
+ }),
+ [setReady],
+ )
+
+ // Look once on mount, and every second while the download runs.
+ const downloading = !!status?.job.running
+ const doneBytes = status?.job.done_bytes ?? 0
+ useEffect(() => {
+ const t = setTimeout(() => void refresh(), downloading ? 1000 : 0)
+ return () => clearTimeout(t)
+ }, [downloading, doneBytes, refresh])
+
+ const install = async () => {
+ setStartError(null)
+ try {
+ await backendCall('parakeet_install')
+ } catch (e) {
+ setStartError(e instanceof Error ? e.message : String(e))
+ }
+ await refresh()
+ }
+
+ const cancel = async () => {
+ await backendCall('parakeet_cancel').catch(() => {})
+ await refresh()
+ }
+
+ if (!status) return null
+ const job = status.job
+ const error = startError ?? job.error
+
+ return (
+ <div className="space-y-1">
+ <div className="flex items-center gap-2 t-micro">
+ <span className="flex items-center gap-1.5 min-w-0">
+ {job.running
+ ? <Loader2 size={11} className="animate-spin text-gray-500 shrink-0" />
+ : status.installed ? <Check size={11} className="text-green-500 shrink-0" /> : <X size={11} className="text-red-500 shrink-0" />}
+ <span className="text-gray-700 dark:text-gray-200 font-medium">{status.model}</span>
+ <span className="text-gray-500 truncate">NVIDIA</span>
+ </span>
+ {status.supported && !status.installed && !job.running && (
+ <button
+ onClick={() => void install()}
+ className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded t-micro font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors"
+ title="Download Parakeet and NVIDIA's runtime for it, checked by checksum"
+ >
+ <Download size={9} />
+ {`Download ${sizeText(status.download_bytes)}`}
+ </button>
+ )}
+ {job.running && (
+ <span className="ml-auto inline-flex items-center gap-1.5 text-gray-500 tabular-nums">
+ {`${percentOf(job.done_bytes, job.total_bytes)} %`}
+ <button onClick={() => void cancel()} title="Stop the download" aria-label="Stop the download" className="text-gray-500 hover:text-gray-300">
+ <X size={10} />
+ </button>
+ </span>
+ )}
+ </div>
+ {!status.supported && status.reason && <p className={`t-micro leading-snug ${HINWEIS_TEXT.fehler}`}>{status.reason}</p>}
+ {error && <p className={`t-micro leading-snug ${HINWEIS_TEXT.fehler}`}>{error}</p>}
+ <p className="t-micro text-gray-500 leading-snug">
+ {`Fast and accurate dictation in 25 European languages, English and German included. It finds the language by itself and runs on this machine. ${status.attribution} Runs on ${status.runtime} by NVIDIA, ${status.runtime_license}.`}
+ </p>
+ </div>
+ )
+}
diff --git a/src/components/settings/SpeechSettings.tsx b/src/components/settings/SpeechSettings.tsx
index e53c6e41..91299700 100644
--- a/src/components/settings/SpeechSettings.tsx
+++ b/src/components/settings/SpeechSettings.tsx
@@ -2,12 +2,13 @@ import { useCallback, useEffect, useReducer, useState } from 'react'
import { Check, Download, Loader2, Mic, Volume2, X } from 'lucide-react'
import { withInstallerOutput } from '../../lib/error-text'
import { HINWEIS_TEXT } from '../../lib/hinweis'
-import { backendCall, getOllamaBase } from '../../api/backend'
+import { backendCall, getOllamaBase, isTauri } from '../../api/backend'
import { useSettingsStore } from '../../stores/settingsStore'
import { useVoiceStore } from '../../stores/voiceStore'
import { checkWhisperAvailable, checkTtsAvailable, downloadPiperVoice, listInstalledPiperVoices, ollamaSpeechUrls, OLLAMA_SPEECH_MODEL } from '../../api/voice'
import { InlineToggle } from './InlineToggle'
import { MicrophoneSetting } from './MicrophoneSetting'
+import { ParakeetSetting } from './ParakeetSetting'
import { initialProbe, makeProbeReducer, needsInstall, showsHint } from './probe-install'
/**
@@ -310,9 +311,16 @@ export function SpeechSettings() {
<EngineSwitch
label="Dictation"
value={voiceSettings.sttMode}
- options={[['whisper', 'faster-whisper'], ['external', 'External HTTP'], ['engine', 'LU Engine']]}
- onPick={(m) => voiceSettings.updateVoiceSettings({ sttMode: m })}
+ options={isTauri()
+ ? [['whisper', 'faster-whisper'], ['parakeet', 'Parakeet'], ['external', 'External HTTP'], ['engine', 'LU Engine']]
+ : [['whisper', 'faster-whisper'], ['external', 'External HTTP'], ['engine', 'LU Engine']]}
+ onPick={(m) => {
+ // Leaving Parakeet frees the memory its server holds (#233).
+ if (voiceSettings.sttMode === 'parakeet' && m !== 'parakeet') void backendCall('parakeet_stop').catch(() => {})
+ voiceSettings.updateVoiceSettings({ sttMode: m })
+ }}
/>
+ {voiceSettings.sttMode === 'parakeet' && <ParakeetSetting />}
{voiceSettings.sttMode === 'engine' && <EngineSpeechNote what="hears" />}
{voiceSettings.sttMode === 'external' && (
<div className="space-y-1.5">
diff --git a/src/hooks/__tests__/parakeet-dictation.dom.test.tsx b/src/hooks/__tests__/parakeet-dictation.dom.test.tsx
new file mode 100644
index 00000000..e639d1da
--- /dev/null
+++ b/src/hooks/__tests__/parakeet-dictation.dom.test.tsx
@@ -0,0 +1,134 @@
+// @vitest-environment jsdom
+/**
+ * GitHub #233: Parakeet TDT as a second dictation engine next to
+ * faster-whisper. The desktop runs it (commands/parakeet.rs); the frontend
+ * only picks it, sends the take there, and gates the microphone on its
+ * install.
+ *
+ * Run: npx vitest run src/hooks/__tests__/parakeet-dictation.dom.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createElement } from 'react'
+import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
+import { standOn } from '../../test-support/devices'
+
+const backend = vi.hoisted(() => ({ backendCall: vi.fn(), tauri: { on: true } }))
+vi.mock('../../api/backend', async (orig) => ({ ...((await orig()) as object), backendCall: backend.backendCall, isTauri: () => backend.tauri.on }))
+vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}) }))
+vi.mock('../../lib/logger', () => ({ log: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() } }))
+vi.mock('../../stores/cloudAuthStore', async (orig) => ({ ...((await orig()) as object), deriveCloudAvailable: () => false }))
+
+import { useVoice, transcribeTake, stopSpeechPlayback } from '../useVoice'
+import { useVoiceStore } from '../../stores/voiceStore'
+import { SpeechSettings } from '../../components/settings/SpeechSettings'
+import { percentOf, sizeText } from '../../components/settings/ParakeetSetting'
+
+const wav = () => new Blob([new Uint8Array([82, 73, 70, 70, 1, 2, 3, 4])], { type: 'audio/wav' })
+
+const status = (over: Record<string, unknown> = {}) => ({
+ supported: true, reason: null, installed: false, running: false, download_bytes: 721_214_791,
+ model: 'Parakeet TDT 0.6B v3', license: 'CC-BY-4.0', attribution: 'Parakeet TDT 0.6B v3 by NVIDIA, licensed under CC BY 4.0.',
+ runtime: 'NeMo-Speech.cpp 0.3.0', runtime_license: 'Apache-2.0',
+ job: { running: false, done_bytes: 0, total_bytes: 0, error: null },
+ ...over,
+})
+
+beforeEach(() => {
+ standOn('mac')
+ backend.tauri.on = true
+ backend.backendCall.mockReset()
+ useVoiceStore.getState().resetVoiceDefaults()
+ useVoiceStore.setState({ sttAvailable: false, parakeetReady: false, sttError: null, transcript: '' })
+})
+afterEach(() => {
+ cleanup()
+ stopSpeechPlayback()
+})
+
+describe('dictation through Parakeet', () => {
+ it('sends the take to parakeet_transcribe and not to faster-whisper', async () => {
+ backend.backendCall.mockResolvedValue({ transcript: 'Bitte schreib mir eine kurze Mail an Thomas.' })
+ useVoiceStore.getState().updateVoiceSettings({ sttMode: 'parakeet' })
+ expect(await transcribeTake(wav(), false)).toBe('Bitte schreib mir eine kurze Mail an Thomas.')
+ expect(backend.backendCall).toHaveBeenCalledTimes(1)
+ const [cmd, args] = backend.backendCall.mock.calls[0]
+ expect(cmd).toBe('parakeet_transcribe')
+ expect(typeof (args as { audioBase64: string }).audioBase64).toBe('string')
+ })
+
+ it('a refusal from the desktop reaches the user as a sentence', async () => {
+ backend.backendCall.mockRejectedValue('Parakeet is not installed. Get it in Settings, Voice.')
+ useVoiceStore.getState().updateVoiceSettings({ sttMode: 'parakeet' })
+ expect(await transcribeTake(wav(), false)).toBe('')
+ expect(useVoiceStore.getState().sttError).toContain('Parakeet is not installed')
+ })
+
+ it('the microphone is ready with Parakeet installed, without faster-whisper', () => {
+ useVoiceStore.getState().updateVoiceSettings({ sttMode: 'parakeet' })
+ const { result } = renderHook(() => useVoice())
+ expect(result.current.sttSupported).toBe(false)
+ act(() => { useVoiceStore.setState({ parakeetReady: true }) })
+ expect(result.current.sttSupported).toBe(true)
+ })
+
+ it('an installed Parakeet does not open the microphone while another engine is chosen', () => {
+ useVoiceStore.setState({ parakeetReady: true })
+ const { result } = renderHook(() => useVoice())
+ expect(result.current.sttSupported).toBe(false)
+ })
+})
+
+describe('the Parakeet line in Settings, Voice', () => {
+ const answer = (s: ReturnType<typeof status>) => backend.backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'parakeet_status') return s
+ if (cmd === 'whisper_status') return { available: true, backend: 'faster-whisper' }
+ if (cmd === 'tts_status') return { available: false }
+ if (cmd === 'installed_piper_voices') return []
+ return null
+ })
+
+ it('is a choice of the dictation switch on the desktop, with the download size', async () => {
+ answer(status())
+ render(createElement(SpeechSettings))
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Parakeet' })) })
+ expect(useVoiceStore.getState().sttMode).toBe('parakeet')
+ expect(await screen.findByText('Parakeet TDT 0.6B v3')).toBeTruthy()
+ const get = await screen.findByRole('button', { name: /Download 721 MB/ })
+ await act(async () => { fireEvent.click(get) })
+ expect(backend.backendCall).toHaveBeenCalledWith('parakeet_install')
+ })
+
+ it('says ready when it is installed and opens the microphone', async () => {
+ answer(status({ installed: true }))
+ useVoiceStore.getState().updateVoiceSettings({ sttMode: 'parakeet' })
+ render(createElement(SpeechSettings))
+ expect(await screen.findByText('Parakeet TDT 0.6B v3')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /Download \d/ })).toBeNull()
+ expect(useVoiceStore.getState().parakeetReady).toBe(true)
+ })
+
+ it('leaving Parakeet stops its server', async () => {
+ answer(status({ installed: true }))
+ useVoiceStore.getState().updateVoiceSettings({ sttMode: 'parakeet' })
+ render(createElement(SpeechSettings))
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'faster-whisper' })) })
+ expect(backend.backendCall).toHaveBeenCalledWith('parakeet_stop')
+ expect(useVoiceStore.getState().sttMode).toBe('whisper')
+ })
+
+ it('is not offered outside the desktop app', async () => {
+ backend.tauri.on = false
+ answer(status())
+ render(createElement(SpeechSettings))
+ expect(screen.queryByRole('button', { name: 'Parakeet' })).toBeNull()
+ })
+
+ it('shows the size and the progress in plain numbers', () => {
+ expect(sizeText(721_214_791)).toBe('721 MB')
+ expect(sizeText(1_500_000_000)).toBe('1.5 GB')
+ expect(sizeText(7_239_335)).toBe('7 MB')
+ expect(percentOf(0, 0)).toBe(0)
+ expect(percentOf(360_000_000, 721_214_791)).toBe(49)
+ expect(percentOf(800, 721)).toBe(100)
+ })
+})
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index 36dc0797..e6e5683a 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -22,6 +22,7 @@ import {
transcribeAudio,
transcribeAudioCloud,
transcribeExternal,
+ transcribeParakeet,
getLastTtsStatus,
LocalSttError,
type AudioRecorder,
@@ -163,8 +164,11 @@ export async function transcribeTake(blob: Blob, cloudVoice: boolean): Promise<s
}
}
const ext = externalStt(store);
+ // Parakeet (#233) is LU's own engine like faster-whisper, run by the
+ // desktop; it has no route and goes first.
const transcript = cloudVoice
? await transcribeAudioCloud(blob)
+ : store.sttMode === "parakeet" ? await transcribeParakeet(blob)
: ext ? await transcribeExternal(blob, ext.url, ext.model).catch((err: unknown) => {
const refusal = speechRefusalText(err instanceof Error ? err.message : String(err), ext);
throw refusal ? refusal : err;
@@ -667,7 +671,8 @@ export function useVoice() {
// Reactive: the source of truth is the store flag set by the startup probe
// (App.tsx) and the in-app install (Settings). Reading a module-level boolean
// here was the bug — it never re-rendered when Whisper came up.
- const sttSupported = cloudVoice || store.sttAvailable || externalStt(store) !== null;
+ const sttSupported = cloudVoice || store.sttAvailable || externalStt(store) !== null
+ || (store.sttMode === "parakeet" && store.parakeetReady);
const ttsSupported = systemVoiceUsable();
// Reactive neural-TTS availability (Piper), same model as sttAvailable.
@@ -744,7 +749,11 @@ export function useVoice() {
if (!snap || snap.size < 12000) return;
interimBusyRef.current = true;
try {
- const partial = await transcribeAudio(snap);
+ // The interim text comes from the engine the final take goes
+ // to: with Parakeet chosen, Whisper may not even be installed.
+ const partial = useVoiceStore.getState().sttMode === "parakeet"
+ ? await transcribeParakeet(snap)
+ : await transcribeAudio(snap);
if (recorderRef.current?.isRecording() && partial.trim()) {
store.setTranscript(partial.trim());
onInterim(partial.trim());
diff --git a/src/lib/speech-route.ts b/src/lib/speech-route.ts
index 2e700377..0e7078c8 100644
--- a/src/lib/speech-route.ts
+++ b/src/lib/speech-route.ts
@@ -16,7 +16,9 @@
* Pure on purpose: which address a take goes to is the part to get right.
*/
-export type SttMode = 'whisper' | 'external' | 'engine'
+/** 'parakeet': NVIDIA Parakeet TDT on NVIDIA's own runtime, run by LU itself
+ * (#233, commands/parakeet.rs). Like 'whisper' it has no route here. */
+export type SttMode = 'whisper' | 'external' | 'engine' | 'parakeet'
export type TtsMode = 'piper' | 'external' | 'engine'
export interface SpeechRoute {
@@ -52,7 +54,8 @@ export function engineSpeechUrls(engineBaseUrl: string): { stt: string; tts: str
return root ? { stt: `${root}/v1/audio/transcriptions`, tts: `${root}/tts` } : null
}
-/** Dictation's route, or null for faster-whisper (also when half filled in). */
+/** Dictation's route, or null for LU's own engines, faster-whisper and
+ * Parakeet (also null when half filled in). */
export function sttRoute(s: Pick<SpeechSettings, 'sttMode' | 'externalSttUrl' | 'externalSttModel'>, engineBaseUrl: string | null | undefined): SpeechRoute | null {
if (s.sttMode === 'engine') {
const urls = engineSpeechUrls(engineBaseUrl ?? '')
diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.ts
index 79e7978f..ef45936f 100644
--- a/src/stores/voiceStore.ts
+++ b/src/stores/voiceStore.ts
@@ -17,6 +17,10 @@ interface VoiceState {
// "available" can never light up the mic on a machine where Whisper is gone,
// and a fresh install lights it up without a restart.
sttAvailable: boolean;
+ /** Whether Parakeet dictation (#233) is installed on this desktop. Same
+ * transient probe model as sttAvailable: re-read every launch and after
+ * its download, never persisted. */
+ parakeetReady: boolean;
// Whether local neural TTS (Piper) is installed + a voice model is present.
// Same transient/probe model as sttAvailable.
ttsAvailable: boolean;
@@ -101,6 +105,7 @@ interface VoiceState {
setSpeaking: (speaking: boolean) => void;
setTranscript: (transcript: string) => void;
setSttAvailable: (available: boolean) => void;
+ setParakeetReady: (ready: boolean) => void;
setTtsAvailable: (available: boolean) => void;
setTtsFallbackReason: (reason: string | null) => void;
setSttError: (error: string | null) => void;
@@ -150,6 +155,7 @@ export const useVoiceStore = create<VoiceState>()(
isSpeaking: false,
transcript: "",
sttAvailable: false,
+ parakeetReady: false,
ttsAvailable: false,
ttsFallbackReason: null,
sttError: null,
@@ -187,6 +193,7 @@ export const useVoiceStore = create<VoiceState>()(
setSpeaking: (speaking) => set({ isSpeaking: speaking }),
setTranscript: (transcript) => set({ transcript }),
setSttAvailable: (available) => set({ sttAvailable: available }),
+ setParakeetReady: (ready) => set({ parakeetReady: ready }),
setTtsAvailable: (available) => set({ ttsAvailable: available }),
setTtsFallbackReason: (reason) => set({ ttsFallbackReason: reason }),
setSttError: (error) => set({ sttError: error }),