Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(voice): add an optional local Parakeet speech model

Alan Buscagliaefc9e6650c9c
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index e76731a..a3bfa99 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aes"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -47,6 +58,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "arbitrary"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
+dependencies = [
+ "derive_arbitrary",
+]
+
[[package]]
name = "ascii"
version = "1.1.0"
@@ -375,6 +395,44 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bzip2"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"
+dependencies = [
+ "bzip2-sys",
+ "libc",
+]
+
+[[package]]
+name = "bzip2"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
+dependencies = [
+ "bzip2-sys",
+]
+
+[[package]]
+name = "bzip2"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
+dependencies = [
+ "libbz2-rs-sys",
+]
+
+[[package]]
+name = "bzip2-sys"
+version = "0.1.13+1.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
[[package]]
name = "cairo-rs"
version = "0.18.5"
@@ -450,6 +508,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
dependencies = [
"find-msvc-tools",
+ "jobserver",
+ "libc",
"shlex",
]
@@ -510,6 +570,16 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+]
+
[[package]]
name = "combine"
version = "4.6.8"
@@ -529,6 +599,12 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "constant_time_eq"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
+
[[package]]
name = "cookie"
version = "0.18.2"
@@ -588,6 +664,21 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
+dependencies = [
+ "crc-catalog",
+]
+
+[[package]]
+name = "crc-catalog"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -696,6 +787,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "deflate64"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
+
[[package]]
name = "defmt"
version = "1.1.1"
@@ -736,6 +833,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "derive_arbitrary"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -765,6 +873,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
+ "subtle",
]
[[package]]
@@ -1013,6 +1122,16 @@ dependencies = [
"rustc_version",
]
+[[package]]
+name = "filetime"
+version = "0.2.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+dependencies = [
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@@ -1277,6 +1396,7 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"block2",
+ "bzip2 0.6.1",
"getrandom 0.3.4",
"image",
"libc",
@@ -1292,6 +1412,9 @@ dependencies = [
"objc2-speech",
"serde",
"serde_json",
+ "sha2",
+ "sherpa-onnx",
+ "tar",
"tauri",
"tauri-build",
"tauri-plugin-autostart",
@@ -1300,6 +1423,7 @@ dependencies = [
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tiny_http",
+ "ureq",
]
[[package]]
@@ -1312,6 +1436,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -1319,9 +1454,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
+ "wasm-bindgen",
]
[[package]]
@@ -1537,6 +1674,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
[[package]]
name = "html5ever"
version = "0.39.0"
@@ -1826,6 +1972,15 @@ dependencies = [
"cfb",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -1978,6 +2133,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -2056,6 +2221,12 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "libbz2-rs-sys"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
+
[[package]]
name = "libc"
version = "0.2.190"
@@ -2117,6 +2288,27 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+[[package]]
+name = "lzma-rs"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e"
+dependencies = [
+ "byteorder",
+ "crc",
+]
+
+[[package]]
+name = "lzma-sys"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+]
+
[[package]]
name = "markup5ever"
version = "0.39.0"
@@ -2680,6 +2872,16 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "pbkdf2"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
+dependencies = [
+ "digest",
+ "hmac",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -3081,6 +3283,20 @@ dependencies = [
"windows-sys 0.60.2",
]
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -3109,6 +3325,41 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "log",
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -3369,6 +3620,17 @@ dependencies = [
"stable_deref_trait",
]
+[[package]]
+name = "sha1"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3380,6 +3642,29 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sherpa-onnx"
+version = "1.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "efaa98d5f08380f3d47026e00f60fed182f6edaf4c0af290d88ac0e08d6e3b90"
+dependencies = [
+ "serde",
+ "serde_json",
+ "sherpa-onnx-sys",
+]
+
+[[package]]
+name = "sherpa-onnx-sys"
+version = "1.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14bbeabb73f73f1c1f4a278af0ee9ae90a19f9727482027047fb9422fa14f8fe"
+dependencies = [
+ "bzip2 0.4.4",
+ "tar",
+ "ureq",
+ "zip",
+]
+
[[package]]
name = "shlex"
version = "2.0.1"
@@ -3526,6 +3811,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "swift-rs"
version = "1.0.8"
@@ -3653,6 +3944,17 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "tar"
+version = "0.4.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
[[package]]
name = "target-lexicon"
version = "0.12.16"
@@ -4380,6 +4682,28 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "ureq"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
+dependencies = [
+ "base64 0.22.1",
+ "flate2",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-pki-types",
+ "url",
+ "webpki-roots 0.26.11",
+]
+
[[package]]
name = "url"
version = "2.5.8"
@@ -4634,6 +4958,24 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-roots"
+version = "0.26.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.9",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webview2-com"
version = "0.39.1"
@@ -4836,6 +5178,15 @@ dependencies = [
"windows-targets 0.42.2",
]
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.59.0"
@@ -5189,12 +5540,31 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "xattr"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
+dependencies = [
+ "libc",
+ "rustix",
+]
+
[[package]]
name = "xkeysym"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+[[package]]
+name = "xz2"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"
+dependencies = [
+ "lzma-sys",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5309,6 +5679,26 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "zerotrie"
version = "0.2.5"
@@ -5342,6 +5732,36 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "zip"
+version = "2.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
+dependencies = [
+ "aes",
+ "arbitrary",
+ "bzip2 0.5.2",
+ "constant_time_eq",
+ "crc32fast",
+ "crossbeam-utils",
+ "deflate64",
+ "displaydoc",
+ "flate2",
+ "getrandom 0.3.4",
+ "hmac",
+ "indexmap 2.14.2",
+ "lzma-rs",
+ "memchr",
+ "pbkdf2",
+ "sha1",
+ "thiserror 2.0.21",
+ "time",
+ "xz2",
+ "zeroize",
+ "zopfli",
+ "zstd",
+]
+
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -5354,6 +5774,46 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
+[[package]]
+name = "zstd"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "7.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.1.0+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
[[package]]
name = "zune-core"
version = "0.5.3"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index f4d20d1..39cf837 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -26,6 +26,15 @@ getrandom = "0.3"
base64 = "0.22"
tiny_http = "0.12"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
+# The optional local voice model (S30.5): Parakeet through sherpa-onnx, linked statically (its
+# build script downloads the prebuilt static libraries from the sherpa-onnx GitHub release unless
+# SHERPA_ONNX_LIB_DIR or SHERPA_ONNX_ARCHIVE_DIR points at a local copy). The model itself is
+# downloaded only when the user asks, over HTTPS, checked against a pinned SHA-256, and unpacked.
+sherpa-onnx = "1.13.8"
+ureq = { version = "2.12", default-features = false, features = ["tls", "proxy-from-env"] }
+sha2 = "0.10"
+tar = { version = "0.4", default-features = false }
+bzip2 = "0.6"
# The computer-control helper (S24) is macOS only.
[target.'cfg(target_os = "macos")'.dependencies]
@@ -57,3 +66,11 @@ opt-level = 3
[profile.dev.package.gentle-dot]
opt-level = 1
+
+# Installing the local voice model (S30.5) hashes a 487 MB download and unpacks 640 MB from
+# bzip2; unoptimized, that alone took 90 s on an M-series Mac.
+[profile.dev.package.libbz2-rs-sys]
+opt-level = 3
+
+[profile.dev.package.sha2]
+opt-level = 3
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index bc80693..dc8b054 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -20,6 +20,10 @@ const COMMANDS: &[&str] = &[
"voice_start",
"voice_stop",
"voice_cancel",
+ "voice_model_status",
+ "voice_model_download",
+ "voice_model_cancel",
+ "voice_model_remove",
];
fn find_in_path(program: &str, path: &str) -> Option<PathBuf> {
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index d05779c..8f69669 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -27,9 +27,18 @@
},
{
"identifier": "voice",
- "description": "Voice input (S30.1): the panel's mic button records and transcribes natively; the Dot never records.",
+ "description": "Voice input (S30.1, S30.5): the panel's mic button records and transcribes natively, and the panel downloads, cancels, and removes the optional local voice model; the Dot never records.",
"windows": ["panel"],
- "permissions": ["allow-voice-status", "allow-voice-start", "allow-voice-stop", "allow-voice-cancel"]
+ "permissions": [
+ "allow-voice-status",
+ "allow-voice-start",
+ "allow-voice-stop",
+ "allow-voice-cancel",
+ "allow-voice-model-status",
+ "allow-voice-model-download",
+ "allow-voice-model-cancel",
+ "allow-voice-model-remove"
+ ]
},
{
"identifier": "glow",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/voice_model_cancel.toml b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_cancel.toml
new file mode 100644
index 0000000..c6e0394
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_cancel.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-voice-model-cancel"
+description = "Enables the voice_model_cancel command without any pre-configured scope."
+commands.allow = ["voice_model_cancel"]
+
+[[permission]]
+identifier = "deny-voice-model-cancel"
+description = "Denies the voice_model_cancel command without any pre-configured scope."
+commands.deny = ["voice_model_cancel"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/voice_model_download.toml b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_download.toml
new file mode 100644
index 0000000..a045c3b
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_download.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-voice-model-download"
+description = "Enables the voice_model_download command without any pre-configured scope."
+commands.allow = ["voice_model_download"]
+
+[[permission]]
+identifier = "deny-voice-model-download"
+description = "Denies the voice_model_download command without any pre-configured scope."
+commands.deny = ["voice_model_download"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/voice_model_remove.toml b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_remove.toml
new file mode 100644
index 0000000..5cf566f
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_remove.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-voice-model-remove"
+description = "Enables the voice_model_remove command without any pre-configured scope."
+commands.allow = ["voice_model_remove"]
+
+[[permission]]
+identifier = "deny-voice-model-remove"
+description = "Denies the voice_model_remove command without any pre-configured scope."
+commands.deny = ["voice_model_remove"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/voice_model_status.toml b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_status.toml
new file mode 100644
index 0000000..18aa944
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/voice_model_status.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-voice-model-status"
+description = "Enables the voice_model_status command without any pre-configured scope."
+commands.allow = ["voice_model_status"]
+
+[[permission]]
+identifier = "deny-voice-model-status"
+description = "Denies the voice_model_status command without any pre-configured scope."
+commands.deny = ["voice_model_status"]
diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs
index deb7179..0db21d6 100644
--- a/apps/desktop/src-tauri/src/shell.rs
+++ b/apps/desktop/src-tauri/src/shell.rs
@@ -30,7 +30,7 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, ShortcutState};
use tauri_plugin_opener::OpenerExt;
const DOT: &str = "dot";
-const PANEL: &str = "panel";
+pub(crate) const PANEL: &str = "panel";
const TRAY: &str = "main";
/// The Dot window, in points: a 66 pt black disc with the rose, plus a 3 pt
/// ring for its shadow. About the screen area of the earlier 64 × 84 rose.
@@ -619,7 +619,11 @@ pub fn run() {
voice::voice_status,
voice::voice_start,
voice::voice_stop,
- voice::voice_cancel
+ voice::voice_cancel,
+ voice::voice_model_status,
+ voice::voice_model_download,
+ voice::voice_model_cancel,
+ voice::voice_model_remove
])
.setup(move |app| {
#[cfg(target_os = "macos")]
@@ -645,7 +649,9 @@ pub fn run() {
full_screen: Mutex::new(None),
});
app.manage(computer::start(&handle));
- app.manage(voice::start());
+ let (voice_input, voice_model) = voice::start(&handle);
+ app.manage(voice_input);
+ app.manage(voice_model);
#[cfg(target_os = "macos")]
register_panic_shortcut(&handle);
diff --git a/apps/desktop/src-tauri/src/voice/app.rs b/apps/desktop/src-tauri/src/voice/app.rs
index 3e03f33..a42f4bc 100644
--- a/apps/desktop/src-tauri/src/voice/app.rs
+++ b/apps/desktop/src-tauri/src/voice/app.rs
@@ -1,14 +1,31 @@
-//! The app side of voice input (S30.1, L88): the `voice_*` commands and the `voice://*` events,
-//! sent only to the webview that started the recording. Off macOS `voice_status` answers
-//! "unavailable" and the other commands fail. Every command runs on a blocking thread: starting
-//! may wait on a permission prompt and stopping waits for the final transcript.
+//! The app side of voice input (S30.1, L88) and of the optional local model (S30.5): the
+//! `voice_*` commands and the `voice://*` events. Recording events go only to the webview that
+//! started the recording; `voice://model` events go to the panel. On macOS, Apple Speech records
+//! until the local model is installed; on Linux, the local model is the only engine; elsewhere
+//! `voice_status` answers "unavailable" and the other recording commands fail. Every command
+//! runs on a blocking thread: starting may wait on a permission prompt, stopping waits for the
+//! final transcript, and removing the model deletes files.
+use super::engine::{fallback_engine, Preferred};
+use super::model::{HttpFetcher, ModelError, ModelEvent, ModelEvents, ModelManager, ModelSpec, ModelStatus, MODEL_EVENT};
+use super::parakeet::{self, Loader, Locate, Parakeet};
use super::{Events, Transcript, Voice, VoiceError, VoiceEvent, VoiceStatus, UNSUPPORTED};
+use crate::computer::SystemClock;
+use std::path::PathBuf;
use std::sync::Arc;
use tauri::{AppHandle, Emitter, EventTarget, Manager};
/// The commands, as registered in `build.rs` and granted to the panel.
-pub const COMMANDS: [&str; 4] = ["voice_status", "voice_start", "voice_stop", "voice_cancel"];
+pub const COMMANDS: [&str; 8] = [
+ "voice_status",
+ "voice_start",
+ "voice_stop",
+ "voice_cancel",
+ "voice_model_status",
+ "voice_model_download",
+ "voice_model_cancel",
+ "voice_model_remove",
+];
/// Voice input, when this platform has a backend.
pub struct VoiceInput {
@@ -45,16 +62,81 @@ impl VoiceInput {
}
}
-/// Apple's Speech framework over the native microphone on macOS; nothing elsewhere.
-pub fn start() -> VoiceInput {
+/// The local model's files and the recognizer that keeps it loaded.
+pub struct VoiceModel {
+ manager: Arc<ModelManager>,
+ local: Arc<Parakeet>,
+}
+
+impl VoiceModel {
+ pub fn status(&self) -> ModelStatus {
+ self.manager.status()
+ }
+
+ pub fn download(&self) -> Result<(), ModelError> {
+ self.manager.download()
+ }
+
+ pub fn cancel(&self) {
+ self.manager.cancel();
+ }
+
+ /// Deletes the files and drops the loaded model.
+ pub fn remove(&self) -> Result<(), ModelError> {
+ self.manager.remove()?;
+ self.local.release();
+ Ok(())
+ }
+}
+
+/// Where models are installed: `<app data>/models`.
+pub fn models_dir(app_data: Option<PathBuf>) -> PathBuf {
+ app_data.unwrap_or_else(|| std::env::temp_dir().join("gentle-dot")).join("models")
+}
+
+/// Voice input with the engine this platform prefers, and the local model's manager.
+pub fn start(app: &AppHandle) -> (VoiceInput, VoiceModel) {
+ let emitter = app.clone();
+ let events: ModelEvents = Arc::new(move |event: ModelEvent| {
+ if let Err(error) = emitter.emit_to(EventTarget::webview_window(crate::shell::PANEL), MODEL_EVENT, event) {
+ eprintln!("gentle-dot: cannot send a voice model event: {error}");
+ }
+ });
+ let manager = Arc::new(ModelManager::new(
+ ModelSpec::parakeet(),
+ models_dir(app.path().app_data_dir().ok()),
+ Arc::new(HttpFetcher),
+ Arc::new(SystemClock),
+ events,
+ fallback_engine(),
+ ));
+ let installed = manager.clone();
+ let locate: Locate = Arc::new(move || installed.installed());
+ let loader: Loader = Arc::new(parakeet::load);
+ let local = Arc::new(Parakeet::new(locate, loader));
+ (platform_input(local.clone()), VoiceModel { manager, local })
+}
+
+/// macOS: the native microphone, Parakeet when installed, else Apple Speech. Linux: a
+/// command-line recorder and Parakeet. Elsewhere: nothing.
+fn platform_input(local: Arc<Parakeet>) -> VoiceInput {
#[cfg(target_os = "macos")]
return VoiceInput::new(Voice::new(
Arc::new(super::MacMicrophone),
- Arc::new(super::AppleSpeech),
- Arc::new(crate::computer::SystemClock),
+ Arc::new(Preferred::new(local, Some(Arc::new(super::AppleSpeech)))),
+ Arc::new(SystemClock),
));
- #[cfg(not(target_os = "macos"))]
- VoiceInput::unsupported()
+ #[cfg(target_os = "linux")]
+ return VoiceInput::new(Voice::new(
+ Arc::new(super::pipe::PipeMicrophone::system()),
+ Arc::new(Preferred::new(local, None)),
+ Arc::new(SystemClock),
+ ));
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
+ {
+ let _ = local;
+ VoiceInput::unsupported()
+ }
}
async fn blocking<T: Send + 'static>(
@@ -94,10 +176,49 @@ pub async fn voice_cancel(app: AppHandle) -> Result<(), String> {
blocking(app, VoiceInput::cancel).await
}
+async fn model<T: Send + 'static>(
+ app: AppHandle,
+ action: impl FnOnce(&VoiceModel) -> Result<T, ModelError> + Send + 'static,
+) -> Result<T, String> {
+ tauri::async_runtime::spawn_blocking(move || action(&app.state::<VoiceModel>()))
+ .await
+ .map_err(|error| error.to_string())?
+ .map_err(String::from)
+}
+
+/// `{installed, bytes?, downloading, received?, total?, engine}`.
+#[tauri::command]
+pub async fn voice_model_status(app: AppHandle) -> Result<ModelStatus, String> {
+ model(app, |model| Ok(model.status())).await
+}
+
+/// Starts the download; `voice://model` events report progress and the outcome.
+#[tauri::command]
+pub async fn voice_model_download(app: AppHandle) -> Result<(), String> {
+ model(app, VoiceModel::download).await
+}
+
+/// Stops a download in flight (harmless otherwise); a `failed` event follows.
+#[tauri::command]
+pub async fn voice_model_cancel(app: AppHandle) -> Result<(), String> {
+ model(app, |model| {
+ model.cancel();
+ Ok(())
+ })
+ .await
+}
+
+/// Deletes the model; a `removed` event follows when there was one.
+#[tauri::command]
+pub async fn voice_model_remove(app: AppHandle) -> Result<(), String> {
+ model(app, VoiceModel::remove).await
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::voice::{VoiceError, VoiceStatus, UNSUPPORTED};
+ use std::path::PathBuf;
use std::sync::Arc;
#[test]
@@ -107,12 +228,30 @@ mod tests {
assert_eq!(input.start(None, Arc::new(|_| {})), Err(VoiceError::Unsupported));
assert_eq!(input.stop(), Err(VoiceError::Unsupported));
assert_eq!(input.cancel(), Err(VoiceError::Unsupported));
- assert_eq!(String::from(VoiceError::Unsupported), "Voice input is available on macOS.");
+ assert_eq!(String::from(VoiceError::Unsupported), "Voice input is available on macOS and Linux.");
+ }
+
+ #[test]
+ fn the_command_names_match_the_l88_and_s30_5_contracts() {
+ assert_eq!(
+ COMMANDS,
+ [
+ "voice_status",
+ "voice_start",
+ "voice_stop",
+ "voice_cancel",
+ "voice_model_status",
+ "voice_model_download",
+ "voice_model_cancel",
+ "voice_model_remove",
+ ]
+ );
}
#[test]
- fn the_command_names_match_the_l88_contract() {
- assert_eq!(COMMANDS, ["voice_status", "voice_start", "voice_stop", "voice_cancel"]);
+ fn models_live_under_the_app_data_dir() {
+ assert_eq!(models_dir(Some(PathBuf::from("/data/app"))), PathBuf::from("/data/app/models"));
+ assert_eq!(models_dir(None), std::env::temp_dir().join("gentle-dot").join("models"));
}
#[test]
diff --git a/apps/desktop/src-tauri/src/voice/engine.rs b/apps/desktop/src-tauri/src/voice/engine.rs
new file mode 100644
index 0000000..8aa5a66
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/engine.rs
@@ -0,0 +1,177 @@
+//! Which speech-to-text engine records (S30.5): the local Parakeet model when it is installed,
+//! else the platform's own (Apple Speech on macOS, S30.1). Linux has no platform engine, so
+//! there voice input needs the model. The choice is made on every call, so a model installed or
+//! removed while the app runs takes effect on the next recording.
+
+use super::model::EngineName;
+use super::parakeet::Parakeet;
+use super::{Authorization, Recognition, Recognizer, Sink, VoiceError};
+use std::sync::Arc;
+
+/// The engine used while the local model is absent, on this platform.
+pub fn fallback_engine() -> EngineName {
+ if cfg!(target_os = "macos") {
+ EngineName::Apple
+ } else {
+ EngineName::None
+ }
+}
+
+pub struct Preferred {
+ local: Arc<Parakeet>,
+ fallback: Option<Arc<dyn Recognizer>>,
+}
+
+impl Preferred {
+ pub fn new(local: Arc<Parakeet>, fallback: Option<Arc<dyn Recognizer>>) -> Self {
+ Preferred { local, fallback }
+ }
+
+ fn pick(&self) -> Option<&dyn Recognizer> {
+ if self.local.installed() {
+ Some(self.local.as_ref())
+ } else {
+ self.fallback.as_deref()
+ }
+ }
+
+ pub fn engine(&self) -> EngineName {
+ if self.local.installed() {
+ EngineName::Parakeet
+ } else if self.fallback.is_some() {
+ // The only platform engine is Apple Speech.
+ EngineName::Apple
+ } else {
+ EngineName::None
+ }
+ }
+}
+
+impl Recognizer for Preferred {
+ fn availability(&self) -> Result<(), VoiceError> {
+ self.pick().map_or(Err(VoiceError::NoModel), |engine| engine.availability())
+ }
+
+ fn authorization(&self) -> Authorization {
+ self.pick().map_or(Authorization::Authorized, |engine| engine.authorization())
+ }
+
+ fn request_authorization(&self) -> Authorization {
+ self.pick().map_or(Authorization::Authorized, |engine| engine.request_authorization())
+ }
+
+ fn current_locale(&self) -> String {
+ self.pick().unwrap_or(self.local.as_ref()).current_locale()
+ }
+
+ fn supported_locales(&self) -> Vec<String> {
+ self.pick().unwrap_or(self.local.as_ref()).supported_locales()
+ }
+
+ fn begin(&self, locale: &str, sink: Sink) -> Result<Box<dyn Recognition>, VoiceError> {
+ self.pick().ok_or(VoiceError::NoModel)?.begin(locale, sink)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::voice::fake::{FakeClock, FakeMicrophone, FakeRecognizer, Recorder};
+ use crate::voice::parakeet::{Engine, Loader, Locate};
+ use crate::voice::{Authorization, Transcript, Voice, VoiceError, VoiceStatus};
+ use std::path::{Path, PathBuf};
+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+ use std::sync::Arc;
+ use std::time::Duration;
+
+ struct Echo;
+
+ impl Engine for Echo {
+ fn transcribe(&self, samples: &[f32]) -> Result<String, String> {
+ Ok(format!("parakeet heard {}", samples.len()))
+ }
+ }
+
+ fn local(installed: Arc<AtomicBool>) -> Arc<Parakeet> {
+ let locate: Locate = Arc::new(move || installed.load(Ordering::SeqCst).then(|| PathBuf::from("/m")));
+ let loader: Loader = Arc::new(|_: &Path| Ok(Arc::new(Echo) as Arc<dyn Engine>));
+ Arc::new(Parakeet::new(locate, loader))
+ }
+
+ struct Rig {
+ voice: Voice,
+ mic: Arc<FakeMicrophone>,
+ apple: Arc<FakeRecognizer>,
+ installed: Arc<AtomicBool>,
+ preferred: Arc<Preferred>,
+ }
+
+ fn rig(apple: FakeRecognizer, with_fallback: bool) -> Rig {
+ let installed = Arc::new(AtomicBool::new(false));
+ let apple = Arc::new(apple);
+ let fallback = with_fallback.then(|| apple.clone() as Arc<dyn Recognizer>);
+ let preferred = Arc::new(Preferred::new(local(installed.clone()), fallback));
+ let mic = Arc::new(FakeMicrophone::granted());
+ let clock = Arc::new(FakeClock(AtomicU64::new(0)));
+ let voice = Voice::new(mic.clone(), preferred.clone(), clock).with_final_timeout(Duration::from_millis(50));
+ Rig { voice, mic, apple, installed, preferred }
+ }
+
+ #[test]
+ fn without_the_model_apple_speech_records() {
+ let rig = rig(FakeRecognizer::granted(), true);
+ assert_eq!(rig.preferred.engine(), EngineName::Apple);
+ *rig.apple.final_text.lock().unwrap() = Some("apple heard".into());
+ rig.voice.start(Some("es-AR"), Recorder::default().events()).unwrap();
+ assert_eq!(rig.apple.log.lock().unwrap().locales, ["es-ES"]);
+ assert_eq!(rig.voice.stop(), Ok(Transcript { text: "apple heard".into() }));
+ }
+
+ #[test]
+ fn with_the_model_installed_parakeet_records_instead() {
+ let rig = rig(FakeRecognizer::granted(), true);
+ rig.installed.store(true, Ordering::SeqCst);
+ assert_eq!(rig.preferred.engine(), EngineName::Parakeet);
+ rig.voice.start(None, Recorder::default().events()).unwrap();
+ rig.mic.sink().audio(&[0.0; 320]);
+ assert_eq!(rig.voice.stop(), Ok(Transcript { text: "parakeet heard 320".into() }));
+ assert!(rig.apple.log.lock().unwrap().locales.is_empty(), "Apple Speech is not used");
+ }
+
+ #[test]
+ fn parakeet_needs_only_the_microphone_permission() {
+ let rig = rig(FakeRecognizer::with(Authorization::Denied, Authorization::Denied), true);
+ assert_eq!(rig.voice.status(), VoiceStatus::unavailable(VoiceError::SpeechDenied.to_string()));
+ rig.installed.store(true, Ordering::SeqCst);
+ assert_eq!(rig.voice.status(), VoiceStatus::available());
+ rig.voice.start(None, Recorder::default().events()).unwrap();
+ assert_eq!(rig.apple.log.lock().unwrap().requests, 0, "no Speech Recognition prompt");
+ rig.voice.cancel().unwrap();
+ }
+
+ #[test]
+ fn the_microphone_permission_still_applies_to_parakeet() {
+ let installed = Arc::new(AtomicBool::new(true));
+ let preferred = Arc::new(Preferred::new(local(installed), None));
+ let mic = Arc::new(FakeMicrophone::with(Authorization::Denied, Authorization::Denied));
+ let voice = Voice::new(mic, preferred, Arc::new(FakeClock(AtomicU64::new(0))));
+ assert_eq!(voice.status(), VoiceStatus::unavailable(VoiceError::MicrophoneDenied.to_string()));
+ }
+
+ #[test]
+ fn with_no_fallback_the_model_is_the_only_engine() {
+ let rig = rig(FakeRecognizer::granted(), false);
+ assert_eq!(rig.preferred.engine(), EngineName::None);
+ assert_eq!(rig.voice.status(), VoiceStatus::unavailable(VoiceError::NoModel.to_string()));
+ assert_eq!(rig.voice.start(None, Recorder::default().events()), Err(VoiceError::NoModel));
+ rig.installed.store(true, Ordering::SeqCst);
+ assert_eq!(rig.preferred.engine(), EngineName::Parakeet);
+ assert_eq!(rig.voice.status(), VoiceStatus::available());
+ }
+
+ #[test]
+ fn the_fallback_name_follows_the_platform() {
+ let expected = if cfg!(target_os = "macos") { EngineName::Apple } else { EngineName::None };
+ assert_eq!(fallback_engine(), expected);
+ }
+}
diff --git a/apps/desktop/src-tauri/src/voice/fake.rs b/apps/desktop/src-tauri/src/voice/fake.rs
index a218f2a..c916fff 100644
--- a/apps/desktop/src-tauri/src/voice/fake.rs
+++ b/apps/desktop/src-tauri/src/voice/fake.rs
@@ -19,7 +19,7 @@ impl Gate {
self.changed.notify_all();
}
- fn wait(&self) {
+ pub fn wait(&self) {
let mut open = self.open.lock().unwrap();
while !*open {
open = self.changed.wait(open).unwrap();
diff --git a/apps/desktop/src-tauri/src/voice/machine.rs b/apps/desktop/src-tauri/src/voice/machine.rs
index 1c3b8ec..1bcd935 100644
--- a/apps/desktop/src-tauri/src/voice/machine.rs
+++ b/apps/desktop/src-tauri/src/voice/machine.rs
@@ -140,7 +140,10 @@ impl Voice {
/// on the first `start`.
pub fn status(&self) -> VoiceStatus {
let (recognizer, microphone) = (&self.inner.recognizer, &self.inner.microphone);
- let reason = blocked(recognizer.authorization(), VoiceError::SpeechDenied, VoiceError::SpeechRestricted)
+ let reason = recognizer
+ .availability()
+ .err()
+ .or_else(|| blocked(recognizer.authorization(), VoiceError::SpeechDenied, VoiceError::SpeechRestricted))
.or_else(|| blocked(microphone.authorization(), VoiceError::MicrophoneDenied, VoiceError::MicrophoneRestricted))
.or_else(|| locale::resolve(None, &recognizer.current_locale(), &recognizer.supported_locales()).err());
match reason {
@@ -195,9 +198,11 @@ impl Voice {
Ok(())
}
- /// Locale first (no point prompting without a recognizer), then Speech, then Microphone.
+ /// Availability and locale first (no point prompting without a recognizer), then Speech,
+ /// then Microphone.
fn prepare(&self, requested: Option<&str>, recording: u64) -> Result<String, VoiceError> {
let (recognizer, microphone) = (&self.inner.recognizer, &self.inner.microphone);
+ recognizer.availability()?;
let locale = locale::resolve(requested, &recognizer.current_locale(), &recognizer.supported_locales())?;
authorize(recognizer.authorization(), || recognizer.request_authorization(), VoiceError::SpeechDenied, VoiceError::SpeechRestricted)?;
self.still_starting(recording)?;
@@ -214,7 +219,8 @@ impl Voice {
}
/// Stops the microphone and resolves with the final transcript, or the latest partial when
- /// the recognizer does not answer within the timeout. Blocks, so it runs off the main thread.
+ /// the recognizer does not answer within the timeout (the recognition's own, when it sets
+ /// one, else the machine's). Blocks, so it runs off the main thread.
pub fn stop(&self) -> Result<Transcript, VoiceError> {
let (recording, mut stream, feed) = {
let mut state = lock(&self.inner.state);
@@ -239,9 +245,13 @@ impl Voice {
if let Some(stream) = stream.as_mut() {
stream.close();
}
- lock(&feed).finish();
+ let timeout = {
+ let mut feed = lock(&feed);
+ feed.finish();
+ feed.recognition.final_timeout().unwrap_or(self.final_timeout)
+ };
- let deadline = Instant::now() + self.final_timeout;
+ let deadline = Instant::now() + timeout;
let mut state = lock(&self.inner.state);
loop {
let State::Stopping(session) = &*state else { return Err(VoiceError::Cancelled) };
diff --git a/apps/desktop/src-tauri/src/voice/mod.rs b/apps/desktop/src-tauri/src/voice/mod.rs
index 8496088..3836358 100644
--- a/apps/desktop/src-tauri/src/voice/mod.rs
+++ b/apps/desktop/src-tauri/src/voice/mod.rs
@@ -3,24 +3,32 @@
//!
//! - `Microphone` captures audio and delivers 16 kHz mono f32 PCM (`audio::SAMPLE_RATE`), the
//! format offline models such as sherpa-onnx expect, so any recognizer can consume it.
-//! - `Recognizer` turns that PCM into partial and final text. Apple's Speech framework is the
-//! default (`macos::AppleSpeech`); a local model can be added as a second implementation.
+//! - `Recognizer` turns that PCM into partial and final text. Apple's Speech framework
+//! (`macos::AppleSpeech`) is the default on macOS; the optional local model (S30.5,
+//! `parakeet::Parakeet`, NVIDIA Parakeet through sherpa-onnx) is preferred once the user has
+//! downloaded it (`model`), and it is the only engine on Linux (`engine::Preferred`).
//!
//! `Voice` is the pure state machine between them (idle → starting → recording → stopping,
//! single flight, cancel, error mapping, level throttling, locale fallback), tested on every OS
-//! with fakes. The objc2 bindings live in `macos`; off macOS the commands answer "unavailable".
+//! with fakes. The objc2 bindings live in `macos`; Linux records through a command-line recorder
+//! (`pipe`); elsewhere the commands answer "unavailable".
//!
//! SpeechAnalyzer/SpeechTranscriber (macOS 26) are Swift-only, with no Objective-C interface to
//! bind from Rust, and the app supports macOS 12.3, so `SFSpeechRecognizer` is the recognizer.
pub mod app;
pub mod audio;
+pub mod engine;
#[cfg(test)]
mod fake;
pub mod locale;
mod machine;
#[cfg(target_os = "macos")]
mod macos;
+pub mod model;
+pub mod parakeet;
+#[cfg(unix)]
+pub mod pipe;
pub use machine::{Sink, Voice};
#[cfg(target_os = "macos")]
@@ -29,6 +37,7 @@ pub use macos::{AppleSpeech, MacMicrophone};
use serde::Serialize;
use std::fmt;
use std::sync::Arc;
+use std::time::Duration;
/// Live text while the user speaks: `{text}`.
pub const PARTIAL_EVENT: &str = "voice://partial";
@@ -36,7 +45,7 @@ pub const PARTIAL_EVENT: &str = "voice://partial";
pub const LEVEL_EVENT: &str = "voice://level";
/// A failure while recording (permission, recognizer, interruption): `{message}`.
pub const ERROR_EVENT: &str = "voice://error";
-pub const UNSUPPORTED: &str = "Voice input is available on macOS.";
+pub const UNSUPPORTED: &str = "Voice input is available on macOS and Linux.";
/// The `voice_status` reply: `{available, reason?}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -112,7 +121,11 @@ pub enum VoiceError {
MicrophoneDenied,
MicrophoneRestricted,
NoRecognizer(String),
+ /// The local model is the only engine here (Linux) and it is not downloaded.
+ NoModel,
NoMicrophone,
+ /// Linux: neither `parec` nor `arecord` is installed.
+ NoRecorder,
Interrupted,
Failed(String),
}
@@ -134,7 +147,11 @@ impl fmt::Display for VoiceError {
),
VoiceError::MicrophoneRestricted => f.write_str("Microphone access is restricted on this Mac."),
VoiceError::NoRecognizer(locale) => write!(f, "Speech recognition is not available for {locale}."),
+ VoiceError::NoModel => f.write_str("Download the local voice model to use voice input."),
VoiceError::NoMicrophone => f.write_str("No microphone is available."),
+ VoiceError::NoRecorder => f.write_str(
+ "No audio recorder was found. Install pulseaudio-utils (parec) or alsa-utils (arecord).",
+ ),
VoiceError::Interrupted => f.write_str("The microphone was interrupted."),
VoiceError::Failed(message) => f.write_str(message),
}
@@ -166,6 +183,11 @@ pub trait Stream: Send {
/// `Sink::finished`, and `Sink::failed`, from any thread, but never from inside `feed`,
/// `finish`, or `cancel` while reporting a failure.
pub trait Recognizer: Send + Sync {
+ /// Whether this recognizer can work at all, apart from permissions (a local model that is
+ /// not downloaded cannot).
+ fn availability(&self) -> Result<(), VoiceError> {
+ Ok(())
+ }
/// The current permission, without prompting (`Authorized` when none is needed).
fn authorization(&self) -> Authorization;
/// Prompts when not yet determined. Blocks until the user answers: never on the main thread.
@@ -184,6 +206,11 @@ pub trait Recognition: Send {
fn finish(&mut self);
/// Discards the recognition.
fn cancel(&mut self);
+ /// How long `stop` waits for the final text, when this recognition needs longer than the
+ /// machine's default (an offline model decodes everything after `finish`).
+ fn final_timeout(&self) -> Option<Duration> {
+ None
+ }
}
#[cfg(test)]
@@ -205,7 +232,7 @@ mod tests {
assert_eq!(serde_json::to_value(VoiceStatus::available()).unwrap(), serde_json::json!({"available": true}));
assert_eq!(
serde_json::to_value(VoiceStatus::unavailable(UNSUPPORTED)).unwrap(),
- serde_json::json!({"available": false, "reason": "Voice input is available on macOS."})
+ serde_json::json!({"available": false, "reason": "Voice input is available on macOS and Linux."})
);
}
diff --git a/apps/desktop/src-tauri/src/voice/model.rs b/apps/desktop/src-tauri/src/voice/model.rs
new file mode 100644
index 0000000..7298e19
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/model.rs
@@ -0,0 +1,926 @@
+//! The optional local voice model (S30.5): NVIDIA Parakeet TDT 0.6B v3, int8, as sherpa-onnx
+//! publishes it. Nothing downloads unless the user asks. A download streams the official release
+//! asset into a staging directory next to the install, hashing it on the way; the SHA-256 and the
+//! size are pinned here. Only a verified archive is unpacked, and only the four model files at
+//! `<archive root>/<file>` are taken from it (any other path, `..` included, is ignored). The
+//! unpacked files then move into place with one rename, so a model directory is either complete
+//! or absent; failures and cancels remove the staging directory.
+//!
+//! Progress and outcomes go out as `voice://model` events, throttled to a few a second.
+
+use crate::computer::Clock;
+use serde::Serialize;
+use sha2::{Digest, Sha256};
+use std::fmt;
+use std::fs::{self, File};
+use std::io::{self, BufReader, Read, Write};
+use std::path::{Component, Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, MutexGuard};
+use std::time::Duration;
+
+/// `{state, received?, total?, message?}`, to the panel.
+pub const MODEL_EVENT: &str = "voice://model";
+/// At most one progress event per this many milliseconds (plus the last one).
+pub const PROGRESS_INTERVAL_MS: u64 = 250;
+const CHUNK: usize = 64 * 1024;
+const CANCELLED: &str = "The download was cancelled.";
+
+/// What to download and what it must contain.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ModelSpec {
+ pub url: String,
+ /// Lowercase hex SHA-256 of the archive.
+ pub sha256: String,
+ /// The archive's size in bytes.
+ pub size: u64,
+ /// The archive's top-level directory.
+ pub archive_root: String,
+ /// The install directory under the models directory.
+ pub dir: String,
+ /// The files the recognizer needs, all of them required.
+ pub files: Vec<String>,
+}
+
+impl ModelSpec {
+ /// The official sherpa-onnx release asset (tag `asr-models`), published 2025-08-16. The
+ /// SHA-256 was computed from the downloaded asset on 2026-10-09 and matches the digest
+ /// GitHub lists for it.
+ pub fn parakeet() -> Self {
+ ModelSpec {
+ url: "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2".into(),
+ sha256: "5793d0fd397c5778d2cf2126994d58e9d56b1be7c04d13c7a15bb1b4eafb16bf".into(),
+ size: 487_170_055,
+ archive_root: "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8".into(),
+ dir: "parakeet-tdt-0.6b-v3-int8".into(),
+ files: ["encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"].map(String::from).to_vec(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ModelState {
+ Downloading,
+ /// Checking the checksum and unpacking the model files.
+ Verifying,
+ Installed,
+ /// Failed or cancelled; `message` says which.
+ Failed,
+ Removed,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct ModelEvent {
+ pub state: ModelState,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub received: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub total: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+}
+
+impl ModelEvent {
+ pub fn state(state: ModelState) -> Self {
+ ModelEvent { state, received: None, total: None, message: None }
+ }
+
+ pub fn failed(message: impl Into<String>) -> Self {
+ ModelEvent { message: Some(message.into()), ..ModelEvent::state(ModelState::Failed) }
+ }
+
+ fn progress(received: u64, total: u64) -> Self {
+ ModelEvent { received: Some(received), total: Some(total), ..ModelEvent::state(ModelState::Downloading) }
+ }
+}
+
+/// The speech-to-text engine `voice_start` uses.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum EngineName {
+ Parakeet,
+ Apple,
+ None,
+}
+
+/// The `voice_model_status` reply.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct ModelStatus {
+ pub installed: bool,
+ /// The installed files' total size.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bytes: Option<u64>,
+ pub downloading: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub received: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub total: Option<u64>,
+ pub engine: EngineName,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ModelError {
+ Installed,
+ Downloading,
+ Failed(String),
+}
+
+impl fmt::Display for ModelError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ModelError::Installed => f.write_str("The local voice model is already installed."),
+ ModelError::Downloading => f.write_str("The local voice model is downloading. Cancel the download first."),
+ ModelError::Failed(message) => f.write_str(message),
+ }
+ }
+}
+
+impl From<ModelError> for String {
+ fn from(error: ModelError) -> String {
+ error.to_string()
+ }
+}
+
+/// An open download: the body, and its length when the server says.
+pub struct Download {
+ pub body: Box<dyn Read + Send>,
+ pub length: Option<u64>,
+}
+
+/// Opens a URL for reading. HTTPS in the app, an in-memory archive in tests.
+pub trait Fetcher: Send + Sync {
+ fn open(&self, url: &str) -> Result<Download, String>;
+}
+
+/// HTTPS through ureq (rustls with the bundled web PKI roots; `HTTPS_PROXY` is honored). GitHub
+/// answers the release URL with a redirect to its asset host, which is followed.
+pub struct HttpFetcher;
+
+impl Fetcher for HttpFetcher {
+ fn open(&self, url: &str) -> Result<Download, String> {
+ let agent = ureq::AgentBuilder::new()
+ .timeout_connect(Duration::from_secs(20))
+ .timeout_read(Duration::from_secs(60))
+ .try_proxy_from_env(true)
+ .https_only(true)
+ .build();
+ let response = agent.get(url).call().map_err(|error| error.to_string())?;
+ let length = response.header("Content-Length").and_then(|value| value.parse().ok());
+ Ok(Download { body: Box::new(response.into_reader()), length })
+ }
+}
+
+pub type ModelEvents = Arc<dyn Fn(ModelEvent) + Send + Sync>;
+
+/// Downloads, verifies, installs, and removes one model under a models directory.
+pub struct ModelManager {
+ shared: Arc<Shared>,
+}
+
+struct Shared {
+ spec: ModelSpec,
+ root: PathBuf,
+ fetcher: Arc<dyn Fetcher>,
+ clock: Arc<dyn Clock>,
+ events: ModelEvents,
+ /// The engine used while the model is absent.
+ fallback: EngineName,
+ job: Mutex<Option<Job>>,
+}
+
+/// The download in flight.
+struct Job {
+ cancel: Arc<AtomicBool>,
+ received: u64,
+ total: u64,
+}
+
+enum Failure {
+ Cancelled,
+ Error(String),
+}
+
+impl From<io::Error> for Failure {
+ fn from(error: io::Error) -> Self {
+ Failure::Error(format!("The local voice model could not be installed: {error}"))
+ }
+}
+
+fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()
+}
+
+/// Removes a directory this manager owns, if present.
+fn clear(path: &Path) -> io::Result<()> {
+ match fs::remove_dir_all(path) {
+ Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
+ _ => Ok(()),
+ }
+}
+
+impl ModelManager {
+ pub fn new(
+ spec: ModelSpec,
+ root: PathBuf,
+ fetcher: Arc<dyn Fetcher>,
+ clock: Arc<dyn Clock>,
+ events: ModelEvents,
+ fallback: EngineName,
+ ) -> Self {
+ let shared = Shared { spec, root, fetcher, clock, events, fallback, job: Mutex::new(None) };
+ ModelManager { shared: Arc::new(shared) }
+ }
+
+ /// The model directory, when every model file is in it.
+ pub fn installed(&self) -> Option<PathBuf> {
+ self.shared.installed()
+ }
+
+ pub fn status(&self) -> ModelStatus {
+ let (downloading, received, total) = match &*lock(&self.shared.job) {
+ Some(job) => (true, Some(job.received), Some(job.total)),
+ None => (false, None, None),
+ };
+ let dir = self.installed();
+ let bytes = dir.as_ref().map(|dir| self.shared.spec.files.iter().filter_map(|f| fs::metadata(dir.join(f)).ok()).map(|m| m.len()).sum());
+ let engine = if dir.is_some() { EngineName::Parakeet } else { self.shared.fallback };
+ ModelStatus { installed: dir.is_some(), bytes, downloading, received, total, engine }
+ }
+
+ /// Starts the download in the background; progress and the outcome arrive as events.
+ pub fn download(&self) -> Result<(), ModelError> {
+ let mut job = lock(&self.shared.job);
+ if job.is_some() {
+ return Err(ModelError::Downloading);
+ }
+ if self.installed().is_some() {
+ return Err(ModelError::Installed);
+ }
+ let cancel = Arc::new(AtomicBool::new(false));
+ let shared = self.shared.clone();
+ let flag = cancel.clone();
+ std::thread::Builder::new()
+ .name("voice-model-download".into())
+ .spawn(move || shared.run(&flag))
+ .map_err(|error| ModelError::Failed(format!("The download could not start: {error}")))?;
+ *job = Some(Job { cancel, received: 0, total: self.shared.spec.size });
+ Ok(())
+ }
+
+ /// Asks the download in flight to stop; whether there was one. The outcome arrives as a
+ /// `failed` event once the staging files are gone.
+ pub fn cancel(&self) -> bool {
+ lock(&self.shared.job).as_ref().map(|job| job.cancel.store(true, Ordering::SeqCst)).is_some()
+ }
+
+ /// Deletes the installed model (refused while downloading). Removing nothing is not an error.
+ pub fn remove(&self) -> Result<(), ModelError> {
+ let shared = &self.shared;
+ {
+ let job = lock(&shared.job);
+ if job.is_some() {
+ return Err(ModelError::Downloading);
+ }
+ let dir = shared.dir();
+ if fs::symlink_metadata(&dir).is_err() {
+ return Ok(());
+ }
+ // Out of sight in one step, then deleted.
+ let trash = shared.root.join(format!(".{}.removing", shared.spec.dir));
+ let removed = clear(&trash).and_then(|()| fs::rename(&dir, &trash)).and_then(|()| clear(&trash));
+ removed.map_err(|error| ModelError::Failed(format!("The local voice model could not be removed: {error}")))?;
+ }
+ (shared.events)(ModelEvent::state(ModelState::Removed));
+ Ok(())
+ }
+}
+
+impl Shared {
+ fn dir(&self) -> PathBuf {
+ self.root.join(&self.spec.dir)
+ }
+
+ fn staging(&self) -> PathBuf {
+ self.root.join(format!(".{}.download", self.spec.dir))
+ }
+
+ fn installed(&self) -> Option<PathBuf> {
+ let dir = self.dir();
+ self.spec.files.iter().all(|file| fs::metadata(dir.join(file)).is_ok_and(|m| m.is_file())).then_some(dir)
+ }
+
+ /// The download thread: run, clean up, clear the job, then report.
+ fn run(&self, cancel: &AtomicBool) {
+ let staging = self.staging();
+ let outcome = self.install(&staging, cancel);
+ if let Err(error) = clear(&staging) {
+ eprintln!("gentle-dot: cannot remove {}: {error}", staging.display());
+ }
+ *lock(&self.job) = None;
+ (self.events)(match outcome {
+ Ok(()) => ModelEvent::state(ModelState::Installed),
+ Err(Failure::Cancelled) => ModelEvent::failed(CANCELLED),
+ Err(Failure::Error(message)) => ModelEvent::failed(message),
+ });
+ }
+
+ fn install(&self, staging: &Path, cancel: &AtomicBool) -> Result<(), Failure> {
+ // A staging directory left by a crash is ours to clear.
+ clear(staging)?;
+ fs::create_dir_all(staging)?;
+ let archive = staging.join("archive.tar.bz2");
+ let digest = self.fetch(&archive, cancel)?;
+ (self.events)(ModelEvent::state(ModelState::Verifying));
+ if digest != self.spec.sha256 {
+ return Err(Failure::Error("The download did not match the published checksum.".into()));
+ }
+ let unpacked = staging.join("model");
+ self.extract(&archive, &unpacked, cancel)?;
+ fs::remove_file(&archive)?;
+ let dir = self.dir();
+ // An incomplete directory (not `installed`) is replaced.
+ clear(&dir)?;
+ fs::rename(&unpacked, &dir)?;
+ Ok(())
+ }
+
+ /// Streams the archive to `path`, reporting progress; the archive's SHA-256.
+ fn fetch(&self, path: &Path, cancel: &AtomicBool) -> Result<String, Failure> {
+ let total = self.spec.size;
+ let Download { mut body, length } = self
+ .fetcher
+ .open(&self.spec.url)
+ .map_err(|error| Failure::Error(format!("The local voice model could not be downloaded: {error}")))?;
+ let wrong_size = || Failure::Error("The download was not the expected size.".into());
+ if length.is_some_and(|length| length != total) {
+ return Err(wrong_size());
+ }
+ let mut file = File::create(path)?;
+ let mut hasher = Sha256::new();
+ let mut buffer = vec![0; CHUNK];
+ let (mut received, mut reported) = (0u64, 0u64);
+ let mut last_ms = self.clock.now_ms();
+ (self.events)(ModelEvent::progress(0, total));
+ loop {
+ if cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ let read = match body.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(read) => read,
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
+ Err(error) => return Err(Failure::Error(format!("The download was interrupted: {error}"))),
+ };
+ received += read as u64;
+ if received > total {
+ return Err(wrong_size());
+ }
+ hasher.update(&buffer[..read]);
+ file.write_all(&buffer[..read])?;
+ if let Some(job) = lock(&self.job).as_mut() {
+ job.received = received;
+ }
+ let now = self.clock.now_ms();
+ if now.saturating_sub(last_ms) >= PROGRESS_INTERVAL_MS {
+ last_ms = now;
+ reported = received;
+ (self.events)(ModelEvent::progress(received, total));
+ }
+ }
+ if cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ if received != total {
+ return Err(wrong_size());
+ }
+ if reported != received {
+ (self.events)(ModelEvent::progress(received, total));
+ }
+ file.sync_all()?;
+ Ok(hex(&hasher.finalize()))
+ }
+
+ /// The model file an archive path names: exactly `<archive root>/<one of the files>`.
+ fn model_file(&self, path: &Path) -> Option<&str> {
+ let mut parts = path.components().filter(|part| *part != Component::CurDir);
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some(Component::Normal(root)), Some(Component::Normal(name)), None) if root == self.spec.archive_root.as_str() => {
+ self.spec.files.iter().find(|file| name == file.as_str()).map(String::as_str)
+ }
+ _ => None,
+ }
+ }
+
+ /// Unpacks the model files of a verified archive into `into`, which must not exist.
+ fn extract(&self, archive: &Path, into: &Path, cancel: &AtomicBool) -> Result<(), Failure> {
+ fs::create_dir(into)?;
+ let mut archive = tar::Archive::new(bzip2::read::BzDecoder::new(BufReader::new(File::open(archive)?)));
+ for entry in archive.entries()? {
+ let mut entry = entry?;
+ if cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ if !entry.header().entry_type().is_file() {
+ continue;
+ }
+ let path = entry.path()?.into_owned();
+ let Some(name) = self.model_file(&path) else { continue };
+ let mut out = File::create_new(into.join(name))?;
+ let mut buffer = vec![0; CHUNK];
+ loop {
+ if cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ let read = entry.read(&mut buffer)?;
+ if read == 0 {
+ break;
+ }
+ out.write_all(&buffer[..read])?;
+ }
+ out.sync_all()?;
+ }
+ let missing: Vec<&str> = self.spec.files.iter().filter(|file| !into.join(file).is_file()).map(String::as_str).collect();
+ if !missing.is_empty() {
+ return Err(Failure::Error(format!("The downloaded model is missing {}.", missing.join(", "))));
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::voice::fake::FakeClock;
+ use bzip2::write::BzEncoder;
+ use sha2::{Digest, Sha256};
+ use std::io::{Cursor, Read};
+ use std::sync::atomic::AtomicU64;
+ use std::sync::mpsc;
+ use std::sync::{Arc, Condvar, Mutex};
+ use std::time::Duration;
+
+ const FILES: [&str; 4] = ["encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"];
+
+ /// A tar.bz2 shaped like the sherpa-onnx release: `<root>/<file>` plus files to skip.
+ fn archive(root: &str, files: &[(&str, &[u8])]) -> Vec<u8> {
+ let paths: Vec<(String, &[u8])> = files.iter().map(|(name, data)| (format!("{root}/{name}"), *data)).collect();
+ raw_archive(&paths.iter().map(|(path, data)| (path.as_str(), *data)).collect::<Vec<_>>())
+ }
+
+ /// Entries written with the exact path bytes, `..` included (the builder refuses those).
+ fn raw_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
+ let mut builder = tar::Builder::new(BzEncoder::new(Vec::new(), bzip2::Compression::fast()));
+ for (path, data) in entries {
+ let mut header = tar::Header::new_old();
+ header.as_old_mut().name[..path.len()].copy_from_slice(path.as_bytes());
+ header.set_size(data.len() as u64);
+ header.set_mode(0o644);
+ header.set_entry_type(tar::EntryType::Regular);
+ header.set_cksum();
+ builder.append(&header, *data).unwrap();
+ }
+ builder.into_inner().unwrap().finish().unwrap()
+ }
+
+ /// Bytes bzip2 cannot shrink, so the archive spans many reads.
+ fn noise(len: usize) -> Vec<u8> {
+ let mut state = 0x2545_f491u32;
+ (0..len)
+ .map(|_| {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ state as u8
+ })
+ .collect()
+ }
+
+ fn full_archive() -> Vec<u8> {
+ archive(
+ "release-root",
+ &[
+ ("tokens.txt", b"<blk> 0\n"),
+ ("encoder.int8.onnx", &noise(20_000)),
+ ("decoder.int8.onnx", &[2u8; 200]),
+ ("joiner.int8.onnx", &[3u8; 100]),
+ ("test_wavs/en.wav", b"RIFF"),
+ ],
+ )
+ }
+
+ fn sha(bytes: &[u8]) -> String {
+ Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
+ }
+
+ fn spec_for(bytes: &[u8]) -> ModelSpec {
+ ModelSpec {
+ url: "https://example.invalid/model.tar.bz2".into(),
+ sha256: sha(bytes),
+ size: bytes.len() as u64,
+ archive_root: "release-root".into(),
+ dir: "parakeet-test".into(),
+ files: FILES.map(String::from).to_vec(),
+ }
+ }
+
+ /// Holds the body after its first chunk, so a test can look at a download in flight.
+ #[derive(Default)]
+ struct Pause {
+ /// (reached, released)
+ state: Mutex<(bool, bool)>,
+ changed: Condvar,
+ }
+
+ impl Pause {
+ fn wait_reached(&self) {
+ let mut state = self.state.lock().unwrap();
+ while !state.0 {
+ state = self.changed.wait_timeout(state, Duration::from_secs(5)).unwrap().0;
+ }
+ }
+
+ fn release(&self) {
+ self.state.lock().unwrap().1 = true;
+ self.changed.notify_all();
+ }
+
+ fn hold(&self) {
+ let mut state = self.state.lock().unwrap();
+ state.0 = true;
+ self.changed.notify_all();
+ while !state.1 {
+ state = self.changed.wait(state).unwrap();
+ }
+ }
+ }
+
+ struct Body {
+ data: Cursor<Vec<u8>>,
+ chunk: usize,
+ pause: Option<Arc<Pause>>,
+ clock: Arc<FakeClock>,
+ served: usize,
+ }
+
+ impl Read for Body {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ if let (Some(pause), true) = (&self.pause, self.served > 0) {
+ pause.hold();
+ }
+ let n = buf.len().min(self.chunk);
+ let read = self.data.read(&mut buf[..n])?;
+ self.served += read;
+ self.clock.advance(100);
+ Ok(read)
+ }
+ }
+
+ struct FakeFetcher {
+ body: Vec<u8>,
+ length: Option<u64>,
+ chunk: usize,
+ pause: Option<Arc<Pause>>,
+ clock: Arc<FakeClock>,
+ urls: Mutex<Vec<String>>,
+ }
+
+ impl Fetcher for FakeFetcher {
+ fn open(&self, url: &str) -> Result<Download, String> {
+ self.urls.lock().unwrap().push(url.to_string());
+ let body = Body {
+ data: Cursor::new(self.body.clone()),
+ chunk: self.chunk,
+ pause: self.pause.clone(),
+ clock: self.clock.clone(),
+ served: 0,
+ };
+ Ok(Download { body: Box::new(body), length: self.length })
+ }
+ }
+
+ struct Rig {
+ manager: ModelManager,
+ fetcher: Arc<FakeFetcher>,
+ events: mpsc::Receiver<ModelEvent>,
+ root: PathBuf,
+ }
+
+ fn temp_root(name: &str) -> PathBuf {
+ let root = std::env::temp_dir().join(format!("gentle-dot-model-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ root
+ }
+
+ fn rig(name: &str, body: Vec<u8>, spec: ModelSpec, pause: Option<Arc<Pause>>) -> Rig {
+ let clock = Arc::new(FakeClock(AtomicU64::new(0)));
+ let length = Some(body.len() as u64);
+ let fetcher = Arc::new(FakeFetcher { body, length, chunk: 512, pause, clock: clock.clone(), urls: Mutex::default() });
+ let (tx, events) = mpsc::channel();
+ let tx = Mutex::new(tx);
+ let root = temp_root(name);
+ let manager = ModelManager::new(
+ spec,
+ root.clone(),
+ fetcher.clone(),
+ clock,
+ Arc::new(move |event| {
+ let _ = tx.lock().unwrap().send(event);
+ }),
+ EngineName::Apple,
+ );
+ Rig { manager, fetcher, events, root }
+ }
+
+ impl Rig {
+ /// Every event up to and including the next terminal one.
+ fn until_done(&self) -> Vec<ModelEvent> {
+ let mut seen = Vec::new();
+ loop {
+ let event = self.events.recv_timeout(Duration::from_secs(10)).expect("a model event");
+ let done = matches!(event.state, ModelState::Installed | ModelState::Failed | ModelState::Removed);
+ seen.push(event);
+ if done {
+ return seen;
+ }
+ }
+ }
+
+ fn leftovers(&self) -> Vec<String> {
+ let Ok(entries) = std::fs::read_dir(&self.root) else { return Vec::new() };
+ let mut names: Vec<String> = entries.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ names.sort();
+ names
+ }
+ }
+
+ #[test]
+ fn the_pinned_parakeet_asset_is_the_official_int8_release() {
+ let spec = ModelSpec::parakeet();
+ assert_eq!(
+ spec.url,
+ "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2"
+ );
+ assert_eq!(spec.sha256, "5793d0fd397c5778d2cf2126994d58e9d56b1be7c04d13c7a15bb1b4eafb16bf");
+ assert_eq!(spec.size, 487_170_055);
+ assert_eq!(spec.archive_root, "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8");
+ assert_eq!(spec.dir, "parakeet-tdt-0.6b-v3-int8");
+ assert_eq!(spec.files, FILES.map(String::from).to_vec());
+ }
+
+ #[test]
+ fn status_before_any_download_reports_the_fallback_engine() {
+ let rig = rig("status", full_archive(), spec_for(&full_archive()), None);
+ let status = rig.manager.status();
+ assert_eq!(
+ serde_json::to_value(&status).unwrap(),
+ serde_json::json!({"installed": false, "downloading": false, "engine": "apple"})
+ );
+ assert_eq!(rig.manager.installed(), None);
+ }
+
+ #[test]
+ fn a_download_reports_progress_verifies_and_installs_only_the_model_files() {
+ let body = full_archive();
+ let rig = rig("install", body.clone(), spec_for(&body), None);
+ rig.manager.download().unwrap();
+ let events = rig.until_done();
+ assert_eq!(rig.fetcher.urls.lock().unwrap().as_slice(), ["https://example.invalid/model.tar.bz2"]);
+
+ let first = &events[0];
+ assert_eq!((first.state, first.received, first.total), (ModelState::Downloading, Some(0), Some(body.len() as u64)));
+ let progress: Vec<u64> = events.iter().filter(|e| e.state == ModelState::Downloading).filter_map(|e| e.received).collect();
+ assert!(progress.windows(2).all(|w| w[0] < w[1]), "progress grows: {progress:?}");
+ assert_eq!(progress.last(), Some(&(body.len() as u64)), "the last progress is the whole body");
+ assert!(
+ progress.len() < body.len().div_ceil(512),
+ "progress is throttled, not one event per chunk ({} events)",
+ progress.len()
+ );
+ assert!(events.iter().any(|e| e.state == ModelState::Verifying));
+ assert_eq!(events.last().unwrap().state, ModelState::Installed);
+
+ let dir = rig.root.join("parakeet-test");
+ assert_eq!(rig.manager.installed(), Some(dir.clone()));
+ let mut names: Vec<String> =
+ std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ names.sort();
+ assert_eq!(names, ["decoder.int8.onnx", "encoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"]);
+ assert_eq!(std::fs::read(dir.join("encoder.int8.onnx")).unwrap(), noise(20_000));
+ assert_eq!(rig.leftovers(), ["parakeet-test"], "no staging files remain");
+
+ let status = rig.manager.status();
+ assert_eq!(
+ serde_json::to_value(&status).unwrap(),
+ serde_json::json!({"installed": true, "bytes": 20_000 + 200 + 100 + 8, "downloading": false, "engine": "parakeet"})
+ );
+ assert_eq!(rig.manager.download(), Err(ModelError::Installed));
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn a_checksum_mismatch_fails_and_leaves_nothing_behind() {
+ let body = full_archive();
+ let mut spec = spec_for(&body);
+ spec.sha256 = "0".repeat(64);
+ let rig = rig("mismatch", body, spec, None);
+ rig.manager.download().unwrap();
+ let last = rig.until_done().pop().unwrap();
+ assert_eq!(last.state, ModelState::Failed);
+ assert!(last.message.unwrap().contains("did not match"), "the reason is the checksum");
+ assert_eq!(rig.manager.installed(), None);
+ assert!(rig.leftovers().is_empty(), "staging removed: {:?}", rig.leftovers());
+ assert!(!rig.manager.status().downloading);
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn a_body_of_the_wrong_size_fails() {
+ let body = full_archive();
+ let mut spec = spec_for(&body);
+ spec.size += 1;
+ let rig = rig("size", body, spec, None);
+ rig.manager.download().unwrap();
+ let last = rig.until_done().pop().unwrap();
+ assert_eq!(last.state, ModelState::Failed);
+ assert!(rig.leftovers().is_empty());
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn an_archive_missing_a_model_file_is_not_installed() {
+ let body = archive("release-root", &[("tokens.txt", b"x"), ("encoder.int8.onnx", b"e"), ("decoder.int8.onnx", b"d")]);
+ let rig = rig("missing", body.clone(), spec_for(&body), None);
+ rig.manager.download().unwrap();
+ let last = rig.until_done().pop().unwrap();
+ assert_eq!(last.state, ModelState::Failed);
+ assert!(last.message.unwrap().contains("joiner.int8.onnx"));
+ assert_eq!(rig.manager.installed(), None);
+ assert!(rig.leftovers().is_empty());
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn entries_outside_the_release_root_are_ignored() {
+ let body = raw_archive(&[
+ ("other-root/tokens.txt", b"t"),
+ ("release-root/../tokens.txt", b"t"),
+ ("../encoder.int8.onnx", b"e"),
+ ("/release-root/encoder.int8.onnx", b"e"),
+ ("release-root/nested/decoder.int8.onnx", b"d"),
+ ("release-root/joiner.int8.onnx", b"j"),
+ ]);
+ let rig = rig("outside", body.clone(), spec_for(&body), None);
+ rig.manager.download().unwrap();
+ let last = rig.until_done().pop().unwrap();
+ assert_eq!(last.state, ModelState::Failed);
+ let message = last.message.unwrap();
+ assert_eq!(
+ message, "The downloaded model is missing encoder.int8.onnx, decoder.int8.onnx, tokens.txt.",
+ "only release-root/<file> counts"
+ );
+ assert!(rig.leftovers().is_empty());
+ assert!(!rig.root.parent().unwrap().join("encoder.int8.onnx").exists());
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn a_download_in_flight_is_reported_not_installed_and_can_be_cancelled() {
+ let body = full_archive();
+ let pause = Arc::new(Pause::default());
+ let rig = rig("cancel", body.clone(), spec_for(&body), Some(pause.clone()));
+ rig.manager.download().unwrap();
+ pause.wait_reached();
+
+ let status = rig.manager.status();
+ assert!(status.downloading && !status.installed);
+ assert_eq!((status.received, status.total), (Some(512), Some(body.len() as u64)));
+ assert_eq!(rig.manager.download(), Err(ModelError::Downloading));
+ assert_eq!(rig.manager.remove(), Err(ModelError::Downloading));
+ assert!(!rig.root.join("parakeet-test").exists(), "nothing is installed until the end");
+
+ assert!(rig.manager.cancel());
+ pause.release();
+ let last = rig.until_done().pop().unwrap();
+ assert_eq!(last.state, ModelState::Failed);
+ assert_eq!(last.message.as_deref(), Some("The download was cancelled."));
+ assert!(rig.leftovers().is_empty(), "staging removed: {:?}", rig.leftovers());
+ assert!(!rig.manager.status().downloading);
+ assert!(!rig.manager.cancel(), "nothing left to cancel");
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn remove_deletes_the_model_and_reports_it() {
+ let body = full_archive();
+ let rig = rig("remove", body.clone(), spec_for(&body), None);
+ rig.manager.download().unwrap();
+ assert_eq!(rig.until_done().pop().unwrap().state, ModelState::Installed);
+
+ rig.manager.remove().unwrap();
+ assert_eq!(rig.until_done(), vec![ModelEvent::state(ModelState::Removed)]);
+ assert_eq!(rig.manager.installed(), None);
+ assert!(rig.leftovers().is_empty());
+ assert_eq!(rig.manager.status().engine, EngineName::Apple);
+ rig.manager.remove().unwrap();
+ assert!(rig.events.try_recv().is_err(), "removing nothing reports nothing");
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn a_staging_directory_left_by_a_crash_is_cleared_by_the_next_download() {
+ let body = full_archive();
+ let rig = rig("stale", body.clone(), spec_for(&body), None);
+ let stale = rig.root.join(".parakeet-test.download");
+ std::fs::create_dir_all(stale.join("model")).unwrap();
+ std::fs::write(stale.join("archive.tar.bz2"), b"partial").unwrap();
+ rig.manager.download().unwrap();
+ assert_eq!(rig.until_done().pop().unwrap().state, ModelState::Installed);
+ assert_eq!(rig.leftovers(), ["parakeet-test"]);
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ #[test]
+ fn an_incomplete_install_does_not_count() {
+ let rig = rig("partial", Vec::new(), spec_for(&[]), None);
+ let dir = rig.root.join("parakeet-test");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("tokens.txt"), b"t").unwrap();
+ assert_eq!(rig.manager.installed(), None);
+ let _ = std::fs::remove_dir_all(&rig.root);
+ }
+
+ /// Reads a local copy of the release asset.
+ struct FileFetcher(PathBuf);
+
+ impl Fetcher for FileFetcher {
+ fn open(&self, _url: &str) -> Result<Download, String> {
+ let file = std::fs::File::open(&self.0).map_err(|e| e.to_string())?;
+ let length = file.metadata().map_err(|e| e.to_string())?.len();
+ Ok(Download { body: Box::new(file), length: Some(length) })
+ }
+ }
+
+ /// Installs from a downloaded copy of the real asset, checking the pinned SHA-256 and the
+ /// release's layout. Run with
+ /// `GENTLE_DOT_PARAKEET_ARCHIVE=<the .tar.bz2> cargo test -- --ignored real_parakeet_archive`.
+ #[test]
+ #[ignore = "needs the real Parakeet archive (487 MB)"]
+ fn real_parakeet_archive_installs() {
+ let Some(archive) = std::env::var_os("GENTLE_DOT_PARAKEET_ARCHIVE").map(PathBuf::from) else {
+ eprintln!("GENTLE_DOT_PARAKEET_ARCHIVE is not set; skipping");
+ return;
+ };
+ let (tx, events) = mpsc::channel();
+ let tx = Mutex::new(tx);
+ let root = temp_root("real");
+ let manager = ModelManager::new(
+ ModelSpec::parakeet(),
+ root.clone(),
+ Arc::new(FileFetcher(archive)),
+ Arc::new(crate::computer::SystemClock),
+ Arc::new(move |event| {
+ let _ = tx.lock().unwrap().send(event);
+ }),
+ EngineName::Apple,
+ );
+ let started = std::time::Instant::now();
+ manager.download().unwrap();
+ let last = loop {
+ let event: ModelEvent = events.recv_timeout(Duration::from_secs(600)).unwrap();
+ if matches!(event.state, ModelState::Installed | ModelState::Failed) {
+ break event;
+ }
+ };
+ eprintln!("installed in {:?}: {:?}", started.elapsed(), manager.status());
+ assert_eq!(last.state, ModelState::Installed, "{:?}", last.message);
+ assert_eq!(manager.status().bytes, Some(670_478_772));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn events_carry_the_contract_shape() {
+ assert_eq!(MODEL_EVENT, "voice://model");
+ let progress = ModelEvent { state: ModelState::Downloading, received: Some(5), total: Some(10), message: None };
+ assert_eq!(
+ serde_json::to_value(progress).unwrap(),
+ serde_json::json!({"state": "downloading", "received": 5, "total": 10})
+ );
+ let failed = ModelEvent::failed("no");
+ assert_eq!(serde_json::to_value(failed).unwrap(), serde_json::json!({"state": "failed", "message": "no"}));
+ for (state, name) in [
+ (ModelState::Verifying, "verifying"),
+ (ModelState::Installed, "installed"),
+ (ModelState::Removed, "removed"),
+ ] {
+ assert_eq!(serde_json::to_value(ModelEvent::state(state)).unwrap(), serde_json::json!({"state": name}));
+ }
+ for (engine, name) in [(EngineName::Parakeet, "parakeet"), (EngineName::Apple, "apple"), (EngineName::None, "none")] {
+ assert_eq!(serde_json::to_value(engine).unwrap(), serde_json::json!(name));
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/voice/parakeet.rs b/apps/desktop/src-tauri/src/voice/parakeet.rs
new file mode 100644
index 0000000..dc15a59
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/parakeet.rs
@@ -0,0 +1,515 @@
+//! The local model backend (S30.5): NVIDIA Parakeet TDT 0.6B v3 (int8) through sherpa-onnx's
+//! offline transducer recognizer, on the CPU. Parakeet is not streaming: a recognition keeps the
+//! recording's PCM and decodes it once `finish` is called, on a thread of its own, then answers
+//! through `Sink::finished`. There are no partials. It detects the language itself (25 European
+//! languages), so the locale is ignored, and it needs no Speech Recognition permission.
+//!
+//! The loaded model (about 0.7 GB in memory) is shared by recordings: loading starts in the
+//! background when a recording begins, so it overlaps the speaking, and the model is dropped
+//! after `IDLE_UNLOAD` without use, or when the files are removed (`release`).
+
+use super::audio::SAMPLE_RATE;
+use super::{Authorization, Recognition, Recognizer, Sink, VoiceError};
+use sherpa_onnx::{OfflineRecognizer, OfflineRecognizerConfig, OfflineTransducerModelConfig};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, MutexGuard};
+use std::time::Duration;
+
+/// sherpa-onnx's name for NeMo transducers such as Parakeet TDT.
+pub const MODEL_TYPE: &str = "nemo_transducer";
+/// Five minutes at 16 kHz; later audio is dropped.
+pub const MAX_SAMPLES: usize = SAMPLE_RATE as usize * 300;
+/// How long `stop` waits for a transcript: a cold load plus decoding a long recording.
+pub const DECODE_TIMEOUT: Duration = Duration::from_secs(60);
+/// An unused model is dropped after this long.
+pub const IDLE_UNLOAD: Duration = Duration::from_secs(300);
+/// The locale Parakeet reports: it picks the language from the audio.
+const AUTO: &str = "auto";
+
+/// Decoding threads: up to four, leaving the rest of the machine alone.
+pub fn threads() -> i32 {
+ std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 4) as i32
+}
+
+/// The recognizer configuration for a model directory holding the release's int8 files.
+pub fn config(dir: &Path, threads: i32) -> OfflineRecognizerConfig {
+ let path = |name: &str| Some(dir.join(name).display().to_string());
+ let mut config = OfflineRecognizerConfig::default();
+ config.model_config.transducer = OfflineTransducerModelConfig {
+ encoder: path("encoder.int8.onnx"),
+ decoder: path("decoder.int8.onnx"),
+ joiner: path("joiner.int8.onnx"),
+ };
+ config.model_config.tokens = path("tokens.txt");
+ config.model_config.model_type = Some(MODEL_TYPE.into());
+ config.model_config.provider = Some("cpu".into());
+ config.model_config.num_threads = threads;
+ config.model_config.debug = false;
+ config.decoding_method = Some("greedy_search".into());
+ config.feat_config.sample_rate = SAMPLE_RATE as i32;
+ config.feat_config.feature_dim = 80;
+ config
+}
+
+/// A loaded model: 16 kHz mono PCM in, text out. Blocks while decoding.
+pub trait Engine: Send + Sync {
+ fn transcribe(&self, samples: &[f32]) -> Result<String, String>;
+}
+
+/// Where the installed model is, if it is.
+pub type Locate = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
+/// Loads the model in a directory. Slow (seconds), so never on the main thread.
+pub type Loader = Arc<dyn Fn(&Path) -> Result<Arc<dyn Engine>, String> + Send + Sync>;
+
+struct Sherpa(OfflineRecognizer);
+
+impl Engine for Sherpa {
+ fn transcribe(&self, samples: &[f32]) -> Result<String, String> {
+ let stream = self.0.create_stream();
+ stream.accept_waveform(SAMPLE_RATE as i32, samples);
+ self.0.decode(&stream);
+ stream.get_result().map(|result| result.text).ok_or_else(|| "The local voice model returned no result.".into())
+ }
+}
+
+/// Loads Parakeet with sherpa-onnx.
+pub fn load(dir: &Path) -> Result<Arc<dyn Engine>, String> {
+ OfflineRecognizer::create(&config(dir, threads()))
+ .map(|recognizer| Arc::new(Sherpa(recognizer)) as Arc<dyn Engine>)
+ .ok_or_else(|| "The local voice model could not be loaded. Remove it and download it again.".into())
+}
+
+fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// The shared loaded model.
+struct Cache {
+ loader: Loader,
+ slot: Mutex<Option<(PathBuf, Arc<dyn Engine>)>>,
+ /// Bumped on every use, so an idle timer knows whether the model was used since.
+ uses: AtomicU64,
+}
+
+impl Cache {
+ /// The model in `dir`, loading it (once) if needed; concurrent callers wait for one load.
+ /// Each use restarts the idle countdown.
+ fn get(self: &Arc<Self>, dir: &Path, idle: Duration) -> Result<Arc<dyn Engine>, String> {
+ self.uses.fetch_add(1, Ordering::SeqCst);
+ let engine = {
+ let mut slot = lock(&self.slot);
+ match slot.as_ref() {
+ Some((loaded, engine)) if loaded == dir => engine.clone(),
+ _ => {
+ // Another model's memory goes before the next one loads.
+ *slot = None;
+ let engine = (self.loader)(dir)?;
+ *slot = Some((dir.to_path_buf(), engine.clone()));
+ engine
+ }
+ }
+ };
+ self.unload_when_idle(idle);
+ Ok(engine)
+ }
+
+ fn release(&self) {
+ *lock(&self.slot) = None;
+ }
+
+ /// Drops the model after `idle` unless it is used again before.
+ fn unload_when_idle(self: &Arc<Self>, idle: Duration) {
+ let mark = self.uses.load(Ordering::SeqCst);
+ let cache = Arc::downgrade(self);
+ let _ = std::thread::Builder::new().name("voice-model-idle".into()).spawn(move || {
+ std::thread::sleep(idle);
+ if let Some(cache) = cache.upgrade() {
+ if cache.uses.load(Ordering::SeqCst) == mark {
+ cache.release();
+ }
+ }
+ });
+ }
+}
+
+/// The Parakeet recognizer, present when the model is installed.
+pub struct Parakeet {
+ locate: Locate,
+ cache: Arc<Cache>,
+ idle: Duration,
+}
+
+impl Parakeet {
+ pub fn new(locate: Locate, loader: Loader) -> Self {
+ let cache = Cache { loader, slot: Mutex::new(None), uses: AtomicU64::new(0) };
+ Parakeet { locate, cache: Arc::new(cache), idle: IDLE_UNLOAD }
+ }
+
+ pub fn with_idle(mut self, idle: Duration) -> Self {
+ self.idle = idle;
+ self
+ }
+
+ pub fn installed(&self) -> bool {
+ (self.locate)().is_some()
+ }
+
+ /// Whether the model is in memory.
+ pub fn loaded(&self) -> bool {
+ lock(&self.cache.slot).is_some()
+ }
+
+ /// Drops the loaded model (its files were removed). A decode in flight keeps its copy.
+ pub fn release(&self) {
+ self.cache.release();
+ }
+}
+
+impl Recognizer for Parakeet {
+ fn availability(&self) -> Result<(), VoiceError> {
+ if self.installed() {
+ Ok(())
+ } else {
+ Err(VoiceError::NoModel)
+ }
+ }
+
+ fn authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn request_authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn current_locale(&self) -> String {
+ AUTO.into()
+ }
+
+ fn supported_locales(&self) -> Vec<String> {
+ vec![AUTO.into()]
+ }
+
+ fn begin(&self, _locale: &str, sink: Sink) -> Result<Box<dyn Recognition>, VoiceError> {
+ let dir = (self.locate)().ok_or(VoiceError::NoModel)?;
+ // Load while the user speaks; `finish` waits for this load instead of starting another.
+ let (cache, warm, idle) = (self.cache.clone(), dir.clone(), self.idle);
+ let _ = std::thread::Builder::new().name("voice-model-load".into()).spawn(move || {
+ if let Err(error) = cache.get(&warm, idle) {
+ eprintln!("gentle-dot: {error}");
+ }
+ });
+ let cancelled = Arc::new(AtomicBool::new(false));
+ Ok(Box::new(ParakeetRecognition {
+ dir,
+ sink,
+ cache: self.cache.clone(),
+ idle: self.idle,
+ samples: Samples::default(),
+ cancelled,
+ }))
+ }
+}
+
+/// The recording so far, capped at `MAX_SAMPLES`.
+#[derive(Default)]
+pub(crate) struct Samples(Vec<f32>);
+
+impl Samples {
+ pub(crate) fn push(&mut self, samples: &[f32]) {
+ let room = MAX_SAMPLES.saturating_sub(self.0.len());
+ self.0.extend_from_slice(&samples[..samples.len().min(room)]);
+ }
+
+ pub(crate) fn take(&mut self) -> Vec<f32> {
+ std::mem::take(&mut self.0)
+ }
+}
+
+struct ParakeetRecognition {
+ dir: PathBuf,
+ sink: Sink,
+ cache: Arc<Cache>,
+ idle: Duration,
+ samples: Samples,
+ cancelled: Arc<AtomicBool>,
+}
+
+impl Recognition for ParakeetRecognition {
+ fn feed(&mut self, samples: &[f32]) {
+ self.samples.push(samples);
+ }
+
+ fn finish(&mut self) {
+ let samples = self.samples.take();
+ let (dir, sink, cache, idle, cancelled) =
+ (self.dir.clone(), self.sink.clone(), self.cache.clone(), self.idle, self.cancelled.clone());
+ let decode = move || {
+ let result = cache.get(&dir, idle).and_then(|engine| {
+ if cancelled.load(Ordering::SeqCst) {
+ return Ok(None);
+ }
+ engine.transcribe(&samples).map(Some)
+ });
+ match result {
+ Ok(Some(text)) => sink.finished(text.trim()),
+ Ok(None) => {}
+ Err(error) => {
+ eprintln!("gentle-dot: {error}");
+ sink.failed(&error);
+ }
+ }
+ };
+ if let Err(error) = std::thread::Builder::new().name("voice-model-decode".into()).spawn(decode) {
+ // `finish` runs while stopping, where a failure only resolves `stop`.
+ self.sink.failed(&format!("The local voice model could not start: {error}"));
+ }
+ }
+
+ fn cancel(&mut self) {
+ self.cancelled.store(true, Ordering::SeqCst);
+ self.samples.take();
+ }
+
+ fn final_timeout(&self) -> Option<Duration> {
+ Some(DECODE_TIMEOUT)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::voice::fake::{FakeClock, FakeMicrophone, Gate, Recorder};
+ use crate::voice::{Authorization, Recognizer, Transcript, Voice, VoiceError, VoiceStatus};
+ use std::path::{Path, PathBuf};
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::time::Duration;
+
+ #[test]
+ fn the_config_points_at_the_int8_transducer_files_of_the_model_dir() {
+ let dir = Path::new("/models/parakeet-tdt-0.6b-v3-int8");
+ let config = config(dir, 3);
+ let model = &config.model_config;
+ let path = |name: &str| Some(dir.join(name).display().to_string());
+ assert_eq!(model.transducer.encoder, path("encoder.int8.onnx"));
+ assert_eq!(model.transducer.decoder, path("decoder.int8.onnx"));
+ assert_eq!(model.transducer.joiner, path("joiner.int8.onnx"));
+ assert_eq!(model.tokens, path("tokens.txt"));
+ assert_eq!(model.model_type.as_deref(), Some("nemo_transducer"));
+ assert_eq!(MODEL_TYPE, "nemo_transducer");
+ assert_eq!(model.provider.as_deref(), Some("cpu"));
+ assert_eq!(model.num_threads, 3);
+ assert!(!model.debug);
+ assert_eq!(config.decoding_method.as_deref(), Some("greedy_search"));
+ assert_eq!(config.feat_config.sample_rate, 16_000);
+ assert_eq!(config.feat_config.feature_dim, 80);
+ }
+
+ #[test]
+ fn decoding_uses_a_few_threads() {
+ assert!((1..=4).contains(&threads()));
+ }
+
+ /// Transcribes to "<n> samples", once the gate (if any) opens, recording the thread.
+ struct FakeEngine {
+ gate: Option<Arc<Gate>>,
+ threads: Arc<Mutex<Vec<std::thread::ThreadId>>>,
+ }
+
+ impl Engine for FakeEngine {
+ fn transcribe(&self, samples: &[f32]) -> Result<String, String> {
+ self.threads.lock().unwrap().push(std::thread::current().id());
+ if let Some(gate) = &self.gate {
+ gate.wait();
+ }
+ Ok(format!(" {} samples ", samples.len()))
+ }
+ }
+
+ struct Setup {
+ installed: Arc<AtomicBool>,
+ loads: Arc<AtomicUsize>,
+ dirs: Arc<Mutex<Vec<PathBuf>>>,
+ threads: Arc<Mutex<Vec<std::thread::ThreadId>>>,
+ fail_load: Arc<AtomicBool>,
+ gate: Option<Arc<Gate>>,
+ }
+
+ impl Setup {
+ fn new(gate: Option<Arc<Gate>>) -> Self {
+ Setup {
+ installed: Arc::new(AtomicBool::new(true)),
+ loads: Arc::default(),
+ dirs: Arc::default(),
+ threads: Arc::default(),
+ fail_load: Arc::default(),
+ gate,
+ }
+ }
+
+ fn parakeet(&self) -> Parakeet {
+ let installed = self.installed.clone();
+ let locate: Locate = Arc::new(move || installed.load(Ordering::SeqCst).then(|| PathBuf::from("/models/p")));
+ let (loads, dirs, threads, fail, gate) =
+ (self.loads.clone(), self.dirs.clone(), self.threads.clone(), self.fail_load.clone(), self.gate.clone());
+ let loader: Loader = Arc::new(move |dir: &Path| {
+ loads.fetch_add(1, Ordering::SeqCst);
+ dirs.lock().unwrap().push(dir.to_path_buf());
+ if fail.load(Ordering::SeqCst) {
+ return Err("The local voice model could not be loaded.".into());
+ }
+ Ok(Arc::new(FakeEngine { gate: gate.clone(), threads: threads.clone() }) as Arc<dyn Engine>)
+ });
+ Parakeet::new(locate, loader)
+ }
+ }
+
+ fn voice(parakeet: Arc<Parakeet>) -> (Voice, Arc<FakeMicrophone>) {
+ let mic = Arc::new(FakeMicrophone::granted());
+ let clock = Arc::new(FakeClock(AtomicU64::new(0)));
+ (Voice::new(mic.clone(), parakeet, clock).with_final_timeout(Duration::from_millis(50)), mic)
+ }
+
+ fn wait_until(what: &str, check: impl Fn() -> bool) {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while !check() {
+ assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}");
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ }
+
+ #[test]
+ fn it_needs_no_speech_permission_and_detects_the_language_itself() {
+ let parakeet = Setup::new(None).parakeet();
+ assert_eq!(parakeet.authorization(), Authorization::Authorized);
+ assert_eq!(parakeet.request_authorization(), Authorization::Authorized);
+ assert_eq!(parakeet.availability(), Ok(()));
+ let locales = parakeet.supported_locales();
+ assert_eq!(crate::voice::locale::resolve(Some("es-AR"), &parakeet.current_locale(), &locales), Ok("auto".into()));
+ }
+
+ #[test]
+ fn without_the_model_it_is_unavailable() {
+ let setup = Setup::new(None);
+ setup.installed.store(false, Ordering::SeqCst);
+ let parakeet = Arc::new(setup.parakeet());
+ assert!(!parakeet.installed());
+ assert_eq!(parakeet.availability(), Err(VoiceError::NoModel));
+ let (voice, _) = voice(parakeet);
+ assert_eq!(voice.status(), VoiceStatus::unavailable(VoiceError::NoModel.to_string()));
+ assert_eq!(voice.start(None, Recorder::default().events()), Err(VoiceError::NoModel));
+ }
+
+ #[test]
+ fn stop_decodes_the_recorded_pcm_off_the_calling_thread() {
+ let gate = Arc::new(Gate::default());
+ let setup = Setup::new(Some(gate.clone()));
+ let (voice, mic) = voice(Arc::new(setup.parakeet()));
+ let recorder = Recorder::default();
+ voice.start(None, recorder.events()).unwrap();
+ mic.sink().audio(&[0.1; 1_600]);
+ mic.sink().audio(&[0.2; 800]);
+
+ let voice = Arc::new(voice);
+ let stopping = {
+ let voice = voice.clone();
+ std::thread::spawn(move || (std::thread::current().id(), voice.stop()))
+ };
+ wait_until("the decoder", || !setup.threads.lock().unwrap().is_empty());
+ // Decoding outlives the default final timeout (50 ms here): stop keeps waiting for it.
+ std::thread::sleep(Duration::from_millis(150));
+ gate.release();
+ let (stop_thread, result) = stopping.join().unwrap();
+ assert_eq!(result, Ok(Transcript { text: "2400 samples".into() }));
+ assert_ne!(setup.threads.lock().unwrap()[0], stop_thread, "decoding runs on its own thread");
+ assert!(recorder.seen().iter().all(|e| !matches!(e, crate::voice::VoiceEvent::Partial(_))), "no partials");
+ }
+
+ #[test]
+ fn the_model_is_loaded_once_when_recording_starts_and_reused() {
+ let setup = Setup::new(None);
+ let parakeet = Arc::new(setup.parakeet());
+ let (voice, mic) = voice(parakeet.clone());
+ for _ in 0..2 {
+ voice.start(None, Recorder::default().events()).unwrap();
+ mic.sink().audio(&[0.0; 160]);
+ assert_eq!(voice.stop(), Ok(Transcript { text: "160 samples".into() }));
+ }
+ assert_eq!(setup.loads.load(Ordering::SeqCst), 1);
+ assert_eq!(setup.dirs.lock().unwrap().as_slice(), [PathBuf::from("/models/p")]);
+ assert!(parakeet.loaded());
+
+ parakeet.release();
+ assert!(!parakeet.loaded());
+ voice.start(None, Recorder::default().events()).unwrap();
+ voice.stop().unwrap();
+ assert_eq!(setup.loads.load(Ordering::SeqCst), 2, "released models load again");
+ }
+
+ #[test]
+ fn an_idle_model_is_unloaded() {
+ let setup = Setup::new(None);
+ let parakeet = Arc::new(setup.parakeet().with_idle(Duration::from_millis(30)));
+ let (voice, _) = voice(parakeet.clone());
+ voice.start(None, Recorder::default().events()).unwrap();
+ voice.stop().unwrap();
+ assert!(parakeet.loaded());
+ wait_until("the idle unload", || !parakeet.loaded());
+ }
+
+ #[test]
+ fn a_model_that_cannot_load_resolves_stop_without_text() {
+ let setup = Setup::new(None);
+ setup.fail_load.store(true, Ordering::SeqCst);
+ let (voice, mic) = voice(Arc::new(setup.parakeet()));
+ voice.start(None, Recorder::default().events()).unwrap();
+ mic.sink().audio(&[0.0; 160]);
+ assert_eq!(voice.stop(), Ok(Transcript { text: String::new() }));
+ }
+
+ #[test]
+ fn cancel_discards_the_recording_without_decoding_it() {
+ let setup = Setup::new(None);
+ let (voice, mic) = voice(Arc::new(setup.parakeet()));
+ voice.start(None, Recorder::default().events()).unwrap();
+ mic.sink().audio(&[0.0; 160]);
+ voice.cancel().unwrap();
+ std::thread::sleep(Duration::from_millis(20));
+ assert!(setup.threads.lock().unwrap().is_empty());
+ }
+
+ #[test]
+ fn recordings_are_capped() {
+ let mut samples = Samples::default();
+ samples.push(&vec![0.0; MAX_SAMPLES - 10]);
+ samples.push(&[0.0; 25]);
+ assert_eq!(samples.take().len(), MAX_SAMPLES);
+ assert_eq!(MAX_SAMPLES, 16_000 * 300, "five minutes at 16 kHz");
+ }
+
+ /// Decodes a short WAV with the real model. Run with
+ /// `GENTLE_DOT_PARAKEET_DIR=<dir with the four files> cargo test -- --ignored real_parakeet`;
+ /// `GENTLE_DOT_PARAKEET_WAV` picks the clip (default `<dir>/test_wavs/en.wav`).
+ #[test]
+ #[ignore = "needs the real Parakeet model (about 640 MB)"]
+ fn real_parakeet_decodes_a_wav() {
+ let Some(dir) = std::env::var_os("GENTLE_DOT_PARAKEET_DIR").map(PathBuf::from) else {
+ eprintln!("GENTLE_DOT_PARAKEET_DIR is not set; skipping");
+ return;
+ };
+ let wav = std::env::var_os("GENTLE_DOT_PARAKEET_WAV")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| dir.join("test_wavs/en.wav"));
+ let wave = sherpa_onnx::Wave::read(&wav.display().to_string()).expect("a readable WAV");
+ // The release's clips are 24 kHz; the microphone delivers 16 kHz, so resample like it.
+ let pcm = crate::voice::audio::Resampler::new(f64::from(wave.sample_rate())).process(wave.samples());
+ let started = std::time::Instant::now();
+ let engine = load(&dir).expect("the model loads");
+ let loaded = started.elapsed();
+ let text = engine.transcribe(&pcm).expect("a transcript");
+ eprintln!("loaded in {loaded:?}, decoded in {:?}: {text}", started.elapsed() - loaded);
+ assert!(!text.trim().is_empty());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/voice/pipe.rs b/apps/desktop/src-tauri/src/voice/pipe.rs
new file mode 100644
index 0000000..9007de1
--- /dev/null
+++ b/apps/desktop/src-tauri/src/voice/pipe.rs
@@ -0,0 +1,215 @@
+//! The Linux microphone (S30.5): a command-line recorder that writes 16 kHz mono f32 PCM to its
+//! standard output, read on a thread of its own. `parec` (PulseAudio, and PipeWire through
+//! pipewire-pulse) is tried first, then `arecord` (ALSA). Linux has no microphone permission to
+//! ask for. Compiled on every Unix so the tests run on macOS too; only Linux uses it.
+
+use super::{Authorization, Microphone, Sink, Stream, VoiceError};
+use std::io::{self, Read};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+
+/// Bytes per read: 512 samples, 32 ms.
+const READ_BYTES: usize = 4 * 512;
+
+pub struct PipeMicrophone {
+ /// Candidate commands, each a program and its arguments, in order of preference.
+ pub(crate) recorders: Vec<Vec<String>>,
+}
+
+impl PipeMicrophone {
+ /// `parec`, then `arecord`, both asked for raw 16 kHz mono little-endian float.
+ pub fn system() -> Self {
+ let command = |parts: &[&str]| parts.iter().map(|part| part.to_string()).collect();
+ PipeMicrophone {
+ recorders: vec![
+ command(&["parec", "--raw", "--format=float32le", "--rate=16000", "--channels=1", "--latency-msec=40"]),
+ command(&["arecord", "-q", "-t", "raw", "-f", "FLOAT_LE", "-r", "16000", "-c", "1"]),
+ ],
+ }
+ }
+
+ pub fn with(recorders: Vec<Vec<String>>) -> Self {
+ PipeMicrophone { recorders }
+ }
+}
+
+/// Turns a byte stream into f32 samples, keeping a partial sample for the next chunk.
+#[derive(Default)]
+pub(crate) struct Decoder {
+ pending: Vec<u8>,
+}
+
+impl Decoder {
+ pub(crate) fn push(&mut self, bytes: &[u8]) -> Vec<f32> {
+ self.pending.extend_from_slice(bytes);
+ let (whole, _) = self.pending.as_chunks::<4>();
+ let samples: Vec<f32> = whole.iter().map(|bytes| f32::from_le_bytes(*bytes)).collect();
+ self.pending.drain(..samples.len() * 4);
+ samples
+ }
+}
+
+impl Microphone for PipeMicrophone {
+ fn authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn request_authorization(&self) -> Authorization {
+ Authorization::Authorized
+ }
+
+ fn open(&self, sink: Sink) -> Result<Box<dyn Stream>, VoiceError> {
+ for recorder in &self.recorders {
+ let Some((program, args)) = recorder.split_first() else { continue };
+ let spawned = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn();
+ let mut child = match spawned {
+ Ok(child) => child,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
+ Err(error) => return Err(VoiceError::Failed(format!("The microphone could not start: {error}"))),
+ };
+ let Some(mut output) = child.stdout.take() else { continue };
+ let closed = Arc::new(AtomicBool::new(false));
+ let reading = closed.clone();
+ let read = move || {
+ let mut decoder = Decoder::default();
+ let mut buffer = [0u8; READ_BYTES];
+ loop {
+ match output.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(read) => {
+ let samples = decoder.push(&buffer[..read]);
+ if !samples.is_empty() {
+ sink.audio(&samples);
+ }
+ }
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
+ Err(_) => break,
+ }
+ }
+ // The recorder ended without being closed: the device went away or failed.
+ if !reading.load(Ordering::SeqCst) {
+ sink.failed(&VoiceError::Interrupted.to_string());
+ }
+ };
+ if let Err(error) = std::thread::Builder::new().name("voice-recorder".into()).spawn(read) {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(VoiceError::Failed(format!("The microphone could not start: {error}")));
+ }
+ return Ok(Box::new(PipeStream { child, closed }));
+ }
+ Err(VoiceError::NoRecorder)
+ }
+}
+
+struct PipeStream {
+ child: Child,
+ closed: Arc<AtomicBool>,
+}
+
+impl Stream for PipeStream {
+ fn close(&mut self) {
+ if !self.closed.swap(true, Ordering::SeqCst) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+ }
+}
+
+impl Drop for PipeStream {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::voice::fake::{FakeClock, FakeRecognizer, Recorder};
+ use crate::voice::{Authorization, Microphone, Voice, VoiceError};
+ use std::sync::atomic::AtomicU64;
+ use std::sync::Arc;
+ use std::time::{Duration, Instant};
+
+ fn command(parts: &[&str]) -> Vec<String> {
+ parts.iter().map(|part| part.to_string()).collect()
+ }
+
+ #[test]
+ fn little_endian_floats_are_decoded_across_chunk_boundaries() {
+ let bytes: Vec<u8> = [0.5f32, -0.25, 1.0].iter().flat_map(|s| s.to_le_bytes()).collect();
+ let mut decoder = Decoder::default();
+ assert_eq!(decoder.push(&bytes[..3]), Vec::<f32>::new());
+ assert_eq!(decoder.push(&bytes[3..9]), vec![0.5, -0.25]);
+ assert_eq!(decoder.push(&bytes[9..]), vec![1.0]);
+ }
+
+ #[test]
+ fn the_system_recorders_ask_for_16_khz_mono_float() {
+ let recorders = PipeMicrophone::system().recorders;
+ assert_eq!(recorders[0][0], "parec");
+ assert!(recorders[0].contains(&"--format=float32le".to_string()));
+ assert!(recorders[0].contains(&"--rate=16000".to_string()));
+ assert!(recorders[0].contains(&"--channels=1".to_string()));
+ assert_eq!(recorders[1], command(&["arecord", "-q", "-t", "raw", "-f", "FLOAT_LE", "-r", "16000", "-c", "1"]));
+ }
+
+ #[test]
+ fn there_is_no_permission_to_ask_for() {
+ let mic = PipeMicrophone::system();
+ assert_eq!(mic.authorization(), Authorization::Authorized);
+ assert_eq!(mic.request_authorization(), Authorization::Authorized);
+ }
+
+ fn voice(mic: PipeMicrophone) -> (Voice, Arc<FakeRecognizer>) {
+ let recognizer = Arc::new(FakeRecognizer::granted());
+ *recognizer.final_text.lock().unwrap() = Some("done".into());
+ let voice = Voice::new(Arc::new(mic), recognizer.clone(), Arc::new(FakeClock(AtomicU64::new(0))));
+ (voice, recognizer)
+ }
+
+ #[test]
+ fn the_first_recorder_found_streams_its_pcm_until_stopped() {
+ // 1,600 zero samples, then silence while the recorder keeps running.
+ let mic = PipeMicrophone::with(vec![
+ command(&["gentle-dot-no-such-recorder"]),
+ command(&["/bin/sh", "-c", "head -c 6400 /dev/zero; exec sleep 30"]),
+ ]);
+ let (voice, recognizer) = voice(mic);
+ voice.start(None, Recorder::default().events()).unwrap();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while recognizer.log.lock().unwrap().fed.len() < 1_600 {
+ assert!(Instant::now() < deadline, "the PCM arrives");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ let stopped = Instant::now();
+ assert_eq!(voice.stop().unwrap().text, "done");
+ assert!(stopped.elapsed() < Duration::from_secs(5), "stop kills the recorder");
+ assert_eq!(recognizer.log.lock().unwrap().fed.len(), 1_600);
+ }
+
+ #[test]
+ fn a_recorder_that_ends_on_its_own_is_an_interruption() {
+ // It ends a moment after starting, once the recording is up.
+ let mic = PipeMicrophone::with(vec![command(&["/bin/sh", "-c", "head -c 64 /dev/zero; sleep 0.3"])]);
+ let (voice, _) = voice(mic);
+ let recorder = Recorder::default();
+ voice.start(None, recorder.events()).unwrap();
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let interrupted = crate::voice::VoiceEvent::Error(VoiceError::Interrupted.to_string());
+ while !recorder.seen().contains(&interrupted) {
+ assert!(Instant::now() < deadline, "the interruption is reported");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(voice.stop(), Err(VoiceError::NotRecording), "the recording ended");
+ }
+
+ #[test]
+ fn no_recorder_on_the_system_explains_what_to_install() {
+ let mic = PipeMicrophone::with(vec![command(&["gentle-dot-no-such-recorder"])]);
+ let (voice, _) = voice(mic);
+ assert_eq!(voice.start(None, Recorder::default().events()), Err(VoiceError::NoRecorder));
+ assert!(VoiceError::NoRecorder.to_string().contains("pulseaudio-utils"));
+ }
+}