diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f4d2cac..cedc1f5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -39,6 +39,35 @@ jobs:
libasound2-dev libpulse-dev libssl-dev \
libx11-dev libxtst-dev libxrandr-dev libxkbcommon-dev pkg-config
+ # The speech engine's Vulkan backend (see src-tauri/Cargo.toml) is
+ # compiled with the Vulkan headers and shader compiler; Parler itself
+ # never needs Vulkan to start.
+ - name: Install the Vulkan SDK (Linux)
+ if: runner.os == 'Linux'
+ run: |
+ wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc
+ sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.3.290-jammy.list https://packages.lunarg.com/vulkan/1.3.290/lunarg-vulkan-1.3.290-jammy.list
+ sudo apt-get update
+ sudo apt-get install -y vulkan-sdk
+
+ - name: Install the Vulkan SDK (Windows)
+ if: runner.os == 'Windows'
+ uses: humbletim/install-vulkan-sdk@v1.2
+ with:
+ version: 1.4.309.0
+ cache: true
+
+ # ggml-vulkan looks for SPIRV-Headers as a CMake package, which the SDK
+ # above doesn't expose on Windows.
+ - name: Install SPIRV-Headers (Windows)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ vcpkg install spirv-headers:x64-windows
+ if ($LASTEXITCODE -ne 0) { throw "vcpkg install spirv-headers failed" }
+ $prefix = "$env:VCPKG_INSTALLATION_ROOT/installed/x64-windows" -replace '\\','/'
+ Add-Content $env:GITHUB_ENV "CMAKE_PREFIX_PATH=$prefix"
+
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c6c069b..86ab665 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -64,6 +64,36 @@ jobs:
libasound2-dev libpulse-dev libssl-dev \
libx11-dev libxtst-dev libxrandr-dev libxkbcommon-dev pkg-config
+ # The speech engine's Vulkan backend (see src-tauri/Cargo.toml) is
+ # compiled with the Vulkan headers and shader compiler. The bundles
+ # don't ship Vulkan: Parler uses the system's driver when there is one
+ # and the CPU otherwise.
+ - name: Install the Vulkan SDK (Linux)
+ if: runner.os == 'Linux'
+ run: |
+ wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc
+ sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.3.290-jammy.list https://packages.lunarg.com/vulkan/1.3.290/lunarg-vulkan-1.3.290-jammy.list
+ sudo apt-get update
+ sudo apt-get install -y vulkan-sdk
+
+ - name: Install the Vulkan SDK (Windows)
+ if: runner.os == 'Windows'
+ uses: humbletim/install-vulkan-sdk@v1.2
+ with:
+ version: 1.4.309.0
+ cache: true
+
+ # ggml-vulkan looks for SPIRV-Headers as a CMake package, which the SDK
+ # above doesn't expose on Windows.
+ - name: Install SPIRV-Headers (Windows)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ vcpkg install spirv-headers:x64-windows
+ if ($LASTEXITCODE -ne 0) { throw "vcpkg install spirv-headers failed" }
+ $prefix = "$env:VCPKG_INSTALLATION_ROOT/installed/x64-windows" -replace '\\','/'
+ Add-Content $env:GITHUB_ENV "CMAKE_PREFIX_PATH=$prefix"
+
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_targets }}
@@ -156,8 +186,44 @@ jobs:
} >> "$GITHUB_ENV"
echo "::notice::Update bundles will be signed."
+ # Parler links libtranscribe, which lives in the cargo build tree until
+ # the bundles copy it (build.rs stages it with the ggml modules). The
+ # AppImage's linuxdeploy resolves every library the binary needs and
+ # fails on one it can't find, so build first and show it where.
+ - name: Build the speech engine first (Linux)
+ if: runner.os == 'Linux'
+ shell: bash
+ run: |
+ set -euo pipefail
+ pnpm build
+ (cd src-tauri && cargo build --release --target "${{ matrix.target }}")
+ lib_dir=$(find "src-tauri/target/${{ matrix.target }}/release/build" -type f -name transcribe-link.json \
+ -path '*transcribe-cpp-sys*/out/lib/*' -printf '%T@ %h\n' | sort -rn | head -1 | cut -d' ' -f2-)
+ if [ -z "$lib_dir" ]; then echo "::error::No transcribe-cpp libraries built."; exit 1; fi
+ ls -la "$lib_dir"
+ echo "LD_LIBRARY_PATH=$lib_dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" >> "$GITHUB_ENV"
+ sudo cp -vL "$lib_dir"/libtranscribe.so* "$lib_dir"/libggml*.so* /usr/local/lib/
+ sudo ldconfig
+
+ # Tauri's own linuxdeploy predates LINUXDEPLOY_EXCLUDED_LIBRARIES (used
+ # below): a current one goes where Tauri looks for it.
+ - name: Install a current linuxdeploy (Linux)
+ if: runner.os == 'Linux'
+ shell: bash
+ run: |
+ set -euo pipefail
+ tools="${XDG_CACHE_HOME:-$HOME/.cache}/tauri"
+ mkdir -p "$tools"
+ curl -L --fail --show-error --retry 3 -o "$tools/linuxdeploy-x86_64.AppImage" \
+ https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage
+ chmod +x "$tools/linuxdeploy-x86_64.AppImage"
+
- name: Build Tauri bundle
shell: bash
+ env:
+ # The Vulkan loader must come from the system, matching its driver:
+ # never bundled into the AppImage.
+ LINUXDEPLOY_EXCLUDED_LIBRARIES: ${{ runner.os == 'Linux' && 'libvulkan.so*' || '' }}
run: |
set -euo pipefail
args=(--target "${{ matrix.target }}")
@@ -166,6 +232,66 @@ jobs:
fi
pnpm tauri build "${args[@]}"
+ # Without the engine's libraries next to it, Parler wouldn't even start
+ # (Linux, Windows): never publish a bundle that lacks them.
+ - name: Check the bundles carry the speech engine
+ if: runner.os != 'macOS'
+ shell: bash
+ run: |
+ set -euo pipefail
+ out="src-tauri/target/${{ matrix.target }}/release/bundle"
+ if [ "$RUNNER_OS" = "Linux" ]; then
+ # Each package must carry the engine; on a miss, say which file
+ # and show what the package holds instead.
+ need() { # listing, pattern, what
+ echo "$1" | grep -Eq "$2" || {
+ echo "::error::$3 lacks $2"
+ echo "$1" | grep -Ei 'transcribe|ggml|vulkan' || echo "(no engine library at all)"
+ exit 1
+ }
+ }
+ # The app must find every library it links where the package
+ # puts it: no "not found" from ldd once unpacked.
+ loads() { # unpacked root, what
+ bin=$(find "$1/usr/bin" -type f | head -1)
+ missing=$(ldd "$bin" | grep 'not found' || true)
+ if [ -n "$missing" ]; then
+ echo "::error::$2: $bin can't find $missing"; exit 1
+ fi
+ }
+ for pkg in "$out"/deb/*.deb; do
+ listing=$(dpkg-deb -c "$pkg")
+ need "$listing" 'usr/lib/Parler/libtranscribe\.so' "$pkg"
+ need "$listing" 'usr/lib/Parler/libggml-cpu' "$pkg"
+ need "$listing" 'usr/lib/Parler/libggml-vulkan\.so' "$pkg"
+ root="$RUNNER_TEMP/deb-root"
+ rm -rf "$root" && dpkg-deb -x "$pkg" "$root"
+ loads "$root" "$pkg"
+ done
+ for pkg in "$out"/rpm/*.rpm; do
+ need "$(rpm -qlp "$pkg")" 'usr/lib/Parler/libtranscribe\.so' "$pkg"
+ done
+ image=$(find "$out/appimage" -name '*.AppImage' | head -1)
+ chmod +x "$image"
+ (cd "$RUNNER_TEMP" && "$OLDPWD/$image" --appimage-extract >/dev/null)
+ listing=$(cd "$RUNNER_TEMP/squashfs-root" && find . -name '*.so*')
+ need "$listing" 'libtranscribe\.so' "$image"
+ need "$listing" 'libggml-vulkan\.so' "$image"
+ if echo "$listing" | grep -q 'libvulkan\.so'; then
+ echo "::error::The AppImage bundles the Vulkan loader."; exit 1
+ fi
+ loads "$RUNNER_TEMP/squashfs-root" "$image"
+ else
+ # 7-Zip lists what the NSIS installer unpacks (the MSI keeps its
+ # files in a cabinet it doesn't name); both bundle the same list.
+ for installer in "$out"/nsis/*.exe; do
+ listing=$(7z l "$installer")
+ for dll in transcribe.dll ggml-vulkan.dll msvcp140.dll; do
+ echo "$listing" | grep -qi "$dll" || { echo "::error::$installer lacks $dll"; exit 1; }
+ done
+ done
+ fi
+
# Nothing is published unless Apple accepted the build and the ticket is
# stapled into the .dmg users download. A congested notary service
# delays the release rather than shipping an unverifiable one.
diff --git a/.gitignore b/.gitignore
index ace6337..2cb926e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,3 +39,6 @@ src-tauri/gen
# Local agent scratch
.claude/
+
+# The speech engine's libraries, gathered by src-tauri/build.rs for the bundles
+src-tauri/transcribe-libs
diff --git a/README.fr.md b/README.fr.md
index 605f793..76f7c53 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -28,16 +28,16 @@ Maintenez un raccourci, parlez, relâchez : vos mots s'écrivent dans n'importe
## Parler, c'est quoi ?
-Parler est une app de dictée libre et gratuite pour votre ordinateur : **la saisie vocale qui marche dans toutes vos apps**, vos mails, votre messagerie, vos documents, votre navigateur ou votre éditeur de code. Maintenez un raccourci, parlez naturellement, relâchez. Parler envoie votre voix à une API de transcription compatible Whisper et écrit le texte là où se trouve votre curseur.
+Parler est une app de dictée libre et gratuite pour votre ordinateur : **la saisie vocale qui marche dans toutes vos apps**, vos mails, votre messagerie, vos documents, votre navigateur ou votre éditeur de code. Maintenez un raccourci, parlez naturellement, relâchez. Parler transcrit votre voix, sur votre ordinateur ou avec un service de transcription, et écrit le texte là où se trouve votre curseur.
-Vous choisissez qui transcrit : **Parler Cloud**, sans rien à configurer, ou votre propre clé d'API chez **Groq** (inscription gratuite), **OpenAI**, **Fireworks** ou **votre propre serveur**, qui reste sur votre ordinateur. Aucun modèle à télécharger, aucune télémétrie.
+Vous choisissez qui transcrit : **Parler Cloud**, sans rien à configurer ; **cet ordinateur**, en privé et hors ligne, avec un modèle à télécharger ; ou votre propre clé d'API chez **Groq** (inscription gratuite), **OpenAI**, **Fireworks** ou **votre propre serveur**, qui reste sur votre ordinateur. Aucune télémétrie.
Vous cherchez une alternative open source à Wispr Flow, SuperWhisper ou à la dictée intégrée de votre système, qui marche pareil sous macOS, Windows et Linux ? C'est exactement ce que fait Parler.
## Comment ça marche
1. **Maintenez** fn sur macOS, ou Ctrl + Espace sous Windows et Linux, et parlez. Une petite pastille en bas de l'écran montre le niveau de votre voix.
-2. **Relâchez.** Parler retire les silences et n'envoie que votre voix au service choisi.
+2. **Relâchez.** Parler retire les silences et ne transcrit que votre voix, sur votre ordinateur ou chez le service choisi.
3. **C'est écrit.** Le texte apparaît là où se trouve votre curseur, et votre presse-papiers est remis comme il était.
Un appui bref au lieu d'un appui long garde l'écoute ouverte jusqu'au suivant. Vous pouvez cliquer et changer de fenêtre pendant que vous parlez : le texte s'écrit là où se trouve votre curseur quand vous relâchez. Appuyez deux fois sur Échap pour annuler. Le raccourci se change dans les réglages.
@@ -56,9 +56,10 @@ Un appui bref au lieu d'un appui long garde l'écoute ouverte jusqu'au suivant.
| **Marche dans toutes les apps** | Écrit dans la fenêtre active, puis rétablit votre presse-papiers. Vous préférez coller vous-même ? Passez en copie seule. |
| **Un raccourci, trois modes** | Intelligent (maintenir pour parler, appui bref pour continuer d'écouter), Maintenir ou Basculer. Sur macOS, une seule touche comme fn ou ⌘ droite ; partout, la combinaison de votre choix. |
| **N'envoie jamais de silence** | Sur un audio vide, Whisper invente du texte (« Sous-titres réalisés par la communauté d'Amara.org »…), donc les enregistrements sans parole ne quittent pas votre machine. |
+| **Fonctionne aussi sur votre ordinateur** | Transcrivez hors ligne et gratuitement, avec un modèle téléchargé une fois. Rien ne quitte votre machine. |
| **Vocabulaire** | Noms, marques et jargon bien orthographiés. |
| **Historique avec recherche** | Retrouvez une dictée et recopiez-la si elle a atterri dans la mauvaise fenêtre. Réessayez quand le réseau a lâché. |
-| **Prise en main guidée** | Choisir un service, coller sa clé, la tester, faire sa première dictée. Environ deux minutes. |
+| **Prise en main guidée** | Se connecter à Parler Cloud, télécharger le modèle ou coller sa clé, puis faire sa première dictée. Environ deux minutes. |
| **Barre des menus et zone de notification** | Lancer une dictée, copier la dernière transcription, ouvrir l'historique. Peut se lancer à l'ouverture de session. |
| **Plus de 30 langues parlées** | Détection automatique, ou choisissez la vôtre pour une transcription plus rapide et plus juste. |
| **Clair ou sombre** | Ou selon votre système. Interface en 12 langues. |
@@ -67,7 +68,7 @@ Un appui bref au lieu d'un appui long garde l'écoute ouverte jusqu'au suivant.
## Services de transcription et tarifs
-Parler est gratuit. Il fonctionne avec tout service compatible avec l'API audio d'OpenAI (`POST /audio/transcriptions`), et vous payez ce service directement, à ses tarifs. Parler ne prend aucune commission.
+Parler est gratuit. Il transcrit sur votre ordinateur, ou avec tout service compatible avec l'API audio d'OpenAI (`POST /audio/transcriptions`), que vous payez directement, à ses tarifs. Parler ne prend aucune commission.
| Service | Modèle par défaut | Autres suggestions | Clé d'API |
| --- | --- | --- | --- |
@@ -78,6 +79,17 @@ Parler est gratuit. Il fonctionne avec tout service compatible avec l'API audio
Tout autre modèle proposé par un service peut être saisi dans les réglages, et vous pouvez changer de service à tout moment : chacun garde sa propre clé.
+### Sur cet ordinateur
+
+Choisissez **Sur cet ordinateur** et Parler transcrit en local, avec [transcribe.cpp](https://github.com/handy-computer/transcribe.cpp) : rien n'est envoyé nulle part, ça fonctionne hors ligne, et c'est gratuit. La première fois, Parler télécharge un modèle :
+
+| Modèle | Taille | Langues | Vocabulaire |
+| --- | --- | --- | --- |
+| **Parakeet Ultra** (recommandé pour les langues européennes) | 740 Mo | 25 langues européennes | Non |
+| **Whisper Large v3 Turbo** (recommandé pour les autres, ou dans *Options avancées*) | 620 Mo | Toutes les langues | Oui |
+
+La transcription utilise la puissance de votre ordinateur : elle peut être plus lente quand il est occupé, et elle est un peu moins précise que Parler Cloud. Les modèles viennent de [Hugging Face](https://huggingface.co/handy-computer), à une version précise, et leur empreinte SHA-256 est vérifiée avant usage.
+
> [!TIP]
> **Pas envie de créer une clé d'API ? Choisissez Parler Cloud.** Sélectionnez-le à la configuration de Parler, connectez-vous une fois depuis votre navigateur, et dictez. Transcription illimitée pour l'usage normal d'une personne ([usage raisonnable](https://parler.synapsr.io/fair-use)), pour 8 € HT par mois ou 49 € HT par an, après 3 jours d'essai gratuit. Votre compte : [cloud.parler.synapsr.io](https://cloud.parler.synapsr.io). Une question : [parler@synapsr.io](mailto:parler@synapsr.io).
@@ -145,18 +157,18 @@ Sous Linux, installez aussi les [prérequis de Tauri](https://tauri.app/start/pr
## Confidentialité
-- L'audio n'est enregistré que pendant la dictée et n'est envoyé qu'au service choisi. Il n'est jamais écrit sur le disque, sauf pour une dictée qui n'a pas pu être envoyée (faute de connexion, par exemple) : son audio reste sur cet ordinateur, lisible par votre seul compte utilisateur, jusqu'à son envoi ou sa suppression, 7 jours au plus.
+- L'audio n'est enregistré que pendant la dictée et n'est envoyé qu'au service choisi ; sur cet ordinateur, il n'est envoyé nulle part. Il n'est jamais écrit sur le disque, sauf pour une dictée qui n'a pas pu être envoyée (faute de connexion, par exemple) : son audio reste sur cet ordinateur, lisible par votre seul compte utilisateur, jusqu'à son envoi ou sa suppression, 7 jours au plus.
- Les enregistrements sans parole ne sont jamais envoyés.
- Votre clé d'API et vos réglages restent dans un fichier local lisible par votre seul compte utilisateur.
- Vos transcriptions (les 5 000 dernières) restent sur votre ordinateur pour pouvoir les retrouver et les recopier. Effacez-les quand vous voulez.
-- Ni statistiques, ni télémétrie. Votre audio ne va qu'au service choisi : votre fournisseur directement, ou Parler Cloud si vous l'avez choisi. Parler Cloud garde l'audio en mémoire le temps de la requête, le fait transcrire par Groq, et ne conserve ni l'audio ni le texte.
+- Ni statistiques, ni télémétrie. Votre audio ne va qu'au service choisi : votre fournisseur directement, ou Parler Cloud si vous l'avez choisi. Sur cet ordinateur, il ne va nulle part : Parler ne se connecte à Hugging Face qu'une fois, pour télécharger le modèle. Parler Cloud garde l'audio en mémoire le temps de la requête, le fait transcrire par Groq, et ne conserve ni l'audio ni le texte.
- Parler cherche les nouvelles versions sur GitHub et les télécharge depuis GitHub (les empaqueteurs peuvent le désactiver avec `PARLER_DISABLE_UPDATER=1`).
- **Réglages → À propos → Envoyer le journal** envoie au support la version de Parler, votre système et son journal technique, seulement quand vous le demandez. Parler Cloud le transmet par e-mail et ne garde rien.
- Ce que le service fait de votre audio dépend de sa propre politique. Avec votre propre serveur, rien ne sort de votre réseau.
## Langues
-**Parlées :** Parler détecte la langue dans laquelle vous parlez, ou vous en choisissez une parmi 31 : anglais, français, espagnol, allemand, italien, portugais, néerlandais, breton, catalan, basque, polonais, tchèque, roumain, hongrois, suédois, danois, norvégien, finnois, grec, turc, ukrainien, russe, arabe, hébreu, hindi, indonésien, vietnamien, thaï, chinois, japonais et coréen. La qualité dépend du service et du modèle.
+**Parlées :** Parler détecte la langue dans laquelle vous parlez, ou vous en choisissez une parmi 31 : anglais, français, espagnol, allemand, italien, portugais, néerlandais, breton, catalan, basque, polonais, tchèque, roumain, hongrois, suédois, danois, norvégien, finnois, grec, turc, ukrainien, russe, arabe, hébreu, hindi, indonésien, vietnamien, thaï, chinois, japonais et coréen. La qualité dépend du service et du modèle. Sur cet ordinateur, Parakeet Ultra connaît 25 langues européennes ; pour les autres, Parler recommande Whisper Large v3 Turbo.
**Interface :** anglais, français, espagnol, allemand, italien, portugais, néerlandais, polonais, turc, japonais, chinois et coréen. [Ajoutez la vôtre](docs/contributing.md#conventions).
@@ -165,35 +177,35 @@ Sous Linux, installez aussi les [prérequis de Tauri](https://tauri.app/start/pr
Parler est-il gratuit ?
-Oui. L'app est libre et gratuite, sous licence MIT. Vous la reliez à votre propre compte chez un service de transcription et vous payez ce service directement, à ses tarifs ; Groq propose une inscription gratuite pour démarrer. Parler Cloud est l'offre payante facultative pour ceux qui préfèrent ne pas gérer de clé d'API : 8 € HT par mois ou 49 € HT par an, après 3 jours d'essai gratuit.
+Oui. L'app est libre et gratuite, sous licence MIT. Vous la reliez à votre propre compte chez un service de transcription et vous payez ce service directement, à ses tarifs ; Groq propose une inscription gratuite pour démarrer. Transcrire sur cet ordinateur ne coûte rien du tout. Parler Cloud est l'offre payante facultative pour ceux qui préfèrent ne pas gérer de clé d'API : 8 € HT par mois ou 49 € HT par an, après 3 jours d'essai gratuit.
Quel service choisir ?
-Parler Cloud si vous ne voulez rien configurer. Avec votre propre clé, Groq est le choix par défaut : il fait tourner Whisper large-v3 turbo, répond vite et propose une inscription gratuite. Prenez OpenAI ou Fireworks si vous y avez déjà un compte, ou votre propre serveur pour tout maîtriser. Vous pouvez en changer à tout moment dans les réglages.
+Parler Cloud si vous ne voulez rien configurer. Sur cet ordinateur si vous tenez à la confidentialité et au hors-ligne, quitte à un peu moins de précision. Avec votre propre clé, Groq est le choix par défaut : il fait tourner Whisper large-v3 turbo, répond vite et propose une inscription gratuite. Prenez OpenAI ou Fireworks si vous y avez déjà un compte, ou votre propre serveur pour tout maîtriser. Vous pouvez en changer à tout moment dans les réglages.
Est-ce que ça marche hors ligne ?
-Pas tout seul : la transcription se fait chez le service choisi, il faut donc une connexion internet. Si vous faites tourner un serveur compatible OpenAI sur votre réseau (speaches, LocalAI…), Parler fonctionne sans internet.
+Oui, si vous choisissez **Sur cet ordinateur** : après un seul téléchargement du modèle, la transcription se fait sur votre ordinateur, sans internet. Les autres services demandent une connexion, sauf si vous faites tourner un serveur compatible OpenAI sur votre réseau (speaches, LocalAI…).
Quelle différence avec Wispr Flow, SuperWhisper ou la dictée de macOS ?
-Même idée : parler plutôt que taper, dans n'importe quelle app. L'approche de Parler : le code est ouvert (MIT), l'app est gratuite, elle tourne sous macOS, Windows et Linux, et vous choisissez qui transcrit votre voix, de Groq, OpenAI ou Fireworks à un serveur que vous hébergez. Parler écrit ce que vous avez dit ; il ne le réécrit pas.
+Même idée : parler plutôt que taper, dans n'importe quelle app. L'approche de Parler : le code est ouvert (MIT), l'app est gratuite, elle tourne sous macOS, Windows et Linux, et vous choisissez qui transcrit votre voix : votre propre ordinateur, hors ligne, ou Groq, OpenAI, Fireworks ou un serveur que vous hébergez. Parler écrit ce que vous avez dit ; il ne le réécrit pas.
Ma voix est-elle conservée ou utilisée pour entraîner des modèles ?
-Parler ne conserve pas votre audio, sauf celui d'une dictée qui n'a pas pu être envoyée : il attend sur votre ordinateur jusqu'à son envoi ou sa suppression, 7 jours au plus. Pour le reste, Parler ne garde que le texte de vos dictées, que vous pouvez effacer à tout moment. Ce que le service fait de l'audio dépend de sa propre politique : lisez-la avant de choisir.
+Parler ne conserve pas votre audio, sauf celui d'une dictée qui n'a pas pu être envoyée : il attend sur votre ordinateur jusqu'à son envoi ou sa suppression, 7 jours au plus. Pour le reste, Parler ne garde que le texte de vos dictées, que vous pouvez effacer à tout moment. Ce que le service fait de l'audio dépend de sa propre politique : lisez-la avant de choisir. Sur cet ordinateur, il n'y a pas de service : l'audio reste chez vous.
diff --git a/README.md b/README.md
index 7d7a6e2..899c03c 100644
--- a/README.md
+++ b/README.md
@@ -28,16 +28,16 @@ Hold a shortcut, speak, let go: your words are typed in any app.
## What is Parler?
-Parler is a free, open-source dictation app for your desktop: **voice typing that works in every app**, whether it's your email, chat, documents, browser or code editor. Hold a shortcut, speak naturally, let go. Parler sends your speech to a Whisper-compatible speech-to-text API and types the text where your cursor is.
+Parler is a free, open-source dictation app for your desktop: **voice typing that works in every app**, whether it's your email, chat, documents, browser or code editor. Hold a shortcut, speak naturally, let go. Parler transcribes your speech, on your computer or with a speech-to-text service, and types the text where your cursor is.
-You choose who transcribes: **Parler Cloud**, with nothing to set up, or your own API key at **Groq** (free sign-up), **OpenAI**, **Fireworks** or **your own server**, which stays on your computer. No model to download, no telemetry.
+You choose who transcribes: **Parler Cloud**, with nothing to set up; **this computer**, private and offline, with one model to download; or your own API key at **Groq** (free sign-up), **OpenAI**, **Fireworks** or **your own server**, which stays on your computer. No telemetry.
Looking for an open-source alternative to Wispr Flow, SuperWhisper or your system's built-in dictation, one that works the same on macOS, Windows and Linux? That's what Parler is for.
## How it works
1. **Hold** fn on macOS, or Ctrl + Space on Windows and Linux, and speak. A small pill at the bottom of the screen shows your voice level.
-2. **Let go.** Parler trims the silence and sends only your speech to the service you picked.
+2. **Let go.** Parler trims the silence and transcribes only your speech, on your computer or at the service you picked.
3. **Done.** The text is typed where your cursor is, and your clipboard is put back the way it was.
A quick tap instead of a hold keeps listening until your next press. You can click and switch windows while you speak: the text goes where your cursor is when you let go. Press Esc twice to cancel. You can change the shortcut in Settings.
@@ -56,9 +56,10 @@ A quick tap instead of a hold keeps listening until your next press. You can cli
| **Works in any app** | Types into the focused window, then restores your clipboard. Prefer to paste yourself? Switch to copy-only. |
| **One shortcut, three modes** | Smart (hold to talk, tap to keep listening), hold, or toggle. On macOS, a single key such as fn or right ⌘; anywhere, your own key combination. |
| **Never sends silence** | Whisper models invent text on silent audio ("Thank you."), so recordings without speech never leave your machine. |
+| **Runs on your computer too** | Transcribe offline, for free, with a model downloaded once. Nothing leaves your machine. |
| **Vocabulary hints** | Names, brands and jargon come out spelled right. |
| **Searchable history** | Find any dictation and copy it again, for when it landed in the wrong window. Retry when the network failed. |
-| **Guided setup** | Pick a service, paste your key, test it, try your first dictation. About two minutes. |
+| **Guided setup** | Sign in to Parler Cloud, download the model or paste your key, then try your first dictation. About two minutes. |
| **Menu bar and tray** | Start a dictation, copy the last transcript or open the history. Can start at login. |
| **30+ spoken languages** | Auto-detect, or pick yours for faster, more accurate results. |
| **Light or dark** | Or follow your system. The interface speaks 12 languages. |
@@ -67,7 +68,7 @@ A quick tap instead of a hold keeps listening until your next press. You can cli
## Speech-to-text providers and pricing
-Parler is free. It works with any service that speaks the OpenAI audio API (`POST /audio/transcriptions`), and you pay that service directly, at its own rates. Parler takes no cut.
+Parler is free. It transcribes on your computer, or with any service that speaks the OpenAI audio API (`POST /audio/transcriptions`), which you pay directly, at its own rates. Parler takes no cut.
| Provider | Default model | Also suggested | API key |
| --- | --- | --- | --- |
@@ -78,6 +79,17 @@ Parler is free. It works with any service that speaks the OpenAI audio API (`POS
You can type any other model a provider serves in Settings, and switch providers at any time: each one keeps its own key.
+### On this computer
+
+Choose **On this computer** and Parler transcribes locally, with [transcribe.cpp](https://github.com/handy-computer/transcribe.cpp): nothing is sent anywhere, it works offline, and it costs nothing. The first time, Parler downloads one model:
+
+| Model | Size | Languages | Vocabulary hints |
+| --- | --- | --- | --- |
+| **Parakeet Ultra** (recommended for European languages) | 740 MB | 25 European languages | No |
+| **Whisper Large v3 Turbo** (recommended for the others, or under *Advanced options*) | 620 MB | All languages | Yes |
+
+It uses your computer's power, so it can be slower while the computer is busy, and it's a little less accurate than Parler Cloud. Models come from [Hugging Face](https://huggingface.co/handy-computer), pinned to an exact version and checked against their SHA-256 fingerprint before use.
+
> [!TIP]
> **Rather not create an API key? Choose Parler Cloud.** Pick it when you set up Parler, sign in once from your browser, and dictate. Unlimited transcription for one person's normal use ([fair use](https://parler.synapsr.io/fair-use)), for €8 a month or €49 a year, excluding VAT, after a 3-day free trial. Your account: [cloud.parler.synapsr.io](https://cloud.parler.synapsr.io). Questions: [parler@synapsr.io](mailto:parler@synapsr.io).
@@ -145,18 +157,18 @@ On Linux, also install the [Tauri prerequisites](https://tauri.app/start/prerequ
## Privacy
-- Audio is recorded only while you dictate and sent only to the provider you picked. It is never written to disk, except a dictation that couldn't be sent (no connection, say): its audio is kept on this computer, readable only by your user account, until it's sent or you delete it, for 7 days at most.
+- Audio is recorded only while you dictate and sent only to the provider you picked; on this computer, it isn't sent at all. It is never written to disk, except a dictation that couldn't be sent (no connection, say): its audio is kept on this computer, readable only by your user account, until it's sent or you delete it, for 7 days at most.
- Recordings without speech are never sent.
- Your API key and settings live in a local file that only your user account can read.
- Your transcripts (the last 5,000) stay on your computer so you can search and copy them again. Clear them anytime.
-- No analytics, no telemetry. Your audio goes only to the service you picked: your provider directly, or Parler Cloud if you chose it. Parler Cloud keeps the audio in memory for the length of the request, transcribes it with Groq, and stores neither the audio nor the text.
+- No analytics, no telemetry. Your audio goes only to the service you picked: your provider directly, or Parler Cloud if you chose it. On this computer, it goes nowhere: Parler only connects to Hugging Face once, to download the model. Parler Cloud keeps the audio in memory for the length of the request, transcribes it with Groq, and stores neither the audio nor the text.
- Parler checks GitHub for new versions and downloads them from there (packagers can turn that off with `PARLER_DISABLE_UPDATER=1`).
- **Settings → About → Send the log** sends support Parler's version, your system and its technical log, only when you ask. Parler Cloud forwards it by email and keeps nothing.
- What a provider does with your audio is set by its own policy. With your own server, nothing leaves your network.
## Languages
-**Spoken:** Parler detects the language you speak, or you can pick one of 31: English, French, Spanish, German, Italian, Portuguese, Dutch, Breton, Catalan, Basque, Polish, Czech, Romanian, Hungarian, Swedish, Danish, Norwegian, Finnish, Greek, Turkish, Ukrainian, Russian, Arabic, Hebrew, Hindi, Indonesian, Vietnamese, Thai, Chinese, Japanese and Korean. Accuracy depends on the provider and model.
+**Spoken:** Parler detects the language you speak, or you can pick one of 31: English, French, Spanish, German, Italian, Portuguese, Dutch, Breton, Catalan, Basque, Polish, Czech, Romanian, Hungarian, Swedish, Danish, Norwegian, Finnish, Greek, Turkish, Ukrainian, Russian, Arabic, Hebrew, Hindi, Indonesian, Vietnamese, Thai, Chinese, Japanese and Korean. Accuracy depends on the provider and model. On this computer, Parakeet Ultra knows 25 European languages; for the others, Parler recommends Whisper Large v3 Turbo.
**Interface:** English, French, Spanish, German, Italian, Portuguese, Dutch, Polish, Turkish, Japanese, Chinese and Korean. [Add yours](docs/contributing.md#conventions).
@@ -165,35 +177,35 @@ On Linux, also install the [Tauri prerequisites](https://tauri.app/start/prerequ
Is Parler free?
-Yes. The app is free and open source under the MIT licence. You connect it to your own account at a speech-to-text service and pay that service directly, at its own rates; Groq offers free sign-up to get you started. Parler Cloud is the optional paid plan for people who'd rather not manage an API key: €8 a month or €49 a year, excluding VAT, after a 3-day free trial.
+Yes. The app is free and open source under the MIT licence. You connect it to your own account at a speech-to-text service and pay that service directly, at its own rates; Groq offers free sign-up to get you started. Transcribing on this computer costs nothing at all. Parler Cloud is the optional paid plan for people who'd rather not manage an API key: €8 a month or €49 a year, excluding VAT, after a 3-day free trial.
Which provider should I choose?
-Parler Cloud if you want nothing to set up. With your own key, Groq is the default: it runs Whisper large-v3 turbo, answers fast and has free sign-up. Pick OpenAI or Fireworks if you already have an account there, or your own server for full control. You can switch at any time in Settings.
+Parler Cloud if you want nothing to set up. On this computer if you want privacy and offline use, and don't mind a little less accuracy. With your own key, Groq is the default: it runs Whisper large-v3 turbo, answers fast and has free sign-up. Pick OpenAI or Fireworks if you already have an account there, or your own server for full control. You can switch at any time in Settings.
Does it work offline?
-Not on its own: transcription happens at the service you chose, so you need an internet connection. If you run an OpenAI-compatible server on your own network (speaches, LocalAI…), Parler works without the internet.
+Yes, if you choose **On this computer**: after a one-time model download, transcription happens on your computer, without the internet. The other services need a connection, unless you run an OpenAI-compatible server on your own network (speaches, LocalAI…).
How is it different from Wispr Flow, SuperWhisper or macOS Dictation?
-Same idea: talk instead of type, in any app. Parler's take: the code is open (MIT), the app is free, it runs on macOS, Windows and Linux, and you choose who transcribes your voice, from Groq, OpenAI or Fireworks to a server you run yourself. Parler types what you said; it doesn't rewrite it.
+Same idea: talk instead of type, in any app. Parler's take: the code is open (MIT), the app is free, it runs on macOS, Windows and Linux, and you choose who transcribes your voice: your own computer, offline, or Groq, OpenAI, Fireworks or a server you run yourself. Parler types what you said; it doesn't rewrite it.
Is my voice stored or used to train models?
-Parler doesn't keep your audio, except a dictation that couldn't be sent: that one waits on your computer until it's sent or you delete it, for 7 days at most. Otherwise it keeps only the text of your dictations, which you can clear at any time. What the provider does with the audio depends on its own policy, so give it a read before you choose.
+Parler doesn't keep your audio, except a dictation that couldn't be sent: that one waits on your computer until it's sent or you delete it, for 7 days at most. Otherwise it keeps only the text of your dictations, which you can clear at any time. What the provider does with the audio depends on its own policy, so give it a read before you choose. On this computer, there is no provider: the audio stays with you.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index c7f04e4..6fbcb76 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -34,3 +34,62 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+
+## transcribe.cpp and ggml
+
+Transcription on this computer runs on
+[transcribe.cpp](https://github.com/handy-computer/transcribe.cpp), through
+its Rust bindings ([`transcribe-cpp`](https://crates.io/crates/transcribe-cpp)),
+built into Parler (macOS) or shipped next to it (Windows, Linux). It includes
+[ggml](https://github.com/ggml-org/ggml), [miniz](https://github.com/richgel999/miniz)
+and code translated from [Silero VAD](https://github.com/snakers4/silero-vad),
+all under the MIT licence.
+
+```
+MIT License
+
+Copyright (c) 2026 The transcribe.cpp authors
+Copyright (c) 2023-2026 The ggml authors
+Copyright 2013-2014 RAD Game Tools and Valve Software
+Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
+Copyright (c) 2020-present Silero Team
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+## Speech models
+
+Parler doesn't ship a model: one is downloaded when transcription on this
+computer is turned on, from the GGUF conversions published by
+[handy-computer](https://huggingface.co/handy-computer) on Hugging Face.
+
+- **Parakeet Ultra**
+ ([handy-computer/parakeet-ultra-gguf](https://huggingface.co/handy-computer/parakeet-ultra-gguf),
+ Q8_0) is [Moondream](https://moondream.ai)'s post-trained
+ [moondream/parakeet-ultra](https://huggingface.co/moondream/parakeet-ultra),
+ built on NVIDIA's
+ [parakeet-tdt-0.6b-v3](https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3).
+ Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/);
+ converted to GGUF and quantized by handy-computer, otherwise unchanged.
+- **Whisper Large v3 Turbo**
+ ([handy-computer/whisper-large-v3-turbo-gguf](https://huggingface.co/handy-computer/whisper-large-v3-turbo-gguf),
+ Q5_K_M) is OpenAI's
+ [whisper-large-v3-turbo](https://huggingface.co/openai/whisper-large-v3-turbo),
+ released under the MIT licence (the conversion is published under
+ Apache-2.0); converted to GGUF and quantized by handy-computer.
diff --git a/docs/architecture.md b/docs/architecture.md
index 4e28141..2074c2f 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -8,6 +8,7 @@ transcribes and pastes, and a React interface in two windows.
tray menu ───────┼──► dictation loop ──► microphone (handy-recorder, 16 kHz mono)
parler --toggle ─┘ (one thread) ──► speech check, WAV encoding
│ ──► provider API (multipart POST /audio/transcriptions)
+ │ or the model on this computer (transcribe.cpp)
│ ──► not sent? kept on disk to send again (pending)
│ ──► paste: clipboard + Cmd/Ctrl+V, clipboard restored
▼
@@ -23,7 +24,8 @@ transcribes and pastes, and a React interface in two windows.
| `dictation.rs` | The dictation loop. One thread owns the microphone and the state; the shortcut, tray, microphone and finished transcriptions all send it events, so press/release/cancel never race. It sends a passing failure once more, keeps what still fails in `pending`, and adds a space after a pasted sentence. A panic in one event is logged and the loop goes back to idle, freeing the microphone, instead of leaving dictation dead until a restart. |
| `audio.rs` | Microphone capture, the voice level for the pill, noticing a microphone that sends nothing, the speech check that keeps silence from being sent, WAV encoding. |
| `pending.rs` | Dictations that couldn't be sent: their speech and a few facts on disk, readable by the user only, until sent, deleted or 7 days old (see below). |
-| `providers.rs` | The provider list and the request to a Whisper-compatible API, with errors the interface can explain. |
+| `providers.rs` | The provider list and the request to a Whisper-compatible API (or, for `local`, to the model here), with errors the interface can explain. |
+| `local.rs` | Transcription on this computer: the two speech models, their resumable, verified downloads, and the engine that keeps one loaded, on the GPU when it can (see below). |
| `cloud.rs` | Parler Cloud: linking a computer with a device code, the account, signing out. |
| `updates.rs` | Checks for updates, downloads and installs them, then restarts Parler. |
| `diagnostics.rs` | Settings → About → "Send the log": version, system, a few settings, the microphone permission (macOS, Windows) and Accessibility (macOS), and the end of the log (keys masked) to `POST /api/diagnostics` on Parler Cloud, which emails support and keeps nothing. |
@@ -89,6 +91,57 @@ nothing depends on deep links or the OS:
- `PARLER_CLOUD_URL` (read once at startup) points the app at another
service, for instance `PARLER_CLOUD_URL=http://localhost:3100 pnpm tauri dev`.
+### Transcription on this computer
+
+The provider `local` ("On this computer") runs a speech model with
+[transcribe.cpp](https://github.com/handy-computer/transcribe.cpp) (ggml):
+nothing leaves the computer, no account or key.
+
+```
+ Settings: download ──► /models/.part (HTTP Range: resumes)
+ ──► SHA-256 checked (blocking thread) ──► renamed
+ local is the provider, or a dictation starts ──► model loaded in the background
+ dictation ──► kept in pending first ──► engine (one run at a time) ──► text
+ └► removed from pending once transcribed
+```
+
+- **Two models**, from `handy-computer` on Hugging Face at a pinned
+ revision: Parakeet Ultra (25 European languages, 740 MB) and Whisper Large
+ v3 Turbo (every language, takes the vocabulary, 620 MB). The recommended
+ one is Parakeet when it knows the dictation language, or the interface's
+ when that is detected, or the system's when the interface follows it;
+ Whisper otherwise. `models.local` holds a choice made in Settings.
+- **State comes from the folder**: a model under its own name at its size is
+ ready (it was only renamed once verified); a `.part` is a download to
+ resume. Progress reaches the window as `parler://local-models`, at most
+ every 120 ms. A cancelled download keeps its part; a wrong checksum throws
+ it away; a server that ignores the Range header starts over.
+- **One model loaded**, kept between dictations, let go after 15 minutes
+ unused, when another provider is picked, or before its file is deleted
+ (Windows can't delete a mapped file). Both models decode long dictations
+ themselves.
+- **Where it runs.** Apple Silicon: Metal, built in. Intel Macs: the CPU,
+ built in (Metal on Intel and AMD GPUs gains little and can hang). Windows
+ and Linux: Vulkan when a driver offers a GPU (integrated ones included),
+ else the CPU, from modules loaded at launch (`transcribe-libs/`, staged by
+ `build.rs`): one CPU module per instruction set, the fastest this
+ processor runs picked at launch, and Parler starts without Vulkan
+ installed. `local_backend` and the support report say which is in use.
+ On Windows, Vulkan's implicit layers (overlays, capture tools) are kept
+ out of Parler, as some crash the apps they hook
+ (`PARLER_KEEP_VULKAN_LAYERS=1` keeps them).
+- **When the GPU fails.** A model that fails to load, or a run that fails,
+ on the GPU goes to the CPU for the rest of the session. ggml can also end
+ the process on a driver fault: a marker file
+ (`/local-gpu-running`) is written around every GPU load and run,
+ and a launch that finds it writes `local-gpu-off` and keeps to the CPU
+ until the next version of Parler.
+- **No dictation lost to a crash.** Before the engine runs, the speech is
+ saved among the unsent dictations, and removed once transcribed or
+ cancelled: after a crash it is there in History, to try again.
+- Errors: `modelMissing` (needs setup: the window opens) and `localFailed`;
+ neither is tried again by itself.
+
### Updates
Parler updates itself with Tauri's updater plugin, driven from Rust:
@@ -149,8 +202,7 @@ to find out.
### Dictations that couldn't be sent
-Parler transcribes in the cloud only, so a flaky network must never cost a
-dictation.
+A flaky network, or a crash on this computer, must never cost a dictation.
- **One more try.** A passing failure (no connection, a 5xx) is sent again
once, 1.5 s later, while the pill keeps writing. Not a timeout (two minutes
@@ -162,7 +214,8 @@ dictation.
survives a restart and leaves as soon as it is transcribed or deleted,
after 7 days at most; past 20 dictations or 50 MB the oldest go first (the
newest always stays). If the disk refuses it, it lasts in memory until
- Parler quits. The audio only ever goes to the service.
+ Parler quits. The audio only ever goes to the service (or stays here, for
+ `local`).
- **Sending it again.** History lists unsent dictations first, each with *Try
again* and *Delete*; Home's problem banner retries the one that just
failed. Text sent again from the window is copied (pasting would type into
diff --git a/docs/contributing.md b/docs/contributing.md
index e212a92..f4797ab 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -7,12 +7,23 @@ setting, ask whether a better default would do.
- [Rust](https://rustup.rs) 1.88 or newer
- [Node.js](https://nodejs.org) 20+ and [pnpm](https://pnpm.io) 10
+- [CMake](https://cmake.org) and a C++ compiler (Xcode's command line tools,
+ Visual Studio's C++ workload, or GCC): the speech engine for transcription
+ on this computer is built from source
+- Windows and Linux: the [Vulkan SDK](https://vulkan.lunarg.com) (its
+ headers and shader compiler build the engine's GPU backend; Parler runs
+ without it), and on Windows SPIRV-Headers
+ (`vcpkg install spirv-headers:x64-windows`, its prefix in
+ `CMAKE_PREFIX_PATH`)
- Linux only: the [Tauri prerequisites](https://tauri.app/start/prerequisites/#linux) and
```sh
sudo apt install libasound2-dev libpulse-dev libxtst-dev libxkbcommon-dev
```
+The first build compiles the engine (a few minutes; on Windows and Linux,
+once per CPU instruction set); later ones reuse it.
+
```sh
pnpm install
pnpm tauri dev
@@ -27,7 +38,8 @@ pick the state: `onboarded=1`, `lang=en`, `platform=windows`, `problem=1`,
`RightControl`, or an accelerator), `problem=key` (a key alone waiting for
Accessibility), `update=available` (`downloading`, `waiting`, `restarting`,
`error`, `offline`, `uptodate`, `disabled`), or `view=overlay&phase=recording`
-(`transcribing`, `error`, `empty`).
+(`transcribing`, `error`, `empty`). `w=780` narrows the window to its
+smallest width.
Parler Cloud: `cloud=signed-out` (or `trial`, `active`, `canceling`,
`past-due`, `inactive`, `canceled`, `offline`) picks it in that state;
@@ -44,6 +56,31 @@ or `view=overlay&phase=error&error=nosound`. Unsent dictations:
`onboarded=1&pending=3` lists them in History (up to 4); sending one again
succeeds unless `retry=fail`.
+On this computer: `local=missing` (or `downloading`, `ready`, `failed`)
+puts its model in that state, and once onboarded picks it as the service;
+`localModel=whisper` uses Whisper Large v3 Turbo instead of the recommended
+model (Parakeet Ultra for the default French); `localError=offline` (`disk`,
+`checksum`, `other`) says why `failed`; `download=fail` stops a download a
+third of the way; `backend=CPU` (or `Vulkan · AMD Radeon 780M`;
+`Metal · Apple M4` by default) is what it runs on, and `loaded=0` leaves the
+ready model unloaded, so Settings says where it will run. Downloads run in about eight seconds.
+`problem=modelMissing` or `problem=localFailed` shows its problems, and
+`view=overlay&phase=error&error=modelMissing` the pill. To reach the
+download step of the first-run flow: `lang=en&clicks=Get started,on this computer`.
+
+The speech models can be tried without the app: the ignored test
+downloads one (into a folder it keeps) and transcribes 16 kHz mono WAV
+files, printing load and run times and where it ran.
+
+```sh
+cd src-tauri
+PARLER_MODELS_DIR=~/parler-models PARLER_TEST_WAVS=fr.wav,en.wav \
+ cargo test --release --lib real_download_and_transcription -- --ignored --nocapture
+```
+
+`PARLER_TEST_MODEL=whisper-large-v3-turbo` picks Whisper, `PARLER_TEST_CPU=1`
+keeps off the GPU and `PARLER_TEST_LANGUAGE=fr` passes a language.
+
## Checks
CI runs these on every pull request; run them before pushing:
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 4b89231..d7d3c10 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -608,6 +608,15 @@ dependencies = [
"error-code",
]
+[[package]]
+name = "cmake"
+version = "0.1.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "combine"
version = "4.6.9"
@@ -3297,6 +3306,8 @@ dependencies = [
"reqwest 0.12.28",
"serde",
"serde_json",
+ "sha2",
+ "sys-locale",
"tauri",
"tauri-build",
"tauri-nspanel",
@@ -3307,6 +3318,7 @@ dependencies = [
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
+ "transcribe-cpp",
"windows 0.61.3",
]
@@ -4482,6 +4494,15 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "sys-locale"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "system-configuration"
version = "0.7.0"
@@ -5308,6 +5329,27 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "transcribe-cpp"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bab65d30f5a4c3ea0ab6f38236823389f3914b0605bbc0073a4ec88018c0714"
+dependencies = [
+ "log",
+ "thiserror 2.0.21",
+ "transcribe-cpp-sys",
+]
+
+[[package]]
+name = "transcribe-cpp-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23a837974fdb873998a59a21ad2bf5a4b7bbf721c20d03d2a3ab8c221726a444"
+dependencies = [
+ "cmake",
+ "serde_json",
+]
+
[[package]]
name = "transpose"
version = "0.2.3"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index eee037e..83720a3 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -39,6 +39,31 @@ reqwest = { version = "0.12", features = ["json", "multipart"] }
arboard = "3"
enigo = "0.6"
tauri-plugin-updater = "2"
+# Hashes a downloaded speech model before it is used (see local.rs).
+sha2 = "0.10"
+# The system's language, which picks the recommended speech model when the
+# interface follows it (already in the tree through tauri).
+sys-locale = "0.3"
+
+# Transcription on this computer (local.rs). The native library is built
+# from source with CMake. Apple Silicon runs it on the GPU through Metal,
+# linked in with its shaders. Intel Macs run it on the CPU, built in for a
+# portable floor (SSE4.2, AVX, F16C): Metal on Intel and AMD GPUs gains little
+# and its shader compile can hang on some of them.
+[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies]
+transcribe-cpp = { version = "0.4.1", default-features = false, features = ["metal"] }
+
+[target.'cfg(all(target_os = "macos", target_arch = "x86_64"))'.dependencies]
+transcribe-cpp = { version = "0.4.1", default-features = false }
+
+# Windows and Linux: the GPU through Vulkan when a driver offers one
+# (integrated GPUs included), else the CPU. Both come as modules loaded at
+# launch, so Parler starts without any Vulkan installed; the CPU code comes
+# as one module per instruction set, from plain x86-64 to AVX-512, and the
+# fastest this processor runs is picked. build.rs stages the modules and the
+# bundles ship them next to Parler.
+[target.'cfg(any(windows, target_os = "linux"))'.dependencies]
+transcribe-cpp = { version = "0.4.1", default-features = false, features = ["dynamic-backends", "vulkan"] }
[target.'cfg(target_os = "macos")'.dependencies]
# Turns the overlay into a non-activating panel, so showing it never takes
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
index d860e1e..60826e7 100644
--- a/src-tauri/build.rs
+++ b/src-tauri/build.rs
@@ -1,3 +1,129 @@
+//! Besides Tauri's own build: what the speech engine (transcribe-cpp, see
+//! `src/local.rs` and Cargo.toml) needs to link and to ship.
+
+use std::collections::BTreeMap;
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+/// Where the engine's libraries are gathered for the bundles: next to the
+/// executable on Windows (tauri.windows.conf.json), in `/usr/lib/Parler`
+/// (deb, rpm) or `usr/lib` (AppImage) on Linux (tauri.linux.conf.json).
+const STAGING: &str = "transcribe-libs";
+
fn main() {
+ let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
+ match target_os.as_str() {
+ "macos" => link_clang_runtime(),
+ "linux" => {
+ // Where the packages put libtranscribe and the ggml modules.
+ println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN/../lib/Parler:$ORIGIN/../lib");
+ // `cargo run` and `cargo test` find them where they were built.
+ if env::var("PROFILE").as_deref() != Ok("release") {
+ if let Some(dir) = env::var_os("DEP_TRANSCRIBE_CPP_RUNTIME_DIR") {
+ println!(
+ "cargo:rustc-link-arg=-Wl,-rpath,{}",
+ Path::new(&dir).display()
+ );
+ }
+ }
+ }
+ _ => {}
+ }
+ stage_engine_libraries();
tauri_build::build()
}
+
+/// macOS: ggml's Metal code checks the system version with `@available`.
+/// Built for an older macOS than the SDK's (11.0 here), clang turns those
+/// checks into calls to `__isPlatformVersionAtLeast`, from clang's runtime,
+/// which rustc doesn't link. Builds for the host's own version fold them
+/// away, so only release builds would fail.
+fn link_clang_runtime() {
+ let Ok(output) = std::process::Command::new("clang")
+ .arg("--print-resource-dir")
+ .output()
+ else {
+ println!("cargo:warning=clang not found: can't link libclang_rt.osx.a");
+ return;
+ };
+ let resource_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ let dir = Path::new(&resource_dir).join("lib/darwin");
+ if !dir.join("libclang_rt.osx.a").exists() {
+ println!("cargo:warning=libclang_rt.osx.a not in {}", dir.display());
+ return;
+ }
+ println!("cargo:rustc-link-search=native={}", dir.display());
+ println!("cargo:rustc-link-lib=static=clang_rt.osx");
+}
+
+/// Windows and Linux: the engine is a shared library plus backend modules
+/// (Vulkan, one CPU module per instruction set) loaded at launch. They are
+/// copied to `transcribe-libs/` for the bundles. (On Windows they need the
+/// Visual C++ runtime, which the bundles ship too: `bundleVCRuntime` in
+/// tauri.windows.conf.json.) macOS links the engine in: nothing to ship,
+/// the folder stays empty.
+fn stage_engine_libraries() {
+ println!("cargo:rerun-if-env-changed=DEP_TRANSCRIBE_CPP_RUNTIME_DIR");
+ println!("cargo:rerun-if-env-changed=DEP_TRANSCRIBE_CPP_MODULE_DIR");
+ let dest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join(STAGING);
+ // Fresh each time, so a module dropped upstream never lingers.
+ let _ = fs::remove_dir_all(&dest);
+ fs::create_dir_all(&dest).expect("create transcribe-libs/");
+
+ let Some(runtime_dir) = env::var_os("DEP_TRANSCRIBE_CPP_RUNTIME_DIR") else {
+ return;
+ };
+ let mut dirs = vec![PathBuf::from(runtime_dir)];
+ if let Some(module_dir) = env::var_os("DEP_TRANSCRIBE_CPP_MODULE_DIR") {
+ dirs.push(PathBuf::from(module_dir));
+ }
+
+ // Each library once, under the name the loader asks for. Linux keeps a
+ // chain of names (libggml.so -> .so.0 -> .so.0.9.4) that the packagers
+ // would turn into three copies: the shortest versioned name is the
+ // linked one, a bare `.so` the dlopen'd module's.
+ let mut best: BTreeMap = BTreeMap::new();
+ for dir in &dirs {
+ println!("cargo:rerun-if-changed={}", dir.display());
+ let entries = fs::read_dir(dir).unwrap_or_else(|e| panic!("read {}: {e}", dir.display()));
+ for path in entries.flatten().map(|e| e.path()) {
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("")
+ .to_string();
+ let (stem, rank) = match versioned_so(&name) {
+ Some((stem, 0)) => (stem.to_string(), usize::MAX),
+ Some((stem, depth)) => (stem.to_string(), depth - 1),
+ None if name.ends_with(".dll") || name.ends_with(".dylib") => (name.clone(), 0),
+ None => continue,
+ };
+ if best.get(&stem).is_none_or(|(r, _, _)| rank < *r) {
+ best.insert(stem, (rank, path, name));
+ }
+ }
+ }
+ assert!(
+ !best.is_empty(),
+ "no transcribe-cpp libraries in {dirs:?}: the bundles would load no engine"
+ );
+ for (_, src, name) in best.values() {
+ fs::copy(src, dest.join(name)).unwrap_or_else(|e| panic!("copy {}: {e}", src.display()));
+ }
+}
+
+/// `libfoo.so` → ("libfoo", 0), `libfoo.so.0.9` → ("libfoo", 2); `None`
+/// for anything else.
+fn versioned_so(name: &str) -> Option<(&str, usize)> {
+ let at = name.find(".so")?;
+ let (stem, rest) = (&name[..at], &name[at + 3..]);
+ if rest.is_empty() {
+ return Some((stem, 0));
+ }
+ let parts: Vec<&str> = rest.strip_prefix('.')?.split('.').collect();
+ parts
+ .iter()
+ .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
+ .then_some((stem, parts.len()))
+}
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index 55df6c9..890349c 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -5,6 +5,7 @@ use crate::cloud::{self, Account, DeviceStart, Poll, SignIn};
use crate::diagnostics::{self, SendError};
use crate::dictation::{Dictation, Event, Problem, Status, StatusState};
use crate::history::{self, Entry, History, Stats};
+use crate::local::{self, Backend, LocalModel};
use crate::paste::{self, PasteError};
use crate::pending::Unsent;
use crate::providers::{self, Provider, Request, TranscribeError};
@@ -47,6 +48,7 @@ pub fn save_settings(app: AppHandle, mut settings: Settings) -> Result Result Vec {
/// Sends half a second of silence with `settings`, which need not be saved
/// yet, so a wrong key, model or URL shows up during setup. Parler Cloud
-/// checks the account instead, which costs no dictation time.
+/// checks the account instead, which costs no dictation time; on this
+/// computer, the model is loaded (and stays so for the first dictation).
#[tauri::command]
pub async fn test_provider(settings: Settings) -> Result<(), TranscribeError> {
let request = Request::from_settings(&settings)?;
+ if request.is_local() {
+ return local::test(&settings).await;
+ }
if settings.provider == cloud::ID {
let token = settings
.api_keys
@@ -223,6 +230,36 @@ fn cloud_token(app: &AppHandle) -> String {
.unwrap_or_default()
}
+/// The speech models for this computer and where each stands; changes come
+/// as `parler://local-models`.
+#[tauri::command]
+pub fn local_models(store: State) -> Vec {
+ local::models(&store.get())
+}
+
+/// Starts (or resumes) downloading a model, in the background.
+#[tauri::command]
+pub fn download_local_model(id: String) -> Result<(), String> {
+ local::download(&id)
+}
+
+/// Stops a download; what came is kept to resume from.
+#[tauri::command]
+pub fn cancel_local_model_download(id: String) {
+ local::cancel(&id);
+}
+
+#[tauri::command]
+pub async fn delete_local_model(id: String) -> Result<(), String> {
+ local::delete(&id).await
+}
+
+/// Where the model runs (or will): the GPU or the processor, by name.
+#[tauri::command]
+pub async fn local_backend() -> Option {
+ local::backend().await
+}
+
#[tauri::command]
pub async fn list_microphones() -> Vec {
tauri::async_runtime::spawn_blocking(audio::list_microphones)
diff --git a/src-tauri/src/diagnostics.rs b/src-tauri/src/diagnostics.rs
index fbafae1..d654ef2 100644
--- a/src-tauri/src/diagnostics.rs
+++ b/src-tauri/src/diagnostics.rs
@@ -52,13 +52,16 @@ struct Sent {
pub async fn send(app: &AppHandle, note: &str) -> Result {
let settings = app.state::().get();
let note: String = note.trim().chars().take(NOTE_MAX).collect();
+ let mut fields = fields(
+ &app.package_info().version.to_string(),
+ &settings,
+ &permissions().await,
+ );
+ // The model on this computer and where it runs (Metal, Vulkan, CPU).
+ fields.extend(crate::local::report_fields(&settings));
let report = Report {
note: ¬e,
- app: fields(
- &app.package_info().version.to_string(),
- &settings,
- &permissions().await,
- ),
+ app: fields,
log: mask_secrets(&read_tail(&log_files(app), LOG_TAIL)),
};
// Signed in to Parler Cloud: support can answer the account's address.
diff --git a/src-tauri/src/dictation.rs b/src-tauri/src/dictation.rs
index 3e78cc2..2aca783 100644
--- a/src-tauri/src/dictation.rs
+++ b/src-tauri/src/dictation.rs
@@ -4,12 +4,12 @@
use crate::audio::{self, CaptureEvent, CaptureSink, MicrophoneError};
use crate::history::{self, History};
-use crate::mute;
use crate::overlay::{self, Hint, Phase as OverlayPhase};
use crate::paste::{self, PasteError};
use crate::pending::{Pending, Unsent};
use crate::providers::{self, Request, TranscribeError};
use crate::settings::{Output, Settings, SettingsStore, ShortcutMode};
+use crate::{local, mute};
use crate::{shortcut, tray};
use handy_recorder::Recorder;
use serde::Serialize;
@@ -58,6 +58,9 @@ pub enum Event {
Finished {
session: u64,
outcome: Outcome,
+ /// Kept among the unsent dictations while it was transcribed on
+ /// this computer (see `keep_while_local`).
+ kept: Option,
},
PasteFailed(PasteError),
}
@@ -297,7 +300,11 @@ impl Controller {
}
}
}
- Event::Finished { session, outcome } => self.finished(session, outcome),
+ Event::Finished {
+ session,
+ outcome,
+ kept,
+ } => self.finished(session, outcome, kept),
Event::PasteFailed(error) => {
let needs_permission = error == PasteError::NeedsAccessibility;
self.report(Problem::Paste { error });
@@ -400,9 +407,14 @@ impl Controller {
fn start(&mut self, latched: bool) {
let settings = self.settings();
// Recording is pointless until a provider is set up: say so instead.
- if let Err(error) = Request::from_settings(&settings) {
- self.fail(Problem::Transcription { error }, true);
- return;
+ match Request::from_settings(&settings) {
+ Err(error) => {
+ self.fail(Problem::Transcription { error }, true);
+ return;
+ }
+ // Loaded while the person speaks, if it was let go.
+ Ok(request) if request.is_local() => local::warm(&settings),
+ Ok(_) => {}
}
overlay::show(&self.app, OverlayPhase::Connecting, settings.sounds);
@@ -456,12 +468,20 @@ impl Controller {
let settings = self.begin_sending();
let session = self.session;
let tx = self.tx.clone();
+ let pending = self.pending.clone();
tauri::async_runtime::spawn(async move {
- let outcome = match prepare(&samples) {
- Ok(speech) => send(&settings, speech, Some(RETRY_AFTER)).await,
- Err(outcome) => outcome,
+ let (outcome, kept) = match prepare(&samples) {
+ Ok(speech) => {
+ let kept = keep_while_local(&settings, &pending, &speech);
+ (send(&settings, speech, Some(RETRY_AFTER)).await, kept)
+ }
+ Err(outcome) => (outcome, None),
};
- let _ = tx.send(Event::Finished { session, outcome });
+ let _ = tx.send(Event::Finished {
+ session,
+ outcome,
+ kept,
+ });
});
}
@@ -478,25 +498,31 @@ impl Controller {
/// Sends speech already prepared, in the current session: an unsent
/// dictation, or the second try of a passing failure.
- fn resend(&self, speech: Speech, retry_after: Option) {
+ fn resend(&self, speech: Speech, retry_after: Option, kept: Option) {
let settings = self.settings();
let session = self.session;
let tx = self.tx.clone();
tauri::async_runtime::spawn(async move {
let outcome = send(&settings, speech, retry_after).await;
- let _ = tx.send(Event::Finished { session, outcome });
+ let _ = tx.send(Event::Finished {
+ session,
+ outcome,
+ kept,
+ });
});
}
- fn finished(&mut self, session: u64, outcome: Outcome) {
+ fn finished(&mut self, session: u64, outcome: Outcome, kept: Option) {
if session != self.session || !matches!(self.phase, Phase::Transcribing) {
- return; // cancelled
+ // Cancelled: what was kept meanwhile goes with it.
+ self.forget_kept(kept);
+ return;
}
match outcome {
// The pill keeps writing through the second try.
Outcome::TryAgain { error, speech } => {
log::info!("Transcription failed ({error}); trying once more");
- self.resend(speech, None);
+ self.resend(speech, None, kept);
}
Outcome::Text {
text,
@@ -505,6 +531,7 @@ impl Controller {
} => {
self.end();
overlay::hide(&self.app);
+ self.forget_kept(kept);
self.forget_resent();
self.app
.state::()
@@ -515,6 +542,7 @@ impl Controller {
}
Outcome::Silence => {
self.end();
+ self.forget_kept(kept);
self.forget_resent();
overlay::flash(&self.app, OverlayPhase::Empty, self.sounds(), None);
self.publish(State::Idle, None);
@@ -535,8 +563,9 @@ impl Controller {
| TranscribeError::Unauthorized { .. }
| TranscribeError::SignedOut { .. }
| TranscribeError::SubscriptionRequired { .. }
+ | TranscribeError::ModelMissing { .. }
);
- self.keep_unsent(speech, &error);
+ self.keep_unsent(speech, &error, kept);
self.fail(Problem::Transcription { error }, needs_setup);
}
}
@@ -550,8 +579,8 @@ impl Controller {
/// Keeps a dictation that couldn't be sent, on disk, so it can be sent
/// later, even after a restart.
- fn keep_unsent(&mut self, speech: Speech, error: &TranscribeError) {
- self.last_failed = match self.resending {
+ fn keep_unsent(&mut self, speech: Speech, error: &TranscribeError, kept: Option) {
+ self.last_failed = match self.resending.or(kept) {
Some(id) => self.pending.failed_again(id, error).then_some(id),
None => Some(
self.pending
@@ -577,6 +606,14 @@ impl Controller {
}
}
+ /// Transcribed on this computer, or cancelled: the copy kept while the
+ /// engine ran leaves the store.
+ fn forget_kept(&mut self, kept: Option) {
+ if kept.is_some_and(|id| self.pending.remove(id)) {
+ self.pending_changed();
+ }
+ }
+
fn pending_changed(&self) {
let _ = self
.app
@@ -656,7 +693,7 @@ impl Controller {
wav,
duration_ms: unsent.duration_ms,
};
- self.resend(speech, Some(RETRY_AFTER));
+ self.resend(speech, Some(RETRY_AFTER), None);
}
fn discard(&mut self, id: u64) {
@@ -735,6 +772,17 @@ fn prepare(samples: &[f32]) -> Result {
})
}
+/// On this computer, a native crash (a GPU driver, the model) would end
+/// Parler and the dictation with it. So the speech is kept first, among the
+/// dictations that couldn't be sent, which survive a restart; it leaves the
+/// store once transcribed or cancelled. Its id.
+fn keep_while_local(settings: &Settings, pending: &Pending, speech: &Speech) -> Option {
+ if settings.provider != local::ID {
+ return None;
+ }
+ Some(pending.save(speech.wav.clone(), speech.duration_ms, local::interrupted()))
+}
+
/// Sends speech to the service. With `retry_after`, a passing failure comes
/// back as `TryAgain` once that time has gone by.
async fn send(settings: &Settings, speech: Speech, retry_after: Option) -> Outcome {
@@ -901,6 +949,29 @@ mod tests {
));
}
+ #[test]
+ fn a_local_dictation_is_kept_until_transcribed() {
+ let dir = std::env::temp_dir().join(format!("parler-kept-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let pending = Pending::load(dir.clone());
+ assert_eq!(
+ keep_while_local(&custom(String::new()), &pending, &speech()),
+ None
+ );
+
+ let here = Settings {
+ provider: local::ID.to_string(),
+ ..Settings::default()
+ };
+ let id = keep_while_local(&here, &pending, &speech()).unwrap();
+ // What a restart after a crash would find.
+ let after_a_crash = Pending::load(dir.clone()).list();
+ assert_eq!(after_a_crash[0].id, id);
+ assert_eq!(after_a_crash[0].error, local::interrupted());
+ assert!(pending.get(id).is_some_and(|(_, wav)| wav == speech().wav));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn no_connection_is_tried_once_more() {
// A port nothing listens on any more.
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 8e6e8d4..d8de070 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -4,6 +4,7 @@ mod commands;
mod diagnostics;
mod dictation;
mod history;
+mod local;
#[cfg(target_os = "macos")]
mod modifier_key;
mod mute;
@@ -107,6 +108,8 @@ pub fn run() {
.plugin(
tauri_plugin_log::Builder::new()
.level(log::LevelFilter::Info)
+ // ggml describes every tensor it loads; only its problems.
+ .level_for("transcribe_cpp", log::LevelFilter::Warn)
// Weeks of use rather than hours, for a report to support.
.max_file_size(512 * 1024)
.rotation_strategy(tauri_plugin_log::RotationStrategy::KeepSome(2))
@@ -160,6 +163,7 @@ pub fn run() {
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
}
mute::init(data_dir.clone());
+ local::init(&handle, data_dir.clone());
app.manage(History::load(data_dir.join("history.json")));
app.manage(ClipboardState::new());
app.manage(StatusState(Mutex::new(Status {
@@ -169,6 +173,8 @@ pub fn run() {
})));
app.manage(Dictation::spawn(&handle));
updates::start(&handle);
+ // Ready before the first dictation, when it runs here.
+ local::settings_changed(&app.state::().get());
overlay::create(&handle);
tray::create(&handle)?;
@@ -208,6 +214,11 @@ pub fn run() {
commands::cloud_sign_in_poll,
commands::cloud_account,
commands::cloud_sign_out,
+ commands::local_models,
+ commands::download_local_model,
+ commands::cancel_local_model_download,
+ commands::delete_local_model,
+ commands::local_backend,
commands::list_microphones,
commands::get_history,
commands::get_stats,
diff --git a/src-tauri/src/local.rs b/src-tauri/src/local.rs
new file mode 100644
index 0000000..d69d6db
--- /dev/null
+++ b/src-tauri/src/local.rs
@@ -0,0 +1,1696 @@
+//! Transcription on this computer: a speech model downloaded once, then run
+//! by [transcribe.cpp](https://github.com/handy-computer/transcribe.cpp).
+//! The audio never leaves the computer.
+//!
+//! - **Two models**, pinned to one revision on Hugging Face and checked
+//! against their SHA-256 before use. They live in
+//! `/models/`. A download goes to `.part`, picks up
+//! where it stopped (HTTP Range), and is renamed once verified, so a file
+//! under its own name is always whole. Whether a model is ready is read
+//! from that folder, never stored.
+//! - **One model loaded at a time**, kept between dictations. It loads in
+//! the background as soon as `local` is the provider, or a dictation
+//! starts, so nobody waits for it after speaking; it is let go after 15
+//! minutes unused or when another provider is picked. One transcription
+//! runs at a time, on a blocking thread.
+//! - **The GPU when there is one**: Metal on Apple Silicon, Vulkan on Windows
+//! and Linux; the CPU otherwise, and on Intel Macs. A GPU that fails to
+//! load the model, or to run it, makes way for the CPU. One that took
+//! Parler down (ggml ends the process on some driver faults) is not tried
+//! again by this version: a marker file is written around each GPU load
+//! and run, and a launch that finds it turns the GPU off.
+
+use crate::providers::TranscribeError;
+use crate::settings::{Settings, SettingsStore};
+use serde::Serialize;
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use std::fs;
+use std::io::{self, Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, MutexGuard, OnceLock};
+use std::thread;
+use std::time::{Duration, Instant};
+use tauri::{AppHandle, Emitter, Manager};
+use transcribe_cpp::{Backend as Compute, DeviceType, Feature, ModelOptions, RunOptions, Session};
+
+pub const ID: &str = "local";
+/// The provider's name in logs and the history; the window shows its own.
+pub const LABEL: &str = "Parler (local)";
+pub const PARAKEET: &str = "parakeet-ultra";
+pub const WHISPER: &str = "whisper-large-v3-turbo";
+
+/// Where the models live, in the app's data directory.
+const MODELS_DIR: &str = "models";
+/// Written before each GPU load or run and removed after: found at launch,
+/// the GPU took Parler down.
+const GPU_RUNNING: &str = "local-gpu-running";
+/// The GPU is off for the version written in it, after a crash.
+const GPU_OFF: &str = "local-gpu-off";
+/// A model unused this long is let go, freeing its memory.
+const IDLE_UNLOAD: Duration = Duration::from_secs(15 * 60);
+const IDLE_CHECK: Duration = Duration::from_secs(30);
+/// Progress events, at most this often (like updates.rs).
+const PROGRESS_EVERY: Duration = Duration::from_millis(120);
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+/// No byte for this long and the download is given up, keeping what came.
+const READ_TIMEOUT: Duration = Duration::from_secs(60);
+/// What a dictation kept before the engine runs says, should Parler stop
+/// before it is transcribed.
+const STOPPED_WHILE_TRANSCRIBING: &str = "Parler stopped while transcribing";
+
+/// A speech model Parler can download.
+#[derive(Debug)]
+pub struct Model {
+ pub id: &'static str,
+ pub name: &'static str,
+ file: &'static str,
+ url: &'static str,
+ pub size: u64,
+ sha256: &'static str,
+ /// ISO 639-1 codes; `None` for every language Whisper knows.
+ pub languages: Option<&'static [&'static str]>,
+ /// Takes the vocabulary as a spelling hint.
+ pub supports_vocabulary: bool,
+}
+
+/// From `handy-computer` on Hugging Face, at a fixed revision. Languages and
+/// hashes as in Handy's catalog.
+pub const MODELS: &[Model] = &[
+ Model {
+ id: PARAKEET,
+ name: "Parakeet Ultra",
+ file: "parakeet-ultra-Q8_0.gguf",
+ url: "https://huggingface.co/handy-computer/parakeet-ultra-gguf/resolve/39eeb55181f0d354fd934f06e92fd8d5037fed8e/parakeet-ultra-Q8_0.gguf",
+ size: 740_363_168,
+ sha256: "007a59761e9258779f189df396b50d12b83bb5b79e66df4b955c230d2f2a0a59",
+ languages: Some(&[
+ "en", "de", "fr", "es", "it", "pt", "ru", "uk", "hr", "sl", "lv", "lt", "et", "fi",
+ "sv", "da", "nl", "pl", "cs", "sk", "hu", "ro", "bg", "el", "mt",
+ ]),
+ supports_vocabulary: false,
+ },
+ Model {
+ id: WHISPER,
+ name: "Whisper Large v3 Turbo",
+ file: "whisper-large-v3-turbo-Q5_K_M.gguf",
+ url: "https://huggingface.co/handy-computer/whisper-large-v3-turbo-gguf/resolve/5eaf945c7978e564bae5b28a5b1639dd93c2bfb1/whisper-large-v3-turbo-Q5_K_M.gguf",
+ size: 619_628_128,
+ sha256: "977b5db4e004349dffd1ab9caa10ba5aaba3fc3edd3ba72cadb84328a3203e36",
+ languages: None,
+ supports_vocabulary: true,
+ },
+];
+
+pub fn find(id: &str) -> Option<&'static Model> {
+ MODELS.iter().find(|m| m.id == id)
+}
+
+fn parakeet() -> &'static Model {
+ &MODELS[0]
+}
+
+fn whisper() -> &'static Model {
+ &MODELS[1]
+}
+
+/// The model these settings use: the one picked, else the recommended one.
+pub fn chosen(settings: &Settings) -> &'static Model {
+ settings
+ .models
+ .get(ID)
+ .and_then(|id| find(id))
+ .unwrap_or_else(|| recommended(settings))
+}
+
+/// Parakeet Ultra, the more accurate, when it knows the language people
+/// speak; Whisper otherwise.
+pub fn recommended(settings: &Settings) -> &'static Model {
+ recommended_for(&spoken_language(settings, sys_locale::get_locale()))
+}
+
+fn recommended_for(language: &str) -> &'static Model {
+ let parakeet = parakeet();
+ let known = parakeet
+ .languages
+ .is_some_and(|languages| languages.contains(&language));
+ // Nothing to go by: most likely a European language, Parakeet's.
+ if known || language.is_empty() {
+ parakeet
+ } else {
+ whisper()
+ }
+}
+
+/// The language people are expected to speak: the one set for dictation,
+/// else the interface's, else the system's (which the interface follows).
+fn spoken_language(settings: &Settings, system: Option) -> String {
+ [settings.language.as_str(), settings.ui_language.as_str()]
+ .into_iter()
+ .map(base_language)
+ .find(|code| !code.is_empty() && code != "auto")
+ .or_else(|| system.as_deref().map(base_language))
+ .unwrap_or_default()
+}
+
+/// "pt-BR" → "pt".
+fn base_language(code: &str) -> String {
+ code.trim()
+ .split(['-', '_'])
+ .next()
+ .unwrap_or_default()
+ .to_ascii_lowercase()
+}
+
+/// A model as the window shows it.
+#[derive(Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalModel {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub size_bytes: u64,
+ pub languages: Option<&'static [&'static str]>,
+ pub recommended: bool,
+ pub supports_vocabulary: bool,
+ pub state: ModelState,
+ /// Where it runs, while it is the model loaded: "Metal · Apple M4",
+ /// "Vulkan · ", "CPU".
+ pub backend: Option,
+}
+
+#[derive(Serialize, Clone, Debug, PartialEq)]
+#[serde(tag = "state", rename_all = "camelCase")]
+pub enum ModelState {
+ Missing,
+ Downloading { downloaded: u64, total: u64 },
+ Verifying,
+ Ready,
+ Failed { error: DownloadError },
+}
+
+/// Why a download stopped, in terms the window can explain.
+#[derive(Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct DownloadError {
+ pub kind: DownloadErrorKind,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub detail: Option,
+}
+
+#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum DownloadErrorKind {
+ /// No connection, or it dropped: trying again resumes.
+ Offline,
+ /// The disk is full.
+ Disk,
+ /// What arrived isn't the model; it was thrown away.
+ Checksum,
+ Other,
+}
+
+impl DownloadError {
+ fn new(kind: DownloadErrorKind, detail: Option) -> Self {
+ Self { kind, detail }
+ }
+
+ fn other(detail: impl Into) -> Self {
+ Self::new(DownloadErrorKind::Other, Some(detail.into()))
+ }
+
+ fn offline(error: impl std::fmt::Display) -> Self {
+ log::warn!("Model download interrupted: {error}");
+ Self::new(DownloadErrorKind::Offline, None)
+ }
+
+ /// A full disk says so; any other file error is shown as it is.
+ fn io(error: io::Error) -> Self {
+ let kind = match error.kind() {
+ io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded => DownloadErrorKind::Disk,
+ _ => DownloadErrorKind::Other,
+ };
+ Self::new(kind, Some(error.to_string()))
+ }
+}
+
+/// The compute device that runs (or will run) the model, for Settings and a
+/// report to support.
+#[derive(Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Backend {
+ /// "metal", "vulkan" or "cpu".
+ pub kind: String,
+ /// The GPU's or processor's name, such as "Apple M4".
+ pub device: String,
+}
+
+impl Backend {
+ fn of(device: &transcribe_cpp::Device) -> Self {
+ Self {
+ kind: device.kind.clone(),
+ device: device.description.trim().to_string(),
+ }
+ }
+
+ fn on_gpu(&self) -> bool {
+ self.kind != "cpu" && self.kind != "accel"
+ }
+
+ fn label(&self) -> String {
+ match self.kind.as_str() {
+ "metal" => format!("Metal · {}", self.device),
+ "vulkan" => format!("Vulkan · {}", self.device),
+ _ => "CPU".to_string(),
+ }
+ }
+}
+
+impl std::fmt::Display for Backend {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{} ({})", self.kind, self.device)
+ }
+}
+
+fn lock(mutex: &Mutex) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+// ---------------------------------------------------------------------------
+// Downloads
+
+/// Where a download stands.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Progress {
+ Bytes { downloaded: u64, total: u64 },
+ Verifying,
+}
+
+/// What to fetch and how to know it's right.
+pub(crate) struct Source<'a> {
+ url: &'a str,
+ size: u64,
+ sha256: &'a str,
+}
+
+impl Model {
+ fn source(&self) -> Source<'static> {
+ Source {
+ url: self.url,
+ size: self.size,
+ sha256: self.sha256,
+ }
+ }
+}
+
+fn part_path(dest: &Path) -> PathBuf {
+ let mut name = dest.file_name().unwrap_or_default().to_os_string();
+ name.push(".part");
+ dest.with_file_name(name)
+}
+
+enum Received {
+ Whole,
+ /// The server can't continue where the part stops: start again.
+ FromTheStart,
+}
+
+/// Downloads `source` to `dest`: into `.part`, from where an earlier
+/// try stopped, then checked and renamed. Cancelling is dropping the future:
+/// what came stays in the part for next time.
+async fn fetch(
+ source: &Source<'_>,
+ dest: &Path,
+ progress: &mut (dyn FnMut(Progress) + Send),
+) -> Result<(), DownloadError> {
+ let part = part_path(dest);
+ if let Some(dir) = dest.parent() {
+ fs::create_dir_all(dir).map_err(DownloadError::io)?;
+ }
+ let client = reqwest::Client::builder()
+ .connect_timeout(CONNECT_TIMEOUT)
+ .read_timeout(READ_TIMEOUT)
+ .user_agent(concat!(
+ "Parler/",
+ env!("CARGO_PKG_VERSION"),
+ " (+https://github.com/Synapsr/Parler)"
+ ))
+ .build()
+ .map_err(|e| DownloadError::other(e.to_string()))?;
+
+ // Once more from the start at most, when the server can't resume.
+ for _ in 0..2 {
+ let mut have = fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
+ if have > source.size {
+ remove_if_there(&part);
+ have = 0;
+ }
+ if have < source.size {
+ if let Received::FromTheStart = receive(&client, source, &part, have, progress).await? {
+ remove_if_there(&part);
+ continue;
+ }
+ }
+ progress(Progress::Verifying);
+ let (path, expected) = (part.clone(), source.sha256.to_string());
+ let hash = tauri::async_runtime::spawn_blocking(move || sha256_of(&path))
+ .await
+ .map_err(|e| DownloadError::other(e.to_string()))?
+ .map_err(DownloadError::io)?;
+ if hash != expected {
+ log::warn!("Downloaded model has SHA-256 {hash}, expected {expected}");
+ remove_if_there(&part);
+ return Err(DownloadError::new(DownloadErrorKind::Checksum, None));
+ }
+ fs::rename(&part, dest).map_err(DownloadError::io)?;
+ return Ok(());
+ }
+ Err(DownloadError::other(
+ "the server could not resume the download",
+ ))
+}
+
+/// One request: the rest of the file after the `have` bytes already in the
+/// part, appended to it.
+async fn receive(
+ client: &reqwest::Client,
+ source: &Source<'_>,
+ part: &Path,
+ have: u64,
+ progress: &mut (dyn FnMut(Progress) + Send),
+) -> Result {
+ let mut request = client.get(source.url);
+ if have > 0 {
+ log::info!("Resuming the model download at {} MB", have / 1_000_000);
+ request = request.header(reqwest::header::RANGE, format!("bytes={have}-"));
+ }
+ let mut response = request.send().await.map_err(DownloadError::offline)?;
+ let status = response.status();
+ let mut have = have;
+ if have > 0 {
+ match status {
+ reqwest::StatusCode::PARTIAL_CONTENT => {
+ let start = response
+ .headers()
+ .get(reqwest::header::CONTENT_RANGE)
+ .and_then(|v| v.to_str().ok())
+ .and_then(content_range_start);
+ if start != Some(have) {
+ log::warn!("The server resumed at {start:?}, not {have}: starting over");
+ return Ok(Received::FromTheStart);
+ }
+ }
+ reqwest::StatusCode::RANGE_NOT_SATISFIABLE => return Ok(Received::FromTheStart),
+ // The whole file again: the Range was ignored.
+ status if status.is_success() => {
+ log::info!("The server sends the whole model again");
+ have = 0;
+ }
+ _ => {}
+ }
+ }
+ if !status.is_success() {
+ log::warn!("Model download refused: HTTP {status}");
+ return Err(DownloadError::other(format!("HTTP {}", status.as_u16())));
+ }
+
+ let mut options = fs::OpenOptions::new();
+ if have > 0 {
+ options.append(true);
+ } else {
+ options.write(true).create(true).truncate(true);
+ }
+ let mut file = options.open(part).map_err(DownloadError::io)?;
+ progress(Progress::Bytes {
+ downloaded: have,
+ total: source.size,
+ });
+ while let Some(chunk) = response.chunk().await.map_err(DownloadError::offline)? {
+ have += chunk.len() as u64;
+ if have > source.size {
+ drop(file);
+ remove_if_there(part);
+ return Err(DownloadError::other("the file is larger than expected"));
+ }
+ file.write_all(&chunk).map_err(DownloadError::io)?;
+ progress(Progress::Bytes {
+ downloaded: have,
+ total: source.size,
+ });
+ }
+ file.sync_all().map_err(DownloadError::io)?;
+ if have < source.size {
+ return Err(DownloadError::offline("the connection closed early"));
+ }
+ Ok(Received::Whole)
+}
+
+/// `bytes 100-199/200` → 100.
+fn content_range_start(value: &str) -> Option {
+ value
+ .trim()
+ .strip_prefix("bytes")?
+ .trim_start()
+ .split('-')
+ .next()?
+ .trim()
+ .parse()
+ .ok()
+}
+
+fn sha256_of(path: &Path) -> io::Result {
+ let mut file = fs::File::open(path)?;
+ let mut hasher = Sha256::new();
+ let mut buffer = vec![0u8; 1 << 20];
+ loop {
+ let n = file.read(&mut buffer)?;
+ if n == 0 {
+ break;
+ }
+ hasher.update(&buffer[..n]);
+ }
+ Ok(format!("{:x}", hasher.finalize()))
+}
+
+fn remove_if_there(path: &Path) {
+ match fs::remove_file(path) {
+ Err(e) if e.kind() != io::ErrorKind::NotFound => {
+ log::warn!("Could not delete {}: {e}", path.display())
+ }
+ _ => {}
+ }
+}
+
+/// A model under its own name, at its size: downloaded and verified.
+fn on_disk(dir: &Path, model: &Model) -> bool {
+ fs::metadata(dir.join(model.file)).is_ok_and(|m| m.len() == model.size)
+}
+
+// ---------------------------------------------------------------------------
+// The engine
+
+/// Whether this launch may use the GPU, decided once from the marker files.
+struct Gpu {
+ /// Where the markers go; `None` in tests, which write none.
+ dir: Option,
+ allowed: AtomicBool,
+}
+
+impl Gpu {
+ /// A marker left by the last run means the GPU took Parler down: off
+ /// for this version (a newer one may have the fix).
+ fn decide(dir: PathBuf) -> Self {
+ let version = env!("CARGO_PKG_VERSION");
+ let running = dir.join(GPU_RUNNING);
+ let off = dir.join(GPU_OFF);
+ if running.exists() {
+ log::error!("The GPU stopped Parler during a transcription: using the CPU from now on");
+ remove_if_there(&running);
+ if let Err(e) = fs::write(&off, version) {
+ log::warn!("Could not remember to keep off the GPU: {e}");
+ }
+ }
+ let allowed = match fs::read_to_string(&off) {
+ Ok(off_for) if off_for.trim() == version => false,
+ Ok(_) => {
+ log::info!("Trying the GPU again with this version");
+ remove_if_there(&off);
+ true
+ }
+ Err(_) => true,
+ };
+ if !allowed {
+ log::info!("The GPU is off for transcription (it crashed before)");
+ }
+ Self {
+ dir: Some(dir),
+ allowed: AtomicBool::new(allowed),
+ }
+ }
+
+ fn allowed(&self) -> bool {
+ self.allowed.load(Ordering::Relaxed)
+ }
+
+ /// Runs `f`, with the marker on disk meanwhile when the GPU is involved.
+ fn guard(&self, on_gpu: bool, f: impl FnOnce() -> T) -> T {
+ let marker = self
+ .dir
+ .as_ref()
+ .filter(|_| on_gpu)
+ .map(|d| d.join(GPU_RUNNING));
+ if let Some(marker) = &marker {
+ let _ = fs::write(marker, b"");
+ }
+ let result = f();
+ if let Some(marker) = &marker {
+ remove_if_there(marker);
+ }
+ result
+ }
+}
+
+/// Registers the compute backends, once per process and before anything
+/// else touches them (a dynamic build loads its modules here). With the GPU
+/// off, its driver is never even loaded.
+fn init_backends(gpu: &Gpu) -> Result<(), String> {
+ static INIT: OnceLock> = OnceLock::new();
+ INIT.get_or_init(|| {
+ transcribe_cpp::init_logging();
+ let result = if gpu.allowed() {
+ gpu.guard(true, transcribe_cpp::init_backends_default)
+ } else {
+ transcribe_cpp::init_backends_with(
+ None::<&Path>,
+ transcribe_cpp::BackendMask::for_backend(Compute::Cpu),
+ )
+ };
+ match &result {
+ Ok(()) => {
+ for device in transcribe_cpp::devices() {
+ log::info!(
+ "Compute device: {} ({}, {:?})",
+ device.description,
+ device.kind,
+ device.device_type
+ );
+ }
+ }
+ Err(e) => log::error!("No compute device for transcription: {e}"),
+ }
+ result.map_err(|e| e.to_string())
+ })
+ .clone()
+}
+
+/// The device a load would pick: the first GPU, else the CPU.
+fn expected_backend(gpu: &Gpu) -> Option {
+ let devices = transcribe_cpp::devices();
+ let is_gpu =
+ |d: &&transcribe_cpp::Device| matches!(d.device_type, DeviceType::Gpu | DeviceType::Igpu);
+ let pick = if gpu.allowed() {
+ devices.iter().find(is_gpu)
+ } else {
+ None
+ };
+ pick.or_else(|| devices.iter().find(|d| d.device_type == DeviceType::Cpu))
+ .map(Backend::of)
+}
+
+struct Loaded {
+ id: &'static str,
+ path: PathBuf,
+ session: Session,
+ backend: Backend,
+ /// The languages it takes as a hint; empty for any.
+ languages: Vec,
+ vocabulary: bool,
+}
+
+/// What one transcription needs besides the audio.
+pub(crate) struct Job {
+ pub model: &'static Model,
+ pub path: PathBuf,
+ /// ISO 639-1, or `None` to let the model tell.
+ pub language: Option,
+ pub vocabulary: Vec,
+}
+
+struct Engine {
+ loaded: Option,
+ last_used: Instant,
+}
+
+fn failed(detail: impl std::fmt::Display) -> TranscribeError {
+ TranscribeError::LocalFailed {
+ provider: LABEL.to_string(),
+ detail: detail.to_string(),
+ }
+}
+
+fn missing() -> TranscribeError {
+ TranscribeError::ModelMissing {
+ provider: LABEL.to_string(),
+ }
+}
+
+fn engine_error(error: transcribe_cpp::Error) -> TranscribeError {
+ match error {
+ transcribe_cpp::Error::ModelFileNotFound(_) => missing(),
+ other => failed(other),
+ }
+}
+
+impl Engine {
+ fn new() -> Self {
+ Self {
+ loaded: None,
+ last_used: Instant::now(),
+ }
+ }
+
+ fn loaded_id(&self) -> Option<&'static str> {
+ self.loaded.as_ref().map(|l| l.id)
+ }
+
+ fn unload(&mut self) {
+ if let Some(loaded) = self.loaded.take() {
+ log::info!("Letting go of the {} model", loaded.id);
+ }
+ }
+
+ /// `model` loaded from `path`, on the GPU when there is one and it
+ /// takes it, else on the CPU.
+ fn ensure(
+ &mut self,
+ gpu: &Gpu,
+ model: &'static Model,
+ path: &Path,
+ ) -> Result<(), TranscribeError> {
+ self.last_used = Instant::now();
+ if self
+ .loaded
+ .as_ref()
+ .is_some_and(|l| l.id == model.id && l.path == path)
+ {
+ return Ok(());
+ }
+ self.unload();
+ if !path.exists() {
+ return Err(missing());
+ }
+ init_backends(gpu).map_err(failed)?;
+ let started = Instant::now();
+ let attempt = if gpu.allowed() {
+ match gpu.guard(true, || load(path, Compute::Auto)) {
+ Ok(loaded) => Ok(loaded),
+ Err(e) => {
+ log::warn!("Could not load the model on the GPU ({e}); using the CPU");
+ gpu.allowed.store(false, Ordering::Relaxed);
+ load(path, Compute::Cpu)
+ }
+ }
+ } else {
+ load(path, Compute::Cpu)
+ };
+ let (handle, session) = attempt.map_err(engine_error)?;
+ let backend = handle.device().map(|d| Backend::of(&d)).unwrap_or(Backend {
+ kind: "cpu".into(),
+ device: String::new(),
+ });
+ let capabilities = handle.capabilities().map_err(engine_error)?;
+ log::info!(
+ "Loaded the {} model on {backend} in {:.1}s",
+ model.id,
+ started.elapsed().as_secs_f64()
+ );
+ self.loaded = Some(Loaded {
+ id: model.id,
+ path: path.to_path_buf(),
+ languages: capabilities.languages,
+ vocabulary: model.supports_vocabulary && handle.supports(Feature::Vocabulary),
+ session,
+ backend,
+ });
+ Ok(())
+ }
+
+ /// Transcribes 16 kHz mono samples. A run that fails on the GPU is run
+ /// again on the CPU.
+ fn transcribe(
+ &mut self,
+ gpu: &Gpu,
+ job: &Job,
+ samples: &[f32],
+ ) -> Result {
+ self.ensure(gpu, job.model, &job.path)?;
+ let loaded = self.loaded.as_mut().expect("just loaded");
+ let on_gpu = loaded.backend.on_gpu();
+ let result = gpu.guard(on_gpu, || run(loaded, job, samples));
+ self.last_used = Instant::now();
+ match result {
+ // The device itself failed, not the request: the CPU may manage.
+ Err(
+ e @ (transcribe_cpp::Error::Backend(_)
+ | transcribe_cpp::Error::OutOfMemory(_)
+ | transcribe_cpp::Error::Other(_)),
+ ) if on_gpu => {
+ log::warn!("Transcription failed on the GPU ({e}); trying the CPU");
+ gpu.allowed.store(false, Ordering::Relaxed);
+ self.unload();
+ self.ensure(gpu, job.model, &job.path)?;
+ let loaded = self.loaded.as_mut().expect("just loaded");
+ run(loaded, job, samples).map_err(engine_error)
+ }
+ result => result.map_err(engine_error),
+ }
+ }
+}
+
+fn load(path: &Path, compute: Compute) -> transcribe_cpp::Result<(transcribe_cpp::Model, Session)> {
+ let options = ModelOptions {
+ backend: compute,
+ ..ModelOptions::default()
+ };
+ let model = transcribe_cpp::Model::load_with(path, &options)?;
+ let session = model.session()?;
+ Ok((model, session))
+}
+
+/// One dictation through the loaded model.
+fn run(loaded: &mut Loaded, job: &Job, samples: &[f32]) -> transcribe_cpp::Result {
+ let language = job
+ .language
+ .clone()
+ .filter(|l| loaded.languages.is_empty() || loaded.languages.contains(l));
+ if language.is_none() && job.language.is_some() {
+ log::info!(
+ "The model takes no {:?} hint: it detects the language",
+ job.language
+ );
+ }
+ let options = RunOptions {
+ language,
+ vocabulary: if loaded.vocabulary {
+ job.vocabulary.clone()
+ } else {
+ Vec::new()
+ },
+ ..RunOptions::default()
+ };
+ // Both models decode long audio themselves (Whisper in 30 s windows,
+ // Parakeet cutting at the pauses its voice detector finds).
+ let transcript = match loaded.session.run(samples, &options) {
+ Ok(transcript) => transcript,
+ // What came before the model stopped or started repeating itself
+ // is kept, rather than losing the dictation.
+ Err(
+ transcribe_cpp::Error::OutputTruncated { partial, message }
+ | transcribe_cpp::Error::OutputRepetition { partial, message },
+ ) if partial.is_some() => {
+ log::warn!("Transcript cut short: {message}");
+ *partial.expect("checked")
+ }
+ Err(e) => return Err(e),
+ };
+ Ok(transcript.text.trim().to_string())
+}
+
+// ---------------------------------------------------------------------------
+// The app's side: one per process, from launch.
+
+struct Downloading {
+ job: u64,
+ progress: Progress,
+ task: Option>,
+}
+
+pub struct Local {
+ app: AppHandle,
+ dir: PathBuf,
+ gpu: Gpu,
+ downloads: Mutex>,
+ /// The last download's failure, shown until the next try.
+ failures: Mutex>,
+ next_job: AtomicU64,
+ engine: Mutex,
+ /// A background load is on its way; another isn't queued behind it.
+ warming: AtomicBool,
+ last_progress: Mutex,
+ /// The model loaded and where, as last seen: read without waiting for
+ /// a transcription to finish.
+ loaded: Mutex
)}
+ {waiting && !done && }
{problem && !done && (
+
+
+ );
+
+ let status;
+ switch (state?.state) {
+ case "downloading":
+ status = {percent(share)};
+ break;
+ case "verifying":
+ status = ;
+ break;
+ case "ready":
+ status = (
+
+
+
+ );
+ break;
+ default:
+ status = ;
+ }
+
+ return (
+