Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
Parakeet reads the 25 languages it covers; Whisper keeps the rest (#196)
Christian Mathiesene52bf05b9b5d
diff --git a/.github/workflows/native-whisper.yml b/.github/workflows/native-whisper.ymlindex 96bdb961..e3a8960e 100644--- a/.github/workflows/native-whisper.yml+++ b/.github/workflows/native-whisper.yml@@ -1,5 +1,5 @@-# whisper-server for Windows (x64) and Linux (x86_64), built by app/scripts/whisper-build.mjs from the pinned whisper.cpp-# and patch that native.sh uses on the Mac. Each build is started by the app's own launcher and transcribes short English+# whisper-server and parakeet-server for Windows (x64) and Linux (x86_64), built by app/scripts/whisper-build.mjs from the+# pinned whisper.cpp and patch that native.sh uses on the Mac. Each build is started by the app's own launcher and transcribes short English# clips (scripts/whisper-smoke.mjs). The realtime factor of each model on the runner's CPU goes in the run summary.# Linux builds on ubuntu-22.04, so it runs on glibc 2.35 and later; it is also run on ubuntu-24.04.# The models are downloaded here only, pinned by commit and sha256; the app never fetches anything for this at run time.@@ -13,10 +13,12 @@ on:- app/scripts/whisper-smoke.mjs- app/native/whisper-server.patch- app/native/whisper-vad-threads.patch+ - app/native/parakeet-server/**- app/src/main/asr/server.ts- app/src/main/asr/speedCheck.ts- app/src/main/asr/transcribe.ts- app/scripts/speed-check-smoke.mjs+ - app/src/main/asr/parakeet.ts- app/resources/speed/**- packages/picker/src/asr.ts- app/src/shared/platform.ts@@ -29,6 +31,8 @@ env:VULKAN_SDK_SHA256_WINDOWS: bcf2d75aa9556889ab974858666e20b3655b6055a0db704ccb47279ff33b5bfe# ggerganov/whisper.cpp on Hugging Face at the commit the catalog usesMODELS_URL: https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1+ # ggml-org/parakeet-GGUF at the commit the catalog uses+ PARAKEET_URL: https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079defaults:run:@@ -76,7 +80,7 @@ jobs:echo "$RUNNER_TEMP/vulkansdk/$v/x86_64/bin" >> "$GITHUB_PATH"fi- - name: Build whisper-server+ - name: Build whisper-server and parakeet-serverrun: node app/scripts/whisper-build.mjs- name: List what was builtrun: ls -la app/resources/bin app/resources/vad@@ -92,12 +96,13 @@ jobs:rm deps.txt"$dumpbin" -nologo -headers whisper-server.exe | grep -i 'subsystem'else- for f in whisper-server *.so; do echo "== $f"; readelf -d "$f" | grep -E 'NEEDED|RUNPATH|RPATH'; done | tee deps.txt- ! grep NEEDED deps.txt | grep -vE '\[(libc\.so\.6|libm\.so\.6|libstdc\+\+\.so\.6|libgcc_s\.so\.1|libpthread\.so\.0|libdl\.so\.2|ld-linux-x86-64\.so\.2|libvulkan\.so\.1|libwhisper\.so|libggml\.so|libggml-base\.so)\]'+ for f in whisper-server parakeet-server *.so; do echo "== $f"; readelf -d "$f" | grep -E 'NEEDED|RUNPATH|RPATH'; done | tee deps.txt+ ! grep NEEDED deps.txt | grep -vE '\[(libc\.so\.6|libm\.so\.6|libstdc\+\+\.so\.6|libgcc_s\.so\.1|libpthread\.so\.0|libdl\.so\.2|ld-linux-x86-64\.so\.2|libvulkan\.so\.1|libwhisper\.so|libparakeet\.so|libggml\.so|libggml-base\.so)\]'grep -q 'RUNPATH.*\$ORIGIN' <(readelf -d whisper-server)+ grep -q 'RUNPATH.*\$ORIGIN' <(readelf -d parakeet-server)rm deps.txt# the newest glibc any file asks for: 2.35 at most (Ubuntu 22.04)- newest=$(for f in whisper-server *.so; do objdump -T "$f"; done | grep -o 'GLIBC_[0-9.]*' | sort -uV | tail -1)+ newest=$(for f in whisper-server parakeet-server *.so; do objdump -T "$f"; done | grep -o 'GLIBC_[0-9.]*' | sort -uV | tail -1)echo "newest glibc symbol: $newest"[ "$(printf '%s\nGLIBC_2.35\n' "$newest" | sort -V | tail -1)" = GLIBC_2.35 ]fi@@ -114,7 +119,7 @@ jobs:uses: actions/cache@v4with:path: ${{ runner.temp }}/models- key: whisper-models-tiny.en-small-q5_1-turbo-q5_0-v1+ key: whisper-models-tiny.en-base-q5_1-small-q5_1-turbo-q5_0-parakeet-v3-q8_0-v1- name: Modelsrun: |mkdir -p "$RUNNER_TEMP/models" && cd "$RUNNER_TEMP/models"@@ -122,6 +127,8 @@ jobs:get ggml-tiny.en.bin 921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1fget ggml-small-q5_1.bin ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bbget ggml-large-v3-turbo-q5_0.bin 394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2+ get ggml-base-q5_1.bin 422f1ae452ade6f30a004d7e5c6a43195e4433bc370bf23fac9cc591f01a8898+ MODELS_URL=$PARAKEET_URL get ggml-parakeet-tdt-0.6b-v3-q8_0.bin 4d64e9e96c2792186d072fde0034df0ad670cf680a2f53069052ead827fd600e- name: Summary headerrun: |@@ -168,11 +175,31 @@ jobs:node app/scripts/whisper-smoke.mjs --bin app/resources/bin/whisper-server --model "$RUNNER_TEMP/models/ggml-tiny.en.bin" \--vad app/resources/vad/ggml-silero-v6.2.0.bin --wav app/native/.whisper-build/samples/jfk.wav --expect country,ask --runs 1 --label tiny.en-lavapipe- - name: Realtime factor, Whisper small and large-v3-turbo on the CPU+ # parakeet-server the way the app starts it here: on the processor alone+ - name: Parakeet transcribes English, survives silence, under a folder named José+ run: |+ exe=app/resources/bin/parakeet-server; [ "$RUNNER_OS" = Windows ] && exe=$exe.exe+ node app/scripts/whisper-smoke.mjs --engine parakeet --cpu --bin "$exe" --model "$RUNNER_TEMP/models/ggml-parakeet-tdt-0.6b-v3-q8_0.bin" \+ --wav app/native/.whisper-build/samples/jfk.wav,app/e2e/fixtures/meeting-me.wav,app/e2e/fixtures/meeting-them.wav,app/resources/speed/clip.wav \+ --expect country,ask --silence --runs 3 --label parakeet-v3-q8_0+ node app/scripts/whisper-smoke.mjs --engine parakeet --cpu --bin "$exe" --model "$RUNNER_TEMP/models/ggml-parakeet-tdt-0.6b-v3-q8_0.bin" \+ --wav app/native/.whisper-build/samples/jfk.wav --expect country,ask --silence --runs 1 --unicode-dir --label parakeet-unicode++ # setup's speed check with Parakeet first, as on a new install: timed on the bundled clip by the whisper models' rules+ - name: Setup speed check times Parakeet+ run: |+ exe=app/resources/bin/whisper-server; pk=app/resources/bin/parakeet-server+ [ "$RUNNER_OS" = Windows ] && exe=$exe.exe && pk=$pk.exe+ node app/scripts/speed-check-smoke.mjs --bin "$exe" --vad app/resources/vad/ggml-silero-v6.2.0.bin \+ --parakeet-bin "$pk" --parakeet "$RUNNER_TEMP/models/ggml-parakeet-tdt-0.6b-v3-q8_0.bin" \+ --model "$RUNNER_TEMP/models/ggml-small-q5_1.bin,$RUNNER_TEMP/models/ggml-base-q5_1.bin" --store "$RUNNER_TEMP/speech-speed-parakeet.json"+ grep -q '"parakeet"' "$RUNNER_TEMP/speech-speed-parakeet.json"++ - name: Realtime factor, Whisper base, small and large-v3-turbo on the CPUrun: |exe=app/resources/bin/whisper-server; [ "$RUNNER_OS" = Windows ] && exe=$exe.exe- clips=app/native/.whisper-build/samples/jfk.wav,app/e2e/fixtures/meeting-me.wav,app/e2e/fixtures/meeting-them.wav- for m in small-q5_1 large-v3-turbo-q5_0; do+ clips=app/native/.whisper-build/samples/jfk.wav,app/e2e/fixtures/meeting-me.wav,app/e2e/fixtures/meeting-them.wav,app/resources/speed/clip.wav+ for m in base-q5_1 small-q5_1 large-v3-turbo-q5_0; donode app/scripts/whisper-smoke.mjs --bin "$exe" --model "$RUNNER_TEMP/models/ggml-$m.bin" \--vad app/resources/vad/ggml-silero-v6.2.0.bin --wav "$clips" --expect country --runs 1 --label "$m"donediff --git a/.github/workflows/preview.yml b/.github/workflows/preview.ymlindex e3049fd7..db8a89b3 100644--- a/.github/workflows/preview.yml+++ b/.github/workflows/preview.yml@@ -1,6 +1,6 @@# By hand only (Actions → Preview builds → Run workflow): unsigned Windows and Linux installers, attached to the run# for testers. Nothing is published, and the Mac release (release.yml) is not touched.-# The installers carry the recorder, the system and AI apps helpers (Rust) and whisper-server with its backends, built+# The installers carry the recorder, the system and AI apps helpers (Rust) and whisper-server and parakeet-server with their backends, built# here by scripts/native.mjs. Each one is installed on the runner and its helpers are run from the install folder.# Linux builds on Ubuntu 22.04, so the AppImage's helpers run on glibc 2.35 and later.# release.yml calls this same workflow for a release's Windows and Linux files (installer, latest*.yml, blockmap, and@@ -26,6 +26,8 @@ env:VULKAN_SDK_SHA256_LINUX: 3bf0f762afb6c79bc6a9d9fb5998745ccff928800a29619b501ed9de7fd9789bVULKAN_SDK_SHA256_WINDOWS: bcf2d75aa9556889ab974858666e20b3655b6055a0db704ccb47279ff33b5bfeMODELS_URL: https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1+ # ggml-org/parakeet-GGUF at the commit the catalog uses+ PARAKEET_URL: https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079CARGO_TERM_COLOR: alwaysjobs:@@ -210,6 +212,17 @@ jobs:mkdir -p "$RUNNER_TEMP/models" && cd "$RUNNER_TEMP/models"curl -sSfL --retry 3 -o ggml-tiny.en.bin "$MODELS_URL/ggml-tiny.en.bin"echo "921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f ggml-tiny.en.bin" | sha256sum -c -+ - name: Parakeet model for the check (cached)+ uses: actions/cache@v4+ with:+ path: ${{ runner.temp }}/parakeet+ key: parakeet-tdt-0.6b-v3-q8_0-35156454+ - name: Parakeet model for the check+ run: |+ mkdir -p "$RUNNER_TEMP/parakeet" && cd "$RUNNER_TEMP/parakeet"+ f=ggml-parakeet-tdt-0.6b-v3-q8_0.bin; sum=4d64e9e96c2792186d072fde0034df0ad670cf680a2f53069052ead827fd600e+ echo "$sum $f" | sha256sum -c - >/dev/null 2>&1 || curl -sSfL --retry 3 -o "$f" "$PARAKEET_URL/$f"+ echo "$sum $f" | sha256sum -c -- name: The installed helpers runtimeout-minutes: 5run: |@@ -222,3 +235,11 @@ jobs:exe="$INSTALLED/bin/whisper-server"; [ "$RUNNER_OS" = Windows ] && exe=$exe.exenode app/scripts/whisper-smoke.mjs --bin "$exe" --model "$RUNNER_TEMP/models/ggml-tiny.en.bin" \--vad "$INSTALLED/vad/ggml-silero-v6.2.0.bin" --wav app/native/.whisper-build/samples/jfk.wav --expect country,ask --runs 1 --label installed+ # the way the app starts it on Windows and Linux: on the processor alone+ - name: The installed parakeet-server transcribes+ if: always() && env.INSTALLED != ''+ timeout-minutes: 10+ run: |+ exe="$INSTALLED/bin/parakeet-server"; [ "$RUNNER_OS" = Windows ] && exe=$exe.exe+ node app/scripts/whisper-smoke.mjs --engine parakeet --cpu --bin "$exe" --model "$RUNNER_TEMP/parakeet/ggml-parakeet-tdt-0.6b-v3-q8_0.bin" \+ --wav app/native/.whisper-build/samples/jfk.wav --expect country,ask --silence --runs 1 --label installed-parakeetdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4a0f1c95..cc3f38bd 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -8,7 +8,7 @@# from updates; latest*.yml must never name them.# Running it by hand (Actions → Release → Run workflow) only builds: the files are attached to the run, nothing is published.# Windows and Linux are built by preview.yml, with the same checks (helpers run from the install folder, whisper-server-# transcribes); the Mac steps are below.+# and parakeet-server transcribe); the Mac steps are below.name: Releaseon:@@ -124,6 +124,27 @@ jobs:node app/scripts/asar-check.mjs app/dist/mac-arm64/Yogurt.app/Contents/Resources/app.asarpnpm -C app exec electron scripts/engine-smoke.cjs dist/mac-arm64/Yogurt.app/Contents/Resources/app.asarif [ "$SIGNED" = true ]; then codesign --verify --deep --strict app/dist/mac-arm64/Yogurt.app; fi+ # the speech programs as packaged (and signed): whisper-server is there, and parakeet-server reads a clip with the+ # model the catalog pins, the way a Mac runs it (Metal). A runner whose graphics can't do that says so and is+ # checked on the processor instead; every Mac also tries it on its own graphics before using it (setup.ts)+ - name: Parakeet model for the check (cached)+ uses: actions/cache@v4+ with:+ path: ${{ runner.temp }}/parakeet+ key: parakeet-tdt-0.6b-v3-q8_0-35156454+ - name: The packaged parakeet-server transcribes+ timeout-minutes: 15+ run: |+ bin=app/dist/mac-arm64/Yogurt.app/Contents/Resources/bin+ test -x "$bin/whisper-server" && test -x "$bin/parakeet-server"+ mkdir -p "$RUNNER_TEMP/parakeet"+ f="$RUNNER_TEMP/parakeet/ggml-parakeet-tdt-0.6b-v3-q8_0.bin"; sum=4d64e9e96c2792186d072fde0034df0ad670cf680a2f53069052ead827fd600e+ [ "$(shasum -a 256 "$f" 2>/dev/null | cut -d' ' -f1)" = "$sum" ] || curl -sSfL --retry 3 -o "$f" https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q8_0.bin+ [ "$(shasum -a 256 "$f" | cut -d' ' -f1)" = "$sum" ]+ smoke() { node app/scripts/whisper-smoke.mjs --engine parakeet "$@" --bin "$bin/parakeet-server" --model "$f" \+ --wav app/native/.whisper-build/samples/jfk.wav --expect country,ask --silence --runs 1; }+ if smoke --label packaged-parakeet-metal; then echo "::notice::the packaged parakeet-server transcribes on this runner's graphics (Metal)"+ else echo "::warning::the packaged parakeet-server did not transcribe on this runner's graphics; checking it on the processor"; smoke --cpu --label packaged-parakeet-cpu; fi# the app inside is notarized by electron-builder; the disk image is checked when downloaded too- name: Notarize the disk imageenv:diff --git a/README.md b/README.mdindex 92fda964..72a866c5 100644--- a/README.md+++ b/README.md@@ -148,7 +148,7 @@ Meeting data stays local; Yogurt goes online for model downloads and update chec<br>-> Yogurt uses Whisper large-v3-turbo on computers that can run it, the same family of models many cloud services use, so English accuracy is close to cloud transcription. Smaller computers get a smaller Whisper model, which is faster but makes more mistakes, especially outside English. You can add names and words to a custom vocabulary so they're spelled right.+> Yogurt uses NVIDIA's Parakeet for English and 24 other European languages, and Whisper for every other language, so accuracy is close to cloud transcription. Computers too slow for Parakeet get a smaller Whisper model, which makes more mistakes, especially outside English. You can add names and words to a custom vocabulary so they're spelled right.</details>@@ -180,7 +180,7 @@ Meeting data stays local; Yogurt goes online for model downloads and update chec<br>-> Transcription uses Whisper through whisper.cpp, with large-v3-turbo or a smaller model depending on your computer. On supported Macs, Apple SpeechAnalyzer supplies live words while Whisper produces the saved transcript. Summaries and answers use a local open-weight model from the Gemma 4, gpt-oss or Qwen3 families, chosen for your hardware and run through llama.cpp. The app uses Electron and needs no account.+> Transcription uses Parakeet TDT 0.6B v3 (NVIDIA, CC BY 4.0) for the 25 languages it covers and Whisper for the rest, both through whisper.cpp; Whisper is large-v3-turbo or a smaller model depending on your computer. On supported Macs, Apple SpeechAnalyzer supplies live words while Parakeet or Whisper produces the saved transcript. Summaries and answers use a local open-weight model from the Gemma 4, gpt-oss or Qwen3 families, chosen for your hardware and run through llama.cpp. The app uses Electron and needs no account.</details>diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 9440cf0b..7a11b162 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -16,5 +16,6 @@ Yogurt doesn't ship any models in this repo or the installers. It downloads them- Gemma 4 (E2B, E4B, 26B A4B), Qwen3 1.7B and gpt-oss (20B, 120B): Apache-2.0.- Whisper (speech to text) and Silero VAD (voice detection): MIT.+- Parakeet TDT 0.6B v3 (speech to text in the 25 languages it covers) by [NVIDIA](https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3): CC BY 4.0. Yogurt downloads converted weights, the GGML q8_0 file from [ggml-org/parakeet-GGUF](https://huggingface.co/ggml-org/parakeet-GGUF), converted from NVIDIA's original and quantized to 8 bits. The credit and licence text are in [app/resources/licenses](app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txt).- EmbeddingGemma 300M: provided under and subject to the [Gemma Terms of Use](https://ai.google.dev/gemma/terms).diff --git a/app/e2e/jargon.spec.ts b/app/e2e/jargon.spec.tsindex 4fb60192..46e946a7 100644--- a/app/e2e/jargon.spec.ts+++ b/app/e2e/jargon.spec.ts@@ -6,8 +6,8 @@ import { join } from 'node:path'const main = join(import.meta.dirname, '../out/main/index.js')-async function launch(userData = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))) {- const app = await electron.launch({ args: [main], env: { ...process.env, YOGURT_FAKE: '1', YOGURT_USER_DATA: userData } })+async function launch(userData = mkdtempSync(join(tmpdir(), 'yogurt-e2e-')), env: Record<string, string> = {}) {+ const app = await electron.launch({ args: [main], env: { ...process.env, YOGURT_FAKE: '1', YOGURT_USER_DATA: userData, ...env } })const page = await app.firstWindow()await expect(page.getByTestId('home')).toBeVisible()return { app, page, userData }@@ -63,8 +63,10 @@ test('personal jargon: added with Enter or the suggestion, removed with × or Ba} finally { await b.app.close() }})+// whisper takes the meeting's words as its prompt; Parakeet takes none (its lines are respelled after), so this one+// runs with whisper reading everything (YOGURT_ASR=whisper)test('personal jargon reaches whisper and the notes', async () => {- const { app, page } = await launch()+ const { app, page } = await launch(undefined, { YOGURT_ASR: 'whisper' })try {await openFromCorner(page, 'settings-open')const input = page.getByTestId('jargon-input')diff --git a/app/e2e/parakeet.spec.ts b/app/e2e/parakeet.spec.tsnew file mode 100644index 00000000..0877218d--- /dev/null+++ b/app/e2e/parakeet.spec.ts@@ -0,0 +1,107 @@+import { _electron as electron, expect, test, type ElectronApplication } from '@playwright/test'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++// Parakeet reads the languages it covers and whisper the rest (stand-ins, YOGURT_FAKE): what a new install downloads,+// who reads a meeting, the kill switch, and an install from before Parakeet moving over.+// @everywhere: the Windows and Linux runners are those computers; a Mac is itself and pretends to be the other two.+const main = join(import.meta.dirname, '../out/main/index.js')+const PARAKEET = 'ggml-parakeet-tdt-0.6b-v3-q8_0.bin', BASE = 'ggml-base-q5_1.bin', TURBO = 'ggml-large-v3-turbo-q5_0.bin'++const platforms = process.platform === 'darwin' ? ['darwin', 'win32', 'linux'] : [process.platform]+async function launch(env: Record<string, string> = {}, profile = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))) {+ const app = await electron.launch({ args: [main], env: { ...process.env, YOGURT_FAKE: '1', YOGURT_USER_DATA: profile, ...env } })+ const page = await app.firstWindow()+ await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })+ return { app, page, profile }+}+const fake = <T>(app: ElectronApplication, fn: string, arg?: unknown): Promise<T> =>+ app.evaluate((_e, [fn, arg]) => (globalThis as unknown as Record<string, Record<string, (a?: unknown) => unknown>>).__fake__[fn as string](arg), [fn, arg] as const) as Promise<T>+type Read = { whisper: string[]; engines: string[]; languages: string[] }+const model = (profile: string, name: string) => join(profile, 'models', 'asr', name)+/** the lines saved for the note on screen */+const lines = (page: import('@playwright/test').Page) => page.evaluate(async () => {+ const id = (await window.yogurt.nav.current()).slice('/note/'.length)+ return (await window.yogurt.transcript.get(id)).map((l: { text: string }) => l.text)+})++const record = async (page: import('@playwright/test').Page) => {+ await page.getByTestId('new-note').click()+ await expect(page.getByTestId('note-state')).toHaveAttribute('data-state', 'recording')+}++for (const platform of platforms) {+test(`@everywhere on ${platform}: a new install gets Parakeet and whisper base, and Parakeet reads an English meeting`, async () => {+ const { app, page, profile } = await launch({ YOGURT_FAKE_PLATFORM: platform })+ try {+ expect(existsSync(model(profile, PARAKEET))).toBe(true)+ expect(existsSync(model(profile, BASE))).toBe(true)+ expect(existsSync(model(profile, TURBO))).toBe(false)+ await record(page)+ await expect.poll(async () => (await lines(page)).length, { timeout: 30_000 }).toBeGreaterThanOrEqual(2)+ const read = await fake<Read>(app, 'prompts')+ expect(new Set(read.engines)).toEqual(new Set(['parakeet']))+ // English only is told as before; Parakeet takes no prompt, so whisper was given none+ expect(new Set(read.languages)).toEqual(new Set(['en']))+ expect(read.whisper).toEqual([])+ await page.getByTestId('note-stop').click()+ } finally { await app.close() }+})++test(`@everywhere on ${platform}: the kill switch (YOGURT_ASR=whisper): whisper reads the meeting, as before Parakeet`, async () => {+ const { app, page, profile } = await launch({ YOGURT_FAKE_PLATFORM: platform, YOGURT_ASR: 'whisper' })+ try {+ expect(existsSync(model(profile, PARAKEET))).toBe(false)+ expect(existsSync(model(profile, TURBO))).toBe(true)+ await record(page)+ await expect.poll(async () => (await lines(page)).length, { timeout: 30_000 }).toBeGreaterThanOrEqual(2)+ const read = await fake<Read>(app, 'prompts')+ expect(new Set(read.engines)).toEqual(new Set(['whisper']))+ expect(read.whisper.length).toBeGreaterThan(0)+ await page.getByTestId('note-stop').click()+ } finally { await app.close() }+})+++test(`@everywhere on ${platform}: a parakeet-server that will not start is no setup error: whisper is picked as before, and reads the meeting`, async () => {+ const { app, page, profile } = await launch({ YOGURT_FAKE_PLATFORM: platform, YOGURT_FAKE_PARAKEET: 'broken' })+ try {+ await expect(page.getByTestId('setup-error')).toHaveCount(0)+ expect(existsSync(model(profile, TURBO))).toBe(true)+ await record(page)+ await expect.poll(async () => (await lines(page)).length, { timeout: 30_000 }).toBeGreaterThanOrEqual(2)+ expect(new Set((await fake<Read>(app, 'prompts')).engines)).toEqual(new Set(['whisper']))+ await page.getByTestId('note-stop').click()+ } finally { await app.close() }+})+}++test('the hidden setting ("asr": "whisper" in settings.json) does the same as the kill switch', async () => {+ const profile = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))+ writeFileSync(join(profile, 'settings.json'), JSON.stringify({ asr: 'whisper' }))+ const { app } = await launch({}, profile)+ try {+ expect(existsSync(model(profile, PARAKEET))).toBe(false)+ expect(existsSync(model(profile, TURBO))).toBe(true)+ expect(JSON.parse(readFileSync(join(profile, 'settings.json'), 'utf8')).asr).toBe('whisper')+ } finally { await app.close() }+})++test('an install from before Parakeet opens on the whisper it has, fetches Parakeet in the background, and uses it from then on', async () => {+ // a profile as an earlier version left it: turbo downloaded and checked+ const profile = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))+ mkdirSync(join(profile, 'models', 'asr'), { recursive: true })+ writeFileSync(model(profile, TURBO), 'fake'); writeFileSync(model(profile, TURBO) + '.ok', 'FAKE')+ const { app, page } = await launch({}, profile)+ try {+ await expect(page.getByTestId('setup-error')).toHaveCount(0)+ await expect.poll(() => existsSync(model(profile, PARAKEET) + '.ok') && existsSync(model(profile, BASE) + '.ok'), { timeout: 30_000 }).toBe(true)+ // the whisper it had stays, for the languages Parakeet doesn't cover+ expect(existsSync(model(profile, TURBO))).toBe(true)+ await record(page)+ await expect.poll(async () => (await fake<Read>(app, 'prompts')).engines.length, { timeout: 30_000 }).toBeGreaterThan(0)+ expect(new Set((await fake<Read>(app, 'prompts')).engines)).toEqual(new Set(['parakeet']))+ await page.getByTestId('note-stop').click()+ } finally { await app.close() }+})diff --git a/app/e2e/speedCheck.spec.ts b/app/e2e/speedCheck.spec.tsindex 704d80ee..fe367193 100644--- a/app/e2e/speedCheck.spec.ts+++ b/app/e2e/speedCheck.spec.ts@@ -9,6 +9,7 @@ const launch = (env: Record<string, string>) => {const profile = mkdtempSync(join(tmpdir(), 'yogurt-e2e-'))return { profile, app: electron.launch({ args: [main], env: { ...process.env, YOGURT_FAKE: '1', YOGURT_USER_DATA: profile, ...env } }) }}+const PARAKEET = 'ggml-parakeet-tdt-0.6b-v3-q8_0.bin'const stored = (profile: string) => JSON.parse(readFileSync(join(profile, 'speech-speed.json'), 'utf8'))for (const platform of ['win32', 'linux']) {@@ -21,30 +22,60 @@ for (const platform of ['win32', 'linux']) {const page = await app.firstWindow()await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })await expect(page.getByTestId('setup-error')).toHaveCount(0)- expect(stored(profile)).toMatchObject({ afterMeeting: true, rtf: { 'whisper-large-v3-turbo-q5_0': 2, 'whisper-small-q5_1': 2, 'whisper-base-q5_1': 2, 'whisper-tiny-q5_1': 2 } })+ // Parakeet is timed first, by the same rules, and is too slow here too+ expect(stored(profile)).toMatchObject({ afterMeeting: true, parakeet: 2, rtf: { 'whisper-large-v3-turbo-q5_0': 2, 'whisper-small-q5_1': 2, 'whisper-base-q5_1': 2, 'whisper-tiny-q5_1': 2 } })+ expect(existsSync(join(profile, 'models', 'asr', PARAKEET))).toBe(false)expect(stored(profile).model).toEqual(expect.any(String))} finally { await app.close() }})- test(`@everywhere on ${platform}: the best speech model that keeps up is kept, and recording is ready`, async () => {- const { app: launching, profile } = launch({ YOGURT_FAKE_PLATFORM: platform, YOGURT_FAKE_RTF: 'whisper-large-v3-turbo-q5_0=0.9,whisper-small-q5_1=1.4' })+ test(`@everywhere on ${platform}: where Parakeet does not keep up, the best whisper that does is kept, and recording is ready`, async () => {+ const { app: launching, profile } = launch({ YOGURT_FAKE_PLATFORM: platform, YOGURT_FAKE_RTF: 'parakeet-tdt-0.6b-v3-q8_0=0.8,whisper-large-v3-turbo-q5_0=0.9,whisper-small-q5_1=1.4' })const app = await launchingtry {const page = await app.firstWindow()await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })// small may lag up to 1.25 times the clip (#107); slower than that, base is kept- expect(stored(profile)).toMatchObject({ model: 'whisper-base-q5_1', rtf: { 'whisper-large-v3-turbo-q5_0': 0.9, 'whisper-small-q5_1': 1.4, 'whisper-base-q5_1': 0.1 } })+ expect(stored(profile)).toMatchObject({ model: 'whisper-base-q5_1', parakeet: 0.8, rtf: { 'whisper-large-v3-turbo-q5_0': 0.9, 'whisper-small-q5_1': 1.4, 'whisper-base-q5_1': 0.1 } })+ } finally { await app.close() }+ })++ test(`@everywhere on ${platform}: Parakeet keeps up, so it is kept with whisper base beside it, and no other whisper is downloaded or timed`, async () => {+ const { app: launching, profile } = launch({ YOGURT_FAKE_PLATFORM: platform, YOGURT_FAKE_RTF: 'parakeet-tdt-0.6b-v3-q8_0=0.2,whisper-small-q5_1=1.4' })+ const app = await launching+ try {+ const page = await app.firstWindow()+ await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })+ await expect(page.getByTestId('setup-error')).toHaveCount(0)+ expect(stored(profile)).toMatchObject({ parakeet: 0.2, whisperTimed: false, rtf: {} })+ expect(existsSync(join(profile, 'models', 'asr', PARAKEET))).toBe(true)+ expect(existsSync(join(profile, 'models', 'asr', 'ggml-base-q5_1.bin'))).toBe(true)+ expect(existsSync(join(profile, 'models', 'asr', 'ggml-small-q5_1.bin'))).toBe(false)} finally { await app.close() }})}-test('@everywhere a Mac never times its speech model: turbo as always, even when every time would be too slow', async () => {+test('@everywhere a Mac never times its speech models: Parakeet and whisper base, even when every time would be too slow', async () => {const { app: launching, profile } = launch({ YOGURT_FAKE_PLATFORM: 'darwin', YOGURT_FAKE_RTF: '2' })const app = await launchingtry {const page = await app.firstWindow()await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })expect(existsSync(join(profile, 'speech-speed.json'))).toBe(false)+ expect(existsSync(join(profile, 'models', 'asr', PARAKEET))).toBe(true)+ expect(existsSync(join(profile, 'models', 'asr', 'ggml-base-q5_1.bin'))).toBe(true)+ // the bigger whisper comes only once a language Parakeet doesn't cover is wanted+ expect(existsSync(join(profile, 'models', 'asr', 'ggml-large-v3-turbo-q5_0.bin'))).toBe(false)+ } finally { await app.close() }+})++test('@everywhere the kill switch (YOGURT_ASR=whisper): a Mac gets turbo as before, and nothing of Parakeet', async () => {+ const { app: launching, profile } = launch({ YOGURT_FAKE_PLATFORM: 'darwin', YOGURT_ASR: 'whisper' })+ const app = await launching+ try {+ const page = await app.firstWindow()+ await expect(page.getByTestId('home')).toBeVisible({ timeout: 15_000 })expect(existsSync(join(profile, 'models', 'asr', 'ggml-large-v3-turbo-q5_0.bin'))).toBe(true)+ expect(existsSync(join(profile, 'models', 'asr', PARAKEET))).toBe(false)} finally { await app.close() }})diff --git a/app/electron-builder.yml b/app/electron-builder.ymlindex 7fb86321..5221d908 100644--- a/app/electron-builder.yml+++ b/app/electron-builder.yml@@ -21,7 +21,7 @@ files:- package.jsonextraResources:# the helpers (scripts/native.mjs): on a Mac native.sh's calendar, call detection and names in calls, recording,- # speech to text; on Windows and Linux the Rust recorder, system helper and AI apps relay, and whisper-server+ # speech to text; on Windows and Linux the Rust recorder, system helper and AI apps relay, and whisper-server and parakeet-server- from: resources/binto: bin# Silero VAD for whisper-server (native.sh or whisper-build.mjs fetch it, checked against its sha256)@@ -29,10 +29,13 @@ extraResources:to: vad# the Mac's menu bar icon (tray.ts reads it from Resources; @2x is picked up next to it)- { from: resources, to: ., filter: ["tray.png", "[email protected]", "tray-titled.png", "[email protected]"] }- # licenses of things bundled or downloaded: fonts, whisper.cpp, Silero VAD, libopus, the native recorders' crates,+ # licenses of things bundled or downloaded: fonts, whisper.cpp, Silero VAD, Parakeet (CC BY 4.0, with its credit), libopus, the native recorders' crates,# whisper-server's headers, animate-ui, the CUDA runtime and the echo canceller (webrtcaec3.js)- from: resources/licensesto: licenses+ # the speed check's clip (src/main/asr/speedCheck.ts): Windows and Linux time their speech models on it, and every+ # system tries Parakeet on it before using it+ - { from: resources/speed, to: speed }# the Mac's About window shows Resources/Credits.html under the version, with its link- from: resources/about/Credits.htmlto: Credits.html@@ -102,8 +105,6 @@ win:# added to the extra resources above (unlike files, these merge): the word list for lowercase respelling (scripts/native.mjs; a Mac has its own)extraResources:- { from: resources/dict, to: dict }- # the speed check's clip (src/main/asr/speedCheck.ts): a Mac never times its speech model- - { from: resources/speed, to: speed }# the tray's colour icons (tray.ts; @2x next to them), a Mac uses its template tray.png- { from: resources, to: ., filter: ["tray-color*.png", "tray-recording*.png"] }artifactName: Yogurt-windows-${arch}.${ext}@@ -137,8 +138,6 @@ linux:# added to the extra resources above (unlike files, these merge): the word list for lowercase respelling (scripts/native.mjs; a Mac has its own)extraResources:- { from: resources/dict, to: dict }- # the speed check's clip (src/main/asr/speedCheck.ts): a Mac never times its speech model- - { from: resources/speed, to: speed }# the tray's colour icons (tray.ts; @2x next to them), a Mac uses its template tray.png- { from: resources, to: ., filter: ["tray-color*.png", "tray-recording*.png"] }artifactName: Yogurt-linux-${arch}.${ext}diff --git a/app/native/parakeet-server/CMakeLists.txt b/app/native/parakeet-server/CMakeLists.txtnew file mode 100644index 00000000..08fe8b69--- /dev/null+++ b/app/native/parakeet-server/CMakeLists.txt@@ -0,0 +1,13 @@+set(CMAKE_CXX_STANDARD 17)+set(CMAKE_CXX_STANDARD_REQUIRED ON)++set(TARGET parakeet-server)+add_executable(${TARGET} server.cpp ../server/httplib.h)++include(DefaultTargetOptions)++target_link_libraries(${TARGET} PRIVATE common json_cpp parakeet ${CMAKE_THREAD_LIBS_INIT})++if (WIN32)+ target_link_libraries(${TARGET} PRIVATE ws2_32)+endif()diff --git a/app/native/parakeet-server/server.cpp b/app/native/parakeet-server/server.cppnew file mode 100644index 00000000..4a13ec9a--- /dev/null+++ b/app/native/parakeet-server/server.cpp@@ -0,0 +1,109 @@+// parakeet-server: Parakeet TDT through whisper.cpp's own parakeet.h, kept loaded, behind the same small HTTP surface+// Yogurt uses on whisper-server (GET / answers when the model is in, POST /inference takes a 16 kHz WAV as "file").+// Built by scripts/native.sh and scripts/whisper-build.mjs inside the pinned whisper.cpp, as examples/parakeet-server.+//+// parakeet-server -m MODEL --host 127.0.0.1 --port N -t THREADS [-ng]+//+// The answer is the model's tokens with their times and log-probabilities, as JSON:+// {"duration": seconds, "text": "...", "tokens": [{"text": "▁Hello", "start": 0.08, "end": 0.24, "logprob": -0.01}, ...]}+// Words, sentences and the "is this a language Parakeet doesn't know" check are made from them in src/main/asr/parakeet.ts.+#include "common.h"+#include "common-whisper.h"+#include "parakeet.h"+#include "ggml-backend.h"+#include "../server/httplib.h"+#include "json.hpp"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <mutex>+#include <string>+#include <vector>++using json = nlohmann::ordered_json;++int main(int argc, char ** argv) {+ std::string model, host = "127.0.0.1";+ int port = 8080, threads = 4;+ bool gpu = true;+ for (int i = 1; i < argc; i++) {+ const std::string a = argv[i];+ const bool more = i + 1 < argc;+ if ((a == "-m" || a == "--model") && more) model = argv[++i];+ else if (a == "--host" && more) host = argv[++i];+ else if (a == "--port" && more) port = std::atoi(argv[++i]);+ else if ((a == "-t" || a == "--threads") && more) threads = std::atoi(argv[++i]);+ else if (a == "-ng" || a == "--no-gpu") gpu = false;+ else if (a == "-h" || a == "--help") { ggml_backend_load_all(); fprintf(stderr, "usage: %s -m MODEL [--host H] [--port N] [-t THREADS] [-ng]\n", argv[0]); return 0; }+ else { fprintf(stderr, "unknown argument: %s\n", a.c_str()); return 2; }+ }+ if (model.empty()) { fprintf(stderr, "a model is needed (-m)\n"); return 2; }+ if (threads < 1) threads = 1;++ ggml_backend_load_all();++ struct parakeet_context_params cp = parakeet_context_default_params();+ cp.use_gpu = gpu;+ struct parakeet_context * ctx = parakeet_init_from_file_with_params(model.c_str(), cp);+ if (!ctx) { fprintf(stderr, "parakeet-server: could not load the model '%s'\n", model.c_str()); return 1; }++ std::mutex busy;+ httplib::Server svr;+ svr.set_default_headers({{"Server", "parakeet-server"}});++ svr.Get("/", [](const httplib::Request &, httplib::Response & res) { res.set_content("ok", "text/plain"); });++ svr.Post("/inference", [&](const httplib::Request & req, httplib::Response & res) {+ if (!req.has_file("file")) { res.status = 400; res.set_content("{\"error\":\"no 'file' field in the request\"}", "application/json"); return; }+ const auto file = req.get_file_value("file");+ std::vector<float> pcm;+ std::vector<std::vector<float>> pcms;+ if (!read_audio_data(file.content.data(), file.content.size(), pcm, pcms, false)) {+ res.status = 400; res.set_content("{\"error\":\"failed to read audio data\"}", "application/json"); return;+ }+ json out;+ out["duration"] = pcm.size() / (double) PARAKEET_SAMPLE_RATE;+ std::string text;+ json tokens = json::array();+ // under a tenth of a second there is nothing to read (and nothing for the mel spectrogram to work on)+ if (pcm.size() >= PARAKEET_SAMPLE_RATE / 10) {+ std::lock_guard<std::mutex> lock(busy);+ struct parakeet_full_params fp = parakeet_full_default_params(PARAKEET_SAMPLING_GREEDY);+ fp.n_threads = threads;+ fp.no_context = true;+ const int ret = parakeet_full(ctx, fp, pcm.data(), (int) pcm.size());+ if (ret != 0) {+ res.status = 500; res.set_content("{\"error\":\"failed to process audio\"}", "application/json"); return;+ }+ for (int i = 0; i < parakeet_full_n_segments(ctx); i++) {+ text += parakeet_full_get_segment_text(ctx, i);+ for (int j = 0; j < parakeet_full_n_tokens(ctx, i); j++) {+ const parakeet_token_data d = parakeet_full_get_token_data(ctx, i, j);+ const char * s = parakeet_token_to_str(ctx, d.id);+ // times are in mel frames (10 ms)+ tokens.push_back({{"text", s ? s : ""}, {"start", d.t0 / 100.0}, {"end", d.t1 / 100.0}, {"logprob", std::log(std::max(d.p, 1e-9f))}});+ }+ }+ }+ out["text"] = text;+ out["tokens"] = tokens;+ res.set_content(out.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");+ });++ svr.set_exception_handler([](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {+ std::string what = "unknown";+ try { std::rethrow_exception(ep); } catch (const std::exception & e) { what = e.what(); } catch (...) {}+ res.status = 500;+ res.set_content(json{{"error", what}}.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");+ });+ svr.set_read_timeout(600);+ svr.set_write_timeout(600);++ if (!svr.bind_to_port(host, port)) { fprintf(stderr, "parakeet-server: couldn't bind to %s:%d\n", host.c_str(), port); parakeet_free(ctx); return 1; }+ fprintf(stderr, "parakeet-server: listening at http://%s:%d with %d threads\n", host.c_str(), port, threads);+ svr.listen_after_bind();+ parakeet_free(ctx);+ return 0;+}diff --git a/app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txt b/app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txtnew file mode 100644index 00000000..fbe83688--- /dev/null+++ b/app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txt@@ -0,0 +1,412 @@+Parakeet TDT 0.6B v3++Yogurt transcribes the languages this model covers with Parakeet TDT 0.6B v3 by NVIDIA+(https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3), licensed under the Creative Commons+Attribution 4.0 International licence (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/).++The model is not shipped with Yogurt: it is downloaded on first use. Yogurt downloads converted+weights, not NVIDIA's original files: the GGML file ggml-parakeet-tdt-0.6b-v3-q8_0.bin from+https://huggingface.co/ggml-org/parakeet-GGUF (revision 35156454d1a39de06863303dd209fd2bed6ee079),+converted from the original for whisper.cpp and quantized to 8 bits. No other changes were made.+It is run by whisper.cpp (MIT, see whisper.cpp-MIT.txt).++The licence text follows.++=======================================================================++Attribution 4.0 International++=======================================================================++Creative Commons Corporation ("Creative Commons") is not a law firm and+does not provide legal services or legal advice. Distribution of+Creative Commons public licenses does not create a lawyer-client or+other relationship. Creative Commons makes its licenses and related+information available on an "as-is" basis. Creative Commons gives no+warranties regarding its licenses, any material licensed under their+terms and conditions, or any related information. Creative Commons+disclaims all liability for damages resulting from their use to the+fullest extent possible.++Using Creative Commons Public Licenses++Creative Commons public licenses provide a standard set of terms and+conditions that creators and other rights holders may use to share+original works of authorship and other material subject to copyright+and certain other rights specified in the public license below. The+following considerations are for informational purposes only, are not+exhaustive, and do not form part of our licenses.++ Considerations for licensors: Our public licenses are+ intended for use by those authorized to give the public+ permission to use material in ways otherwise restricted by+ copyright and certain other rights. Our licenses are+ irrevocable. Licensors should read and understand the terms+ and conditions of the license they choose before applying it.+ Licensors should also secure all rights necessary before+ applying our licenses so that the public can reuse the+ material as expected. Licensors should clearly mark any+ material not subject to the license. This includes other CC-+ licensed material, or material used under an exception or+ limitation to copyright. More considerations for licensors:+ wiki.creativecommons.org/Considerations_for_licensors++ Considerations for the public: By using one of our public+ licenses, a licensor grants the public permission to use the+ licensed material under specified terms and conditions. If+ the licensor's permission is not necessary for any reason--for+ example, because of any applicable exception or limitation to+ copyright--then that use is not regulated by the license. Our+ licenses grant only permissions under copyright and certain+ other rights that a licensor has authority to grant. Use of+ the licensed material may still be restricted for other+ reasons, including because others have copyright or other+ rights in the material. A licensor may make special requests,+ such as asking that all changes be marked or described.+ Although not required by our licenses, you are encouraged to+ respect those requests where reasonable. More considerations+ for the public:+ wiki.creativecommons.org/Considerations_for_licensees++=======================================================================++Creative Commons Attribution 4.0 International Public License++By exercising the Licensed Rights (defined below), You accept and agree+to be bound by the terms and conditions of this Creative Commons+Attribution 4.0 International Public License ("Public License"). To the+extent this Public License may be interpreted as a contract, You are+granted the Licensed Rights in consideration of Your acceptance of+these terms and conditions, and the Licensor grants You such rights in+consideration of benefits the Licensor receives from making the+Licensed Material available under these terms and conditions.+++Section 1 -- Definitions.++ a. Adapted Material means material subject to Copyright and Similar+ Rights that is derived from or based upon the Licensed Material+ and in which the Licensed Material is translated, altered,+ arranged, transformed, or otherwise modified in a manner requiring+ permission under the Copyright and Similar Rights held by the+ Licensor. For purposes of this Public License, where the Licensed+ Material is a musical work, performance, or sound recording,+ Adapted Material is always produced where the Licensed Material is+ synched in timed relation with a moving image.++ b. Adapter's License means the license You apply to Your Copyright+ and Similar Rights in Your contributions to Adapted Material in+ accordance with the terms and conditions of this Public License.++ c. Copyright and Similar Rights means copyright and/or similar rights+ closely related to copyright including, without limitation,+ performance, broadcast, sound recording, and Sui Generis Database+ Rights, without regard to how the rights are labeled or+ categorized. For purposes of this Public License, the rights+ specified in Section 2(b)(1)-(2) are not Copyright and Similar+ Rights.++ d. Effective Technological Measures means those measures that, in the+ absence of proper authority, may not be circumvented under laws+ fulfilling obligations under Article 11 of the WIPO Copyright+ Treaty adopted on December 20, 1996, and/or similar international+ agreements.++ e. Exceptions and Limitations means fair use, fair dealing, and/or+ any other exception or limitation to Copyright and Similar Rights+ that applies to Your use of the Licensed Material.++ f. Licensed Material means the artistic or literary work, database,+ or other material to which the Licensor applied this Public+ License.++ g. Licensed Rights means the rights granted to You subject to the+ terms and conditions of this Public License, which are limited to+ all Copyright and Similar Rights that apply to Your use of the+ Licensed Material and that the Licensor has authority to license.++ h. Licensor means the individual(s) or entity(ies) granting rights+ under this Public License.++ i. Share means to provide material to the public by any means or+ process that requires permission under the Licensed Rights, such+ as reproduction, public display, public performance, distribution,+ dissemination, communication, or importation, and to make material+ available to the public including in ways that members of the+ public may access the material from a place and at a time+ individually chosen by them.++ j. Sui Generis Database Rights means rights other than copyright+ resulting from Directive 96/9/EC of the European Parliament and of+ the Council of 11 March 1996 on the legal protection of databases,+ as amended and/or succeeded, as well as other essentially+ equivalent rights anywhere in the world.++ k. You means the individual or entity exercising the Licensed Rights+ under this Public License. Your has a corresponding meaning.+++Section 2 -- Scope.++ a. License grant.++ 1. Subject to the terms and conditions of this Public License,+ the Licensor hereby grants You a worldwide, royalty-free,+ non-sublicensable, non-exclusive, irrevocable license to+ exercise the Licensed Rights in the Licensed Material to:++ a. reproduce and Share the Licensed Material, in whole or+ in part; and++ b. produce, reproduce, and Share Adapted Material.++ 2. Exceptions and Limitations. For the avoidance of doubt, where+ Exceptions and Limitations apply to Your use, this Public+ License does not apply, and You do not need to comply with+ its terms and conditions.++ 3. Term. The term of this Public License is specified in Section+ 6(a).++ 4. Media and formats; technical modifications allowed. The+ Licensor authorizes You to exercise the Licensed Rights in+ all media and formats whether now known or hereafter created,+ and to make technical modifications necessary to do so. The+ Licensor waives and/or agrees not to assert any right or+ authority to forbid You from making technical modifications+ necessary to exercise the Licensed Rights, including+ technical modifications necessary to circumvent Effective+ Technological Measures. For purposes of this Public License,+ simply making modifications authorized by this Section 2(a)+ (4) never produces Adapted Material.++ 5. Downstream recipients.++ a. Offer from the Licensor -- Licensed Material. Every+ recipient of the Licensed Material automatically+ receives an offer from the Licensor to exercise the+ Licensed Rights under the terms and conditions of this+ Public License.++ b. No downstream restrictions. You may not offer or impose+ any additional or different terms or conditions on, or+ apply any Effective Technological Measures to, the+ Licensed Material if doing so restricts exercise of the+ Licensed Rights by any recipient of the Licensed+ Material.++ 6. No endorsement. Nothing in this Public License constitutes or+ may be construed as permission to assert or imply that You+ are, or that Your use of the Licensed Material is, connected+ with, or sponsored, endorsed, or granted official status by,+ the Licensor or others designated to receive attribution as+ provided in Section 3(a)(1)(A)(i).++ b. Other rights.++ 1. Moral rights, such as the right of integrity, are not+ licensed under this Public License, nor are publicity,+ privacy, and/or other similar personality rights; however, to+ the extent possible, the Licensor waives and/or agrees not to+ assert any such rights held by the Licensor to the limited+ extent necessary to allow You to exercise the Licensed+ Rights, but not otherwise.++ 2. Patent and trademark rights are not licensed under this+ Public License.++ 3. To the extent possible, the Licensor waives any right to+ collect royalties from You for the exercise of the Licensed+ Rights, whether directly or through a collecting society+ under any voluntary or waivable statutory or compulsory+ licensing scheme. In all other cases the Licensor expressly+ reserves any right to collect such royalties.+++Section 3 -- License Conditions.++Your exercise of the Licensed Rights is expressly made subject to the+following conditions.++ a. Attribution.++ 1. If You Share the Licensed Material (including in modified+ form), You must:++ a. retain the following if it is supplied by the Licensor+ with the Licensed Material:++ i. identification of the creator(s) of the Licensed+ Material and any others designated to receive+ attribution, in any reasonable manner requested by+ the Licensor (including by pseudonym if+ designated);++ ii. a copyright notice;++ iii. a notice that refers to this Public License;++ iv. a notice that refers to the disclaimer of+ warranties;++ v. a URI or hyperlink to the Licensed Material to the+ extent reasonably practicable;++ b. indicate if You modified the Licensed Material and+ retain an indication of any previous modifications; and++ c. indicate the Licensed Material is licensed under this+ Public License, and include the text of, or the URI or+ hyperlink to, this Public License.++ 2. You may satisfy the conditions in Section 3(a)(1) in any+ reasonable manner based on the medium, means, and context in+ which You Share the Licensed Material. For example, it may be+ reasonable to satisfy the conditions by providing a URI or+ hyperlink to a resource that includes the required+ information.++ 3. If requested by the Licensor, You must remove any of the+ information required by Section 3(a)(1)(A) to the extent+ reasonably practicable.++ 4. If You Share Adapted Material You produce, the Adapter's+ License You apply must not prevent recipients of the Adapted+ Material from complying with this Public License.+++Section 4 -- Sui Generis Database Rights.++Where the Licensed Rights include Sui Generis Database Rights that+apply to Your use of the Licensed Material:++ a. for the avoidance of doubt, Section 2(a)(1) grants You the right+ to extract, reuse, reproduce, and Share all or a substantial+ portion of the contents of the database;++ b. if You include all or a substantial portion of the database+ contents in a database in which You have Sui Generis Database+ Rights, then the database in which You have Sui Generis Database+ Rights (but not its individual contents) is Adapted Material; and++ c. You must comply with the conditions in Section 3(a) if You Share+ all or a substantial portion of the contents of the database.++For the avoidance of doubt, this Section 4 supplements and does not+replace Your obligations under this Public License where the Licensed+Rights include other Copyright and Similar Rights.+++Section 5 -- Disclaimer of Warranties and Limitation of Liability.++ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.++ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.++ c. The disclaimer of warranties and limitation of liability provided+ above shall be interpreted in a manner that, to the extent+ possible, most closely approximates an absolute disclaimer and+ waiver of all liability.+++Section 6 -- Term and Termination.++ a. This Public License applies for the term of the Copyright and+ Similar Rights licensed here. However, if You fail to comply with+ this Public License, then Your rights under this Public License+ terminate automatically.++ b. Where Your right to use the Licensed Material has terminated under+ Section 6(a), it reinstates:++ 1. automatically as of the date the violation is cured, provided+ it is cured within 30 days of Your discovery of the+ violation; or++ 2. upon express reinstatement by the Licensor.++ For the avoidance of doubt, this Section 6(b) does not affect any+ right the Licensor may have to seek remedies for Your violations+ of this Public License.++ c. For the avoidance of doubt, the Licensor may also offer the+ Licensed Material under separate terms or conditions or stop+ distributing the Licensed Material at any time; however, doing so+ will not terminate this Public License.++ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public+ License.+++Section 7 -- Other Terms and Conditions.++ a. The Licensor shall not be bound by any additional or different+ terms or conditions communicated by You unless expressly agreed.++ b. Any arrangements, understandings, or agreements regarding the+ Licensed Material not stated herein are separate from and+ independent of the terms and conditions of this Public License.+++Section 8 -- Interpretation.++ a. For the avoidance of doubt, this Public License does not, and+ shall not be interpreted to, reduce, limit, restrict, or impose+ conditions on any use of the Licensed Material that could lawfully+ be made without permission under this Public License.++ b. To the extent possible, if any provision of this Public License is+ deemed unenforceable, it shall be automatically reformed to the+ minimum extent necessary to make it enforceable. If the provision+ cannot be reformed, it shall be severed from this Public License+ without affecting the enforceability of the remaining terms and+ conditions.++ c. No term or condition of this Public License will be waived and no+ failure to comply consented to unless expressly agreed to by the+ Licensor.++ d. Nothing in this Public License constitutes or may be interpreted+ as a limitation upon, or waiver of, any privileges and immunities+ that apply to the Licensor or You, including from the legal+ processes of any jurisdiction or authority.+++=======================================================================++Creative Commons is not a party to its public+licenses. Notwithstanding, Creative Commons may elect to apply one of+its public licenses to material it publishes and in those instances+will be considered the “Licensor.” The text of the Creative Commons+public licenses is dedicated to the public domain under the CC0 Public+Domain Dedication. Except for the limited purpose of indicating that+material is shared under a Creative Commons public license or as+otherwise permitted by the Creative Commons policies published at+creativecommons.org/policies, Creative Commons does not authorize the+use of the trademark "Creative Commons" or any other trademark or logo+of Creative Commons without its prior written consent including,+without limitation, in connection with any unauthorized modifications+to any of its public licenses or any other arrangements,+understandings, or agreements concerning use of licensed material. For+the avoidance of doubt, this paragraph does not form part of the+public licenses.++Creative Commons may be contacted at creativecommons.org.+diff --git a/app/scripts/helpers-smoke.mjs b/app/scripts/helpers-smoke.mjsindex 28b29153..2af40638 100644--- a/app/scripts/helpers-smoke.mjs+++ b/app/scripts/helpers-smoke.mjs@@ -26,6 +26,8 @@ check(existsSync(join(a.resources, 'dict', 'words')), 'the word list is installeif (process.platform === 'linux') check(existsSync(bin('libyogurt-bigalloc.so')), 'the notes engine\'s allocator shim is installed', bin('libyogurt-bigalloc.so'))if (!a['no-whisper']) {check(existsSync(bin('whisper-server')), 'whisper-server is installed', bin('whisper-server'))+ check(existsSync(bin('parakeet-server')), 'parakeet-server is installed', bin('parakeet-server'))+ check(run(bin('parakeet-server'), ['--help']).status === 0, 'parakeet-server starts')check(existsSync(join(a.resources, 'vad', 'ggml-silero-v6.2.0.bin')), 'the VAD model is installed')const libs = readdirSync(join(a.resources, 'bin')).filter((f) => (win ? /^ggml.*\.dll$/ : /^libggml.*\.so$/).test(f))check(libs.some((f) => /cpu/i.test(f)), "whisper-server's CPU backends are installed", libs.join(' '))diff --git a/app/scripts/native.sh b/app/scripts/native.shindex 30da790d..e63d6f61 100755--- a/app/scripts/native.sh+++ b/app/scripts/native.sh@@ -1,6 +1,7 @@#!/bin/sh# Builds the Mac helpers (Apple Silicon) into resources/bin: yogurt-mac (calendar, mic apps, names from calls),-# yogurt-audio (recording), yogurt-mcp (AI apps reading meetings) and whisper-server (speech to text, built from a pinned whisper.cpp).+# yogurt-audio (recording), yogurt-mcp (AI apps reading meetings), and whisper-server and parakeet-server (speech to text,+# built from a pinned whisper.cpp).# Skipped off a Mac, or when a helper is newer than its source.set -e[ "$(uname)" = "Darwin" ] || exit 0@@ -21,10 +22,14 @@ done# The clone and build live in native/.whisper-build (gitignored); only the finished program is copied out.# native/whisper-server.patch is applied on top: with VAD on, a chunk with no speech in it crashed the server.# It also makes whisper pick a discrete graphics card over an integrated one (Windows and Linux; a Mac has one).+# parakeet-server (native/parakeet-server) is built in the same tree, as one more example: Parakeet TDT through the+# parakeet.h that this whisper.cpp carries, so there is no second runtime.WHISPER_TAG=v1.9.5WHISPER_COMMIT=d1be6fde11ac6e0407606b4e42fe72d34add8037out=resources/bin/whisper-server-if [ ! -f "$out" ] || [ "$0" -nt "$out" ] || [ native/whisper-server.patch -nt "$out" ]; then+pk=resources/bin/parakeet-server+if [ ! -f "$out" ] || [ ! -f "$pk" ] || [ "$0" -nt "$out" ] || [ native/whisper-server.patch -nt "$out" ] \+ || [ native/parakeet-server/server.cpp -nt "$pk" ] || [ native/parakeet-server/CMakeLists.txt -nt "$pk" ]; thenCMAKE=/opt/homebrew/bin/cmake[ -x "$CMAKE" ] || CMAKE=$(command -v cmake) || { echo "cmake is needed to build whisper-server (brew install cmake)" >&2; exit 1; }dir=native/.whisper-build@@ -34,12 +39,15 @@ if [ ! -f "$out" ] || [ "$0" -nt "$out" ] || [ native/whisper-server.patch -nt "git -C "$dir" checkout --quiet --force "$WHISPER_COMMIT"[ "$(git -C "$dir" rev-parse HEAD)" = "$WHISPER_COMMIT" ] || { echo "whisper.cpp is not at $WHISPER_COMMIT" >&2; exit 1; }git -C "$dir" apply "$PWD/native/whisper-server.patch"+ rm -rf "$dir/examples/parakeet-server" && cp -R native/parakeet-server "$dir/examples/parakeet-server"+ echo 'add_subdirectory(parakeet-server)' >> "$dir/examples/CMakeLists.txt""$CMAKE" -S "$dir" -B "$dir/build" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF \-DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DWHISPER_BUILD_TESTS=OFF \-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=14.4 >/dev/null- "$CMAKE" --build "$dir/build" --config Release --target whisper-server -j "$(sysctl -n hw.ncpu)" >/dev/null+ "$CMAKE" --build "$dir/build" --config Release --target whisper-server parakeet-server -j "$(sysctl -n hw.ncpu)" >/dev/nullcp "$dir/build/bin/whisper-server" "$out"- echo "built $out"+ cp "$dir/build/bin/parakeet-server" "$pk"+ echo "built $out and $pk"fi# Silero VAD for whisper-server (MIT, ggml-org/whisper-vad at a pinned commit): whisper only reads the stretches withdiff --git a/app/scripts/release-mac.sh b/app/scripts/release-mac.shindex 10cc51b4..af4fa7f9 100755--- a/app/scripts/release-mac.sh+++ b/app/scripts/release-mac.sh@@ -66,6 +66,19 @@ for h in "$APP" "$APP"/Contents/Resources/bin/*; doinfo=$(codesign -dv "$h" 2>&1)echo "$info" | grep -q "runtime" || { echo "$h has no hardened runtime" >&2; exit 1; }done+# both speech programs are in, and the signed parakeet-server starts (hardened runtime, no entitlements)+for h in whisper-server parakeet-server; do [ -x "$APP/Contents/Resources/bin/$h" ] || { echo "$h is not in the app" >&2; exit 1; }; done+"$APP/Contents/Resources/bin/parakeet-server" --help >/dev/null 2>&1 || { echo "the packaged parakeet-server doesn't start" >&2; exit 1; }+# and it reads a clip on this Mac's graphics (Metal), as it will in meetings, when its model is here: the one this Mac's+# own Yogurt downloaded (only read), or YOGURT_PARAKEET_MODEL+PK_MODEL="${YOGURT_PARAKEET_MODEL:-$HOME/Library/Application Support/Yogurt/models/asr/ggml-parakeet-tdt-0.6b-v3-q8_0.bin}"+if [ -f "$PK_MODEL" ]; then+ node scripts/whisper-smoke.mjs --engine parakeet --bin "$APP/Contents/Resources/bin/parakeet-server" --model "$PK_MODEL" \+ --wav native/.whisper-build/samples/jfk.wav --expect country,ask --silence --runs 1 --label packaged-parakeet-metal \+ || { echo "the packaged parakeet-server doesn't transcribe on this Mac's graphics" >&2; exit 1; }+else+ echo "no Parakeet model on this Mac ($PK_MODEL): the packaged parakeet-server was started, not asked to transcribe"+ficodesign -d --entitlements - "$APP/Contents/Resources/bin/yogurt-audio" 2>/dev/null | grep -q device.audio-input || { echo "yogurt-audio can't use the microphone" >&2; exit 1; }if [ "${YOGURT_FUSES:-1}" != 0 ]; thenpnpm exec electron-fuses read --app "$APP" | grep -q "RunAsNode is Disabled" || { echo "Electron's fuses aren't set" >&2; exit 1; }diff --git a/app/scripts/sign.cjs b/app/scripts/sign.cjsindex 7f25f1e5..7b66b845 100644--- a/app/scripts/sign.cjs+++ b/app/scripts/sign.cjs@@ -6,6 +6,7 @@ const HELPERS = {'yogurt-audio': 'entitlements.audio.plist','yogurt-mac': 'entitlements.mac-helper.plist','whisper-server': 'entitlements.none.plist',+ 'parakeet-server': 'entitlements.none.plist','yogurt-mcp': 'entitlements.none.plist',}diff --git a/app/scripts/speed-check-smoke.mjs b/app/scripts/speed-check-smoke.mjsindex 7d898863..4a991f7b 100644--- a/app/scripts/speed-check-smoke.mjs+++ b/app/scripts/speed-check-smoke.mjs@@ -4,6 +4,8 @@// does, reads it back and checks a time was stored for the first model. Prints the result; a row goes to $GITHUB_STEP_SUMMARY.//// node scripts/speed-check-smoke.mjs --bin <whisper-server> --vad <silero .bin> --model a.bin[,b.bin] [--store file.json]+// [--parakeet-bin <parakeet-server> --parakeet <ggml .bin>]+// --parakeet: Parakeet is timed first, by the same rules, as setup does; its time is stored with the others.import { appendFileSync, mkdtempSync } from 'node:fs'import { availableParallelism, cpus, tmpdir } from 'node:os'import { basename, join } from 'node:path'@@ -11,16 +13,19 @@ import { registerHooks } from 'node:module'import { parseArgs } from 'node:util'import { fileURLToPath } from 'node:url'-// the app's sources import each other without extensions (the bundler finds them); plain Node needs the .ts+// the app's sources import each other without extensions (the bundler finds them); plain Node needs the .ts.+// Nothing is installed where this runs, so the picker package is its one file the speed check uses (no dependencies).+const picker = new URL('../../packages/picker/src/asr.ts', import.meta.url).hrefregisterHooks({resolve(spec, ctx, next) {+ if (spec === '@yogurt/picker') return next(picker, ctx)try { return next(spec, ctx) } catch (e) { if (spec.startsWith('.')) return next(spec + '.ts', ctx); throw e }},})-const { measureSpeed, speedStore } = await import('../src/main/asr/speedCheck.ts')-const { pickBySpeed, KEEPS_UP_RTF } = await import('../../packages/picker/src/asr.ts')+const { measureParakeet, measureSpeed, speedStore } = await import('../src/main/asr/speedCheck.ts')+const { parakeetKeepsUp, pickBySpeed, KEEPS_UP_RTF } = await import('../../packages/picker/src/asr.ts')-const { values: a } = parseArgs({ options: { bin: { type: 'string' }, vad: { type: 'string' }, model: { type: 'string' }, store: { type: 'string' } } })+const { values: a } = parseArgs({ options: { bin: { type: 'string' }, vad: { type: 'string' }, model: { type: 'string' }, store: { type: 'string' }, 'parakeet-bin': { type: 'string' }, parakeet: { type: 'string' } } })if (!a.bin || !a.model) { console.error('--bin and --model are needed'); process.exit(2) }// the clip the app ships (speedClipPath finds it there; plain Node has no __dirname for the app's sources)const clip = fileURLToPath(new URL('../resources/speed/clip.wav', import.meta.url))@@ -28,6 +33,13 @@ const file = a.store ?? join(mkdtempSync(join(tmpdir(), 'speed-')), 'speech-speeconst models = a.model.split(',').map((path) => ({ id: basename(path), path }))const key = `${process.platform}|${process.arch}|${cpus()[0]?.model}|${availableParallelism()}|ci`+let parakeet+if (a.parakeet) {+ if (!a['parakeet-bin']) { console.error('--parakeet-bin is needed with --parakeet'); process.exit(2) }+ parakeet = await measureParakeet(a.parakeet, { binary: a['parakeet-bin'], clip })+ console.log(`${basename(a.parakeet)}: ${parakeet === null ? 'ran out of time' : `${parakeet} x the clip's length`} on the processor (${parakeetKeepsUp(parakeet) ? 'keeps up live' : 'does not keep up live'})`)+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `\nSpeed check on ${process.platform}: Parakeet took **${parakeet ?? 'too long'}** x the clip's length on the processor (${availableParallelism()} x ${cpus()[0]?.model}): ${parakeetKeepsUp(parakeet) ? 'it keeps up live' : 'it does not keep up live'}\n`)+}let gpuOff = falseconst r = await pickBySpeed(models, async (m) => {const t = await measureSpeed(m.path, { binary: a.bin, vadModel: a.vad, clip })@@ -36,7 +48,7 @@ const r = await pickBySpeed(models, async (m) => {return t.rtf})const store = speedStore(file)-store.save({ key, model: r.model?.id ?? null, rtf: r.rtf, at: Date.now(), ...(gpuOff ? { gpuOff } : {}) })+store.save({ key, model: r.model?.id ?? null, rtf: r.rtf, at: Date.now(), ...(gpuOff ? { gpuOff } : {}), ...(parakeet !== undefined ? { parakeet } : {}) })const back = speedStore(file).load()console.log(`RESULT ${JSON.stringify(back)}`)const first = models[0].iddiff --git a/app/scripts/whisper-build.mjs b/app/scripts/whisper-build.mjsindex ed0f3f12..369a4632 100644--- a/app/scripts/whisper-build.mjs+++ b/app/scripts/whisper-build.mjs@@ -1,6 +1,6 @@#!/usr/bin/env node-// Builds whisper-server for Windows (x64) and Linux (x86_64) into resources/bin, and fetches the Silero VAD model into-// resources/vad. The Mac build stays in native.sh; this one uses the same pinned whisper.cpp and the same patch,+// Builds whisper-server and parakeet-server (native/parakeet-server, Parakeet through the same whisper.cpp's parakeet.h)+// for Windows (x64) and Linux (x86_64) into resources/bin, and fetches the Silero VAD model into resources/vad. The Mac build stays in native.sh; this one uses the same pinned whisper.cpp and the same patch,// plus native/whisper-vad-threads.patch: VAD ran on a fixed 4 threads, which on a 2-core computer made it so slow the// first chunk never came back (Macs have 8 cores or more, so native.sh does without it).//@@ -13,7 +13,7 @@// --cpu-only builds without Vulkan, for a quick local build without the SDK.import { spawnSync } from 'node:child_process'import { createHash } from 'node:crypto'-import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { appendFileSync, copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'import { cpus } from 'node:os'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'@@ -33,6 +33,8 @@ const vadPatch = join(app, 'native', 'whisper-vad-threads.patch')const dir = join(app, 'native', '.whisper-build')const bin = join(app, 'resources', 'bin')const out = join(bin, win ? 'whisper-server.exe' : 'whisper-server')+const pkSrc = join(app, 'native', 'parakeet-server')+const pkOut = join(bin, win ? 'parakeet-server.exe' : 'parakeet-server')const run = (cmd, args, opts = {}) => {const r = spawnSync(cmd, args, { stdio: 'inherit', ...opts })@@ -42,7 +44,7 @@ const run = (cmd, args, opts = {}) => {const git = (...args) => run('git', ['-C', dir, ...args])const newer = (a, b) => statSync(a).mtimeMs > statSync(b).mtimeMs-if (!existsSync(out) || newer(script, out) || newer(patch, out) || newer(vadPatch, out)) {+if (!existsSync(out) || !existsSync(pkOut) || newer(script, out) || newer(patch, out) || newer(vadPatch, out) || newer(join(pkSrc, 'server.cpp'), pkOut) || newer(join(pkSrc, 'CMakeLists.txt'), pkOut)) {if (!cpuOnly && !process.env.VULKAN_SDK && win) { console.error('the Vulkan SDK is needed (set VULKAN_SDK), or pass --cpu-only'); process.exit(1) }if (!existsSync(join(dir, '.git'))) run('git', ['clone', '--quiet', 'https://github.com/ggml-org/whisper.cpp.git', dir])git('checkout', '--quiet', '--force', WHISPER_COMMIT)@@ -50,6 +52,10 @@ if (!existsSync(out) || newer(script, out) || newer(patch, out) || newer(vadPatcif (head !== WHISPER_COMMIT) { console.error(`whisper.cpp is not at ${WHISPER_COMMIT}`); process.exit(1) }git('apply', patch)git('apply', vadPatch)+ // parakeet-server is one more example in the same tree+ rmSync(join(dir, 'examples', 'parakeet-server'), { recursive: true, force: true })+ cpSync(pkSrc, join(dir, 'examples', 'parakeet-server'), { recursive: true })+ appendFileSync(join(dir, 'examples', 'CMakeLists.txt'), '\nadd_subdirectory(parakeet-server)\n')const build = join(dir, 'build')rmSync(build, { recursive: true, force: true })@@ -67,7 +73,7 @@ if (!existsSync(out) || newer(script, out) || newer(patch, out) || newer(vadPatc}run('cmake', ['-S', dir, '-B', build, ...flags])// ggml depends on its backends (GGML_BACKEND_DL), so this builds them too- run('cmake', ['--build', build, '--config', 'Release', '--target', 'whisper-server', '-j', String(cpus().length)])+ run('cmake', ['--build', build, '--config', 'Release', '--target', 'whisper-server', 'parakeet-server', '-j', String(cpus().length)])const built = win ? join(build, 'bin', 'Release') : join(build, 'bin')mkdirSync(bin, { recursive: true })@@ -75,8 +81,9 @@ if (!existsSync(out) || newer(script, out) || newer(patch, out) || newer(vadPatcfor (const f of readdirSync(bin)) if (isWhisperLib(f, win)) rmSync(join(bin, f))for (const f of libs) copyFileSync(join(built, f), join(bin, f))copyFileSync(join(built, win ? 'whisper-server.exe' : 'whisper-server'), out)- if (win) utf8Manifest(out)- console.log(`built ${out} with ${libs.join(', ')}`)+ copyFileSync(join(built, win ? 'parakeet-server.exe' : 'parakeet-server'), pkOut)+ if (win) { utf8Manifest(out); utf8Manifest(pkOut) }+ console.log(`built ${out} and ${pkOut} with ${libs.join(', ')}`)}// Silero VAD, the same file and checksum as native.shdiff --git a/app/scripts/whisper-smoke.mjs b/app/scripts/whisper-smoke.mjsindex d159248f..c54ed264 100644--- a/app/scripts/whisper-smoke.mjs+++ b/app/scripts/whisper-smoke.mjs@@ -5,6 +5,9 @@//// node scripts/whisper-smoke.mjs --bin <whisper-server> --model <ggml .bin> [--vad <silero .bin>]// --wav a.wav,b.wav [--expect word,word] [--runs 3] [--label name] [--silence] [--unicode-dir] [--threads N]+// [--engine parakeet] [--cpu]+// --engine parakeet: the program is parakeet-server and the model a Parakeet one (the same launcher and request; it has+// no beam, so both columns are the same reading). --cpu: on the processor alone, as the app runs Parakeet on Windows and Linux.// --expect: words the first clip must contain. --silence: also send 3 s of silence, which crashed the server with VAD on// before native/whisper-server.patch. --unicode-dir: first copy the program's folder, the model and the VAD model under a// folder named like a Windows user called José (and a few more scripts), as an installed copy and its models would be.@@ -27,7 +30,7 @@ const { createWhisperServer } = await import('../src/main/asr/server.ts')const { values: a } = parseArgs({options: {bin: { type: 'string' }, model: { type: 'string' }, vad: { type: 'string' }, wav: { type: 'string' },- expect: { type: 'string' }, runs: { type: 'string', default: '3' }, label: { type: 'string' }, silence: { type: 'boolean' }, 'unicode-dir': { type: 'boolean' }, threads: { type: 'string' },+ expect: { type: 'string' }, runs: { type: 'string', default: '3' }, label: { type: 'string' }, silence: { type: 'boolean' }, 'unicode-dir': { type: 'boolean' }, threads: { type: 'string' }, engine: { type: 'string' }, cpu: { type: 'boolean' },},})if (!a.bin || !a.model || !a.wav) { console.error('--bin, --model and --wav are needed'); process.exit(2) }@@ -61,7 +64,7 @@ const silenceWav = (ms) => {return b}-const srv = createWhisperServer({ binary: a.bin, model: a.model, vadModel: a.vad, threads, startTimeoutMs: 300_000 })+const srv = createWhisperServer({ binary: a.bin, model: a.model, vadModel: a.vad, threads, startTimeoutMs: 300_000, ...(a.engine === 'parakeet' ? { engine: 'parakeet' } : {}), ...(a.cpu ? { cpuOnly: true } : {}) })const t0 = performance.now()let failed = falsetry {diff --git a/app/scripts/whisperLibs.mjs b/app/scripts/whisperLibs.mjsindex a91c0048..8b179111 100644--- a/app/scripts/whisperLibs.mjs+++ b/app/scripts/whisperLibs.mjs@@ -1,3 +1,3 @@// The shared libraries whisper-server's build owns in resources/bin, so a rebuild replaces them and nothing else:// on Linux the notes engine's allocator shim (libyogurt-bigalloc.so, #32) lives there too.-export const isWhisperLib = (name, win) => win ? name.endsWith('.dll') : /^lib(ggml|whisper).*\.so/.test(name)+export const isWhisperLib = (name, win) => win ? name.endsWith('.dll') : /^lib(ggml|whisper|parakeet).*\.so/.test(name)diff --git a/app/src/main/asr/fake.ts b/app/src/main/asr/fake.tsindex dd3a96fa..de408fcd 100644--- a/app/src/main/asr/fake.ts+++ b/app/src/main/asr/fake.ts@@ -18,9 +18,11 @@ const SAYS = {],} as const-export async function fakeTranscribe(c: Chunk, o?: { partial?: boolean }, prompt = '', language?: string): Promise<Line[]> {- fakePrompts.whisper.push(prompt)+export async function fakeTranscribe(c: Chunk, o?: { partial?: boolean }, prompt = '', language?: string, engine: 'parakeet' | 'whisper' = 'whisper'): Promise<Line[]> {+ // Parakeet takes no prompt: only whisper is given the meeting's names and jargon+ if (engine === 'whisper') fakePrompts.whisper.push(prompt)fakePrompts.languages.push(language ?? 'auto')+ fakePrompts.engines.push(engine)const near = SAYS[c.track].reduce((a, b) => (Math.abs(b.at - c.startMs) < Math.abs(a.at - c.startMs) ? b : a))// a partial: the first words, about as many as have been said so farconst words = near.text.split(' ')diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.tsindex 9fb133af..317cbcca 100644--- a/app/src/main/asr/index.ts+++ b/app/src/main/asr/index.ts@@ -11,10 +11,11 @@ import { loadAec3 } from './aec3'import { echoConfidence } from './echo'import { appleSpeechAvailable, installSpeechLocale, readSpeechLocales, speechDisagrees, speechFits, wantedSpeechLocale, type SpeechHost, type SpeechLocales } from './appleSpeech'import { whisperLanguage, type Spoken } from '../../shared/spoken'-import { basename } from 'node:path'-import { createWhisperServer, recoverer, vadModelPath, whisperServerPath, type WhisperServer } from './server'+import { basename, dirname, join } from 'node:path'+import { createWhisperServer, parakeetServerPath, recoverer, vadModelPath, whisperServerPath, type WhisperServer } from './server'import { clipStart, hearsClip } from './speedCheck'-import { createTranscriber, type Line, type Transcribe } from './transcribe'+import { createTranscriber, type Line, type Target, type Transcribe } from './transcribe'+import { engineFor, parakeetCovers } from './parakeet'import { meetingWords, respell, whisperPrompt } from '../vocab'import type { TranscriptPartial } from '../../shared/types'import type { Chunk } from './chunker'@@ -107,8 +108,19 @@ export function spokenChanged() {/** segments and hideSegments: the echo sweep after the meeting (tests may leave them out) */type SessionStore = Pick<Store, 'updateMeeting'> & Partial<Pick<Store, 'segments' | 'hideSegments' | 'meeting' | 'deleteSegments'>>-let server: WhisperServer | undefined-let serverKey: string | undefined+/**+ * The speech servers while meetings need them: whisper (the model for this computer), and with Parakeet in use+ * parakeet-server and, where the main whisper is a bigger model, a small whisper that hears which language a track is in.+ */+type Slot = 'whisper' | 'parakeet' | 'lid'+/**+ * parakeet-server never answered in a meeting (it won't start here): the next meetings start on whisper instead of+ * finding that out again. Only until Yogurt is started again, when it gets another try.+ */+let parakeetTrouble: string | null = null+/** for tests */+export const forgetParakeetTrouble = (): void => { parakeetTrouble = null }+const servers = new Map<Slot, { srv: WhisperServer; key: string }>()const sessions = new Map<string, Session>()/** Unknown, stale or paused input is not evidence that a conversation ended. */export function liveSilentMs(id: string, now = Date.now()): number {@@ -153,26 +165,30 @@ export function onWhisperGpuOff(cb: () => void) { gpuOffListener = cb }/** One whisper-server while meetings need it: started (warmed up) when one starts, let go a while after the last *//** keepCpu: the speed check found the processor faster than the graphics here: whisper never tries the graphics */-function serverFor(model: string, pidFile: string | undefined, make?: (model: string, pidFile?: string) => WhisperServer, o: { cpuOnly?: boolean; keepCpu?: boolean } = {}): WhisperServer {+function serverFor(model: string, pidFile: string | undefined, make?: (model: string, pidFile?: string) => WhisperServer, o: { cpuOnly?: boolean; keepCpu?: boolean; slot?: Slot } = {}): WhisperServer {clearTimeout(idleTimer)+ const slot = o.slot ?? 'whisper'const key = `${model}|${pidFile}`- if (!server || serverKey !== key) {- void server?.stop()- server = make ? make(model, pidFile) : createWhisperServer({ binary: whisperServerPath(), model, pidFile, vadModel: vadModelPath(), gpuFallback: process.platform !== 'darwin' && !o.keepCpu, cpuOnly: o.cpuOnly || o.keepCpu, onGpuOff: () => gpuOffListener?.(), checkGpu: async (url) => { const clip = clipStart(); return !clip || hearsClip(url, clip) } })- serverKey = key- }- return server+ const have = servers.get(slot)+ if (have?.key === key) return have.srv+ void have?.srv.stop()+ // Parakeet: Metal on a Mac; on Windows and Linux always the processor, where it was timed (never Vulkan, which nobody measured)+ const srv = make ? make(model, pidFile)+ : slot === 'parakeet' ? createWhisperServer({ binary: parakeetServerPath(), engine: 'parakeet', model, pidFile, cpuOnly: process.platform !== 'darwin' })+ : createWhisperServer({ binary: whisperServerPath(), model, pidFile, vadModel: vadModelPath(), gpuFallback: process.platform !== 'darwin' && !o.keepCpu, cpuOnly: o.cpuOnly || o.keepCpu, onGpuOff: () => gpuOffListener?.(), checkGpu: async (url) => { const clip = clipStart(); return !clip || hearsClip(url, clip) } })+ servers.set(slot, { srv, key })+ return srv}/** no meeting left to transcribe: whisper-server's memory goes back to the Mac after a while */function armServerIdle() {clearTimeout(idleTimer)- if (sessions.size || !server) return+ if (sessions.size || !servers.size) returnidleTimer = setTimeout(() => {- if (sessions.size || !server) return- const s = server- server = undefined; serverKey = undefined- void s.stop().catch((e) => console.error('stopping whisper-server failed', e))+ if (sessions.size) return+ const all = [...servers.values()]+ servers.clear()+ for (const s of all) void s.srv.stop().catch((e) => console.error('stopping a speech server failed', e))}, idleMs)}@@ -201,7 +217,23 @@ export function hookTranscription(p: {transcriber?: ((c: Chunk, heard?: (language: string, chars: number, locked?: boolean) => void, o?: { partial?: boolean }) => Promise<Line[]> | Line[]) | undefinedonStart?: (fn: (m: Meeting) => void) => unknownonStop?: (fn: (m: Meeting) => void) => unknown- /** for tests: a stand-in whisper-server, and how long it stays up after the last meeting */+ /**+ * Parakeet for the languages it covers, once setup has it downloaded and checked (and fast enough here): its model, and+ * the small whisper that hears which language a track is in. Nothing: whisper reads everything, as before.+ */+ parakeet?: () => { model: string; lid: string } | undefined+ /** why Parakeet is switched off (YOGURT_ASR=whisper), for the log; null: it is not */+ parakeetOff?: () => string | null+ /** a track was heard in a language Parakeet doesn't cover: a bigger whisper may be fetched for the next meetings */+ uncovered?: (language: string) => void+ /** whisper has to read where Parakeet should have (parakeet-server failed): the bigger whisper is fetched where it is missing */+ wantWhisper?: () => void+ /**+ * a live meeting has a track read by the small whisper only because the bigger one is not downloaded yet: once that+ * is in, the meeting is read again from its recording+ */+ weakWhisper?: (meetingId: string) => void+ /** for tests: a stand-in whisper-server (and parakeet-server), and how long it stays up after the last meeting */server?: (model: string, pidFile?: string) => WhisperServerserverIdleMs?: number/** who said a line of the other side, as the call app showed it (callNames); null: Them */@@ -251,7 +283,8 @@ export function hookTranscription(p: {const promptOf = () => { const m = p.store.meeting?.(id); return m ? whisperPrompt(meetingWords(m)) : '' }if (p.transcriber) { const f = p.transcriber; transcribe = async (c, o) => f(c, (l, n, locked) => hear(l, n, locked), o) }// fake mode's stand-in is loaded only in fake mode, so it stays out of what real runs load- else if (isFake()) transcribe = async (c, o) => (await import('./fake')).fakeTranscribe(c, o, promptOf(), whisperLanguage(spokenNow()))+ // (the fixtures are in English, so with Parakeet there it reads them in either mode)+ else if (isFake()) transcribe = async (c, o) => (await import('./fake')).fakeTranscribe(c, o, promptOf(), whisperLanguage(spokenNow()), engineFor({ parakeet: !!p.parakeet?.(), language: 'en' }).engine)else {const model = p.modelPath()if (model) {@@ -260,8 +293,24 @@ export function hookTranscription(p: {srv.resetBudget()// no other meeting on it: a graphics card set aside earlier gets another chance (#156: it stayed off until a restart)if (!sessions.size) srv.gpuAgain(later ? 'a saved recording' : 'a new meeting')- // the model takes a few seconds to load: start now, so the first chunk does not wait for it (not for a meeting read after it ends)- if (later || !p.afterMeeting?.()) srv.url().catch((e) => console.error('whisper-server did not start', e))+ const pk = parakeetTrouble ? undefined : p.parakeet?.()+ const told = options?.language ?? whisperLanguage(spokenNow())+ const pidBeside = (name: string) => (p.pidFile ? join(dirname(p.pidFile), name) : undefined)+ const pkSrv = pk && serverFor(pk.model, pidBeside('parakeet-server.pid'), p.server, { slot: 'parakeet' })+ // the small whisper, where the main one is a bigger model: on the processor on Windows and Linux (it is tiny, and the graphics card stays the main whisper's)+ const lidSrv = pk && pk.lid !== model ? serverFor(pk.lid, pidBeside('whisper-server-lid.pid'), p.server, { slot: 'lid', keepCpu: process.platform !== 'darwin' }) : undefined+ pkSrv?.resetBudget(); lidSrv?.resetBudget()+ // which engine and why, for reports: the kill switch, Parakeet not there yet, or who reads what+ console.info('ASR', `${later ? 'a saved recording' : 'meeting start'}: ${!pk ? `whisper (${basename(model)}) reads every language: ${p.parakeetOff?.() ?? (parakeetTrouble && `parakeet-server failed earlier (${parakeetTrouble}); it is tried again when Yogurt is next started`) ?? 'Parakeet is not in use on this computer (not downloaded and checked yet, or too slow here)'}`+ : told ? (parakeetCovers(told) ? `Parakeet (${basename(pk.model)}) reads both tracks, the language is given as ${told}; whisper (${basename(model)}) stands by` : `whisper (${basename(model)}) reads both tracks: Parakeet does not know ${told}`)+ : `Multi-language: whisper (${basename(pk.lid)}) hears each track's language first, then Parakeet (${basename(pk.model)}) reads the languages it covers and whisper (${basename(model)}) the rest`}`)+ // the models take a few seconds to load: start now, so the first chunk does not wait for them (not for a meeting read after it ends)+ if (!pk) { if (later || !p.afterMeeting?.()) srv.url().catch((e) => console.error('whisper-server did not start', e)) }+ else {+ if (!told || parakeetCovers(told)) pkSrv!.url().catch((e) => console.error('parakeet-server did not start', e))+ // the whisper that hears languages (Multi-language only); the bigger one starts when a track needs it+ if (!told) (lidSrv ?? srv).url().catch((e) => console.error('whisper-server did not start', e))+ }const pauseLive = (why: string) => {if (s.pipeline?.paused()) returnconsole.warn(`ASR ${why}: live transcription pauses, and the saved recording finishes the transcript after the meeting`)@@ -293,7 +342,31 @@ export function hookTranscription(p: {}// relaunches spent: nothing more goes to whisper this meetingconst gaveUp = () => { if (!later) pauseLive('whisper-server will not be started again this meeting') }- transcribe = createTranscriber({ url: () => srv.url(), recover: (reason, used) => recoverer(srv, { slow: tooSlow, gaveUp })(reason, used),+ /** a server beside the main whisper: on the processor and slower than the audio, live transcription pauses (the recording finishes it) */+ const beside = (x: WhisperServer, name: string): Target => {+ const slow = () => { if (!later && x.tooSlow) pauseLive(`${name} on the processor reads at ${x.cpuRtf ? `${x.cpuRtf.toFixed(2)} x` : 'more than'} the audio's length`) }+ return { url: () => x.url(), recover: (reason, used) => recoverer(x, { slow, gaveUp: () => { if (!later) pauseLive(`${name} will not be started again this meeting`) } })(reason, used),+ timeoutMs: (n) => (later && x.cpuOnly ? Math.max(x.timeoutMs(n), Math.round((n / 16) * 10)) : x.timeoutMs(n)), onTimed: (n, ms, used) => { x.timed(n, ms, used); slow() } }+ }+ // parakeet-server that can't be brought back pauses nothing: the transcriber hands its chunks, then its track, to whisper+ const pkTarget = pkSrv && { ...beside(pkSrv, 'parakeet-server'), recover: (reason: 'gone' | 'timeout', used?: string) => recoverer(pkSrv, { slow: () => { if (!later && pkSrv.tooSlow) pauseLive('parakeet-server on the processor is slower than the audio') } })(reason, used) }+ const parakeet = pkTarget && {+ ...pkTarget, ...(lidSrv ? { lid: beside(lidSrv, 'whisper-server') } : {}),+ onFailed: (f: { track: Track; error: unknown; never: boolean }) => {+ const why = f.error instanceof Error ? f.error.message : String(f.error)+ if (f.never && !parakeetTrouble) { parakeetTrouble = why; console.warn('ASR', `parakeet-server never answered in this meeting (${why}): the next meetings start on whisper, and it is tried again when Yogurt is next started`) }+ try { p.wantWhisper?.() } catch (e) { console.error('asking for the bigger whisper failed', e) }+ },+ onEngine: (track: Track, engine: string, why: string) => {+ console.info('ASR', `${track}: ${engine === 'parakeet' ? 'Parakeet' : 'whisper'} reads this track: ${why}`)+ // the small whisper is all there is yet: this meeting is read again once the bigger one is in+ if (engine === 'whisper' && !later && pk!.lid === model) { try { p.weakWhisper?.(id) } catch (e) { console.error('noting a meeting to read again failed', e) } }+ // whisper can't keep up live on this computer (the speed check): the track's meeting is read from its recording+ if (engine === 'whisper' && !later && p.afterMeeting?.()) pauseLive(`whisper reads the ${track} track (${why}) and can't keep up live on this computer`)+ },+ onUncovered: (language: string) => { try { p.uncovered?.(language) } catch (e) { console.error('noting a language Parakeet does not cover failed', e) } },+ }+ transcribe = createTranscriber({ ...(parakeet ? { parakeet } : {}), url: () => srv.url(), recover: (reason, used) => recoverer(srv, { slow: tooSlow, gaveUp })(reason, used),// a saved recording has no hurry: on the processor a request may take 10 times its audiotimeoutMs: (n) => (later && srv.cpuOnly ? Math.max(srv.timeoutMs(n), Math.round((n / 16) * 10)) : srv.timeoutMs(n)),onTimed: (n, ms, used) => { srv.timed(n, ms, used); tooSlow() },@@ -353,8 +426,8 @@ export function hookTranscription(p: {}if (s.speech) s.pipeline?.setQuickReads(false)// the speed check found no speech model that keeps up live here: the meeting is recorded, and the saved recording- // gives the transcript once it ends (never a refusal to record)- if (!later && s.pipeline && p.afterMeeting?.()) {+ // gives the transcript once it ends (never a refusal to record). Not with Parakeet, which only reads live where it keeps up.+ if (!later && s.pipeline && p.afterMeeting?.() && !p.parakeet?.()) {console.info('ASR this computer transcribes meetings after they end: live transcription is off')s.pipeline.pause()setTimeout(() => warnOnce('live-paused'), NO_MODEL_NOTE_DELAY_MS)@@ -537,11 +610,11 @@ export async function settleTranscription(capMs = 20_000): Promise<void> {* load next to it (a 24 GB Mac froze with both loaded). Never while a meeting or a saved recording is being transcribed.*/export async function releaseIdleSpeech(): Promise<void> {- if (sessions.size || !server) return+ if (sessions.size || !servers.size) returnclearTimeout(idleTimer)- const s = server- server = undefined; serverKey = undefined- await s.stop().catch((e) => console.error('stopping whisper-server failed', e))+ const all = [...servers.values()]+ servers.clear()+ await Promise.all(all.map((s) => s.srv.stop().catch((e) => console.error('stopping a speech server failed', e))))}-export function stopTranscriptionServer() { clearTimeout(idleTimer); server?.kill(); server = undefined; serverKey = undefined }+export function stopTranscriptionServer() { clearTimeout(idleTimer); for (const s of servers.values()) s.srv.kill(); servers.clear() }diff --git a/app/src/main/asr/parakeet.ts b/app/src/main/asr/parakeet.tsnew file mode 100644index 00000000..317e37e9--- /dev/null+++ b/app/src/main/asr/parakeet.ts@@ -0,0 +1,147 @@+/**+ * Parakeet TDT 0.6B v3 (NVIDIA, CC-BY-4.0; run by parakeet-server, the pinned whisper.cpp's own parakeet.h) reads the 25+ * European languages it was trained on better and far faster than whisper. Every other language comes out of it as+ * Latin gibberish, so whisper keeps those. This file is the plain logic: which languages, what its tokens turn into,+ * and how to tell it is reading a language it doesn't know.+ */++/** the languages Parakeet v3 covers: their codes and whisper's names for them (its guesses name languages in full) */+export const PARAKEET_LANGUAGES: Readonly<Record<string, string>> = {+ bg: 'bulgarian', hr: 'croatian', cs: 'czech', da: 'danish', nl: 'dutch', en: 'english', et: 'estonian', fi: 'finnish', fr: 'french',+ de: 'german', el: 'greek', hu: 'hungarian', it: 'italian', lv: 'latvian', lt: 'lithuanian', mt: 'maltese', pl: 'polish',+ pt: 'portuguese', ro: 'romanian', sk: 'slovak', sl: 'slovenian', es: 'spanish', sv: 'swedish', ru: 'russian', uk: 'ukrainian',+}+const NAMES = new Set(Object.values(PARAKEET_LANGUAGES))++/** Does Parakeet know this language? A code ("de"), a locale ("de-AT") or whisper's name for it ("german"). */+export function parakeetCovers(language: string | null | undefined): boolean {+ if (!language) return false+ const l = language.trim().toLowerCase()+ return NAMES.has(l) || Object.hasOwn(PARAKEET_LANGUAGES, l.split(/[-_]/)[0])+}++/** YOGURT_ASR=whisper, or "asr": "whisper" in settings.json: Parakeet is never used, as before it existed */+export function asrKillSwitch(env: Record<string, string | undefined>, settings: { asr?: unknown } = {}): string | null {+ if (env.YOGURT_ASR?.trim().toLowerCase() === 'whisper') return 'YOGURT_ASR=whisper'+ if (typeof settings.asr === 'string' && settings.asr.trim().toLowerCase() === 'whisper') return '"asr": "whisper" in settings.json'+ return null+}++export type Engine = 'parakeet' | 'whisper'+/**+ * Who reads a track: Parakeet when it is there and the language (the one the person picked, or the one the track was+ * heard in) is one of its 25; whisper for every other language, for a track Parakeet read as gibberish, and while the+ * language is not known yet. `why` goes in the log.+ */+export function engineFor(o: { /** Parakeet is downloaded, checked and allowed here */ parakeet: boolean; /** picked or heard; none: not known yet */ language?: string | null; /** Parakeet wrote gibberish on this track */ fellBack?: boolean }): { engine: Engine; why: string } {+ if (!o.parakeet) return { engine: 'whisper', why: 'Parakeet is not in use here' }+ if (o.fellBack) return { engine: 'whisper', why: 'Parakeet could not read this track' }+ if (!o.language) return { engine: 'whisper', why: 'the language is not known yet' }+ return parakeetCovers(o.language) ? { engine: 'parakeet', why: `Parakeet knows ${o.language}` } : { engine: 'whisper', why: `Parakeet does not know ${o.language}` }+}++/** a token as parakeet-server gives it: SentencePiece text ("▁Hello", "ver", ","), seconds into the audio, log-probability */+export type ParakeetToken = { text: string; start: number; end: number; logprob: number }+/** a line as whisper-server's verbose_json has it, so everything after reads both the same way */+export type HeardSegment = { start: number; end: number; text: string; words?: Array<{ word: string; start: number; end: number }> }++const SPACE = '▁'+const SENTENCE_END = /[.?!…]["'”’)\]]*$/++/**+ * Parakeet gives one run of tokens for a chunk. Words are tokens up to the next one that starts with a space, each with+ * its own times; a line ends where a sentence does. Texts start with a space, like whisper's segments and words.+ */+export function parakeetSegments(tokens: ParakeetToken[]): HeardSegment[] {+ const words: Array<{ word: string; start: number; end: number }> = []+ for (const t of tokens) {+ // control pieces (<unk>, <|…|>) are not text+ if (!t.text || /^<.*>$/.test(t.text)) continue+ const text = t.text.replaceAll(SPACE, ' ')+ const last = words.at(-1)+ if (last && !text.startsWith(' ')) { last.word += text; last.end = Math.max(last.end, t.end); continue }+ if (!text.trim()) continue+ words.push({ word: text.startsWith(' ') ? text : ` ${text}`, start: t.start, end: t.end })+ }+ const out: HeardSegment[] = []+ let open: HeardSegment | undefined+ for (const w of words) {+ if (!open) { open = { start: w.start, end: w.end, text: '', words: [] }; out.push(open) }+ open.text += w.word+ open.end = Math.max(open.end, w.end)+ open.words!.push(w)+ if (SENTENCE_END.test(w.word)) open = undefined+ }+ return out+}++/** under this mean log-probability per token, or this many tokens a second, Parakeet is guessing */+export const GARBAGE_LOGPROB = -0.2+export const GARBAGE_TOKENS_PER_S = 1.5+/** a chunk counts for or against the track only when it is this long: shorter ones are flagged by chance (9 of 80 at 5 s, 4 of 80 at 10 s) */+export const GARBAGE_MIN_MS = 5000+/** and someone is clearly talking in it (the chunker's clearMs), not a long faint sound */+export const GARBAGE_MIN_CLEAR_MS = 1000+/** Is this chunk enough to judge Parakeet's reading by? */+export const judgeable = (c: { samples: { length: number }; clearMs?: number }): boolean => c.samples.length / 16 >= GARBAGE_MIN_MS && (c.clearMs ?? 0) >= GARBAGE_MIN_CLEAR_MS+/** this many such chunks in a row and the track goes back to whisper */+export const GARBAGE_CHUNKS = 3++/**+ * Is Parakeet reading a language it doesn't know? Its tokens are then unsure (a low mean log-probability) or few for+ * the time. On whole chunks of about 10 s this flagged every clip of a language it doesn't cover and none it does.+ */+export function garbageSignal(tokens: ParakeetToken[], seconds: number): { flagged: boolean; meanLogprob: number | null; tokensPerSecond: number } {+ const meanLogprob = tokens.length ? tokens.reduce((n, t) => n + t.logprob, 0) / tokens.length : null+ const tokensPerSecond = seconds > 0 ? tokens.length / seconds : 0+ return { flagged: meanLogprob === null || meanLogprob < GARBAGE_LOGPROB || tokensPerSecond < GARBAGE_TOKENS_PER_S, meanLogprob, tokensPerSecond }+}++/**+ * Counts bad chunks in a row per track: ones Parakeet read like a language it doesn't know, and in which whisper heard+ * such a language too (a noisy room alone makes Parakeet unsure now and then). A good one starts the count again.+ * true: that was the last straw, the track goes back to whisper (and the count starts over).+ */+export function garbageWatch<T extends string = string>() {+ const row = new Map<T, number>()+ return {+ saw(track: T, bad: boolean): boolean {+ if (!bad) { row.set(track, 0); return false }+ const n = (row.get(track) ?? 0) + 1+ row.set(track, n >= GARBAGE_CHUNKS ? 0 : n)+ return n >= GARBAGE_CHUNKS+ },+ reset(track: T) { row.set(track, 0) },+ }+}++const RATE = 16000+/** Parakeet drops sentences on long audio in one pass: never more than this at once */+export const PARAKEET_MAX_PASS_S = 15+const WIN = RATE / 10+/** where a cut may fall: the quietest 100 ms of the last 2 s of a pass */+const SEARCH_S = 2++/**+ * The audio in passes of 15 s at most, cut at the quietest 100 ms of each pass's last 2 s (as the chunker cuts a long+ * chunk). The chunker never gives more than 15 s, so this is one pass nearly always; it is here so nothing longer can+ * ever reach Parakeet (the speed check's clip, a caller that forgot).+ */+export function parakeetPasses(samples: Float32Array): Array<{ offset: number; samples: Float32Array }> {+ const max = PARAKEET_MAX_PASS_S * RATE+ const out: Array<{ offset: number; samples: Float32Array }> = []+ let at = 0+ while (samples.length - at > max) {+ const from = at + max - SEARCH_S * RATE+ let cut = at + max, quietest = Infinity+ for (let w = from; w + WIN <= at + max; w += WIN) {+ let e = 0+ for (let i = w; i < w + WIN; i++) e += samples[i] * samples[i]+ if (e < quietest) { quietest = e; cut = w + WIN / 2 }+ }+ out.push({ offset: at, samples: samples.subarray(at, cut) })+ at = cut+ }+ if (samples.length > at || !out.length) out.push({ offset: at, samples: samples.subarray(at) })+ return out+}diff --git a/app/src/main/asr/reread.ts b/app/src/main/asr/reread.tsnew file mode 100644index 00000000..53778bd1--- /dev/null+++ b/app/src/main/asr/reread.ts@@ -0,0 +1,43 @@+/**+ * On a new install the only whisper is the small one that hears languages; the bigger one is fetched when a language+ * Parakeet doesn't cover turns up. The meeting it turned up in was read by the small one meanwhile. Those meetings are+ * remembered here, and once the bigger whisper is in and the meeting has ended, each is read again from its recording+ * (the same way as Transcribe again), so its transcript ends up as good as it would have been.+ */+export function createRereads(d: {+ /** the meetings waiting, kept across restarts */+ load(): string[]+ save(ids: string[]): void+ /** the bigger whisper is downloaded and in use */+ ready(): boolean+ /** null: the meeting is gone. busy: still recording or being transcribed. audio: its recording is there to read */+ meeting(id: string): { busy: boolean; audio: boolean } | null+ /** read it again from its recording; false: not now */+ start(id: string): boolean | Promise<boolean>+}) {+ /** started here and not asked about yet */+ const started = new Set<string>()+ let running = false+ return {+ note(id: string) { const ids = d.load(); if (!ids.includes(id)) d.save([...ids, id]) },+ /** start what can be started now; called when the bigger whisper lands, when a meeting ends, and at start-up */+ async run() {+ if (running || !d.ready()) return+ running = true+ try {+ for (const id of d.load()) {+ const m = d.meeting(id)+ if (m?.busy) continue+ let done = !m || !m.audio+ if (!done) {+ try { done = await d.start(id) } catch (e) { console.error('reading a meeting again failed to start', id, e) }+ if (done) { started.add(id); console.info('ASR', `meeting ${id} was read by the small whisper while the bigger one downloaded: it is read again from its recording`) }+ }+ if (done) d.save(d.load().filter((x) => x !== id))+ }+ } finally { running = false }+ },+ /** was this meeting's new transcript one of these re-reads? (true once) */+ reread(id: string): boolean { return started.delete(id) },+ }+}diff --git a/app/src/main/asr/server.ts b/app/src/main/asr/server.tsindex 945fb5f3..f6d640ff 100644--- a/app/src/main/asr/server.ts+++ b/app/src/main/asr/server.ts@@ -47,6 +47,18 @@ const freePort = (): Promise<number> => new Promise((resolve, reject) => {const windowsName = (pid: number): string | null =>execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true }).match(/^"([^"]+)"/m)?.[1] ?? null+/** Parakeet's server (native/parakeet-server), next to whisper-server: the same whisper.cpp, its parakeet.h */+export function parakeetServerPath(): string {+ const file = helperFile('parakeet', process.platform)+ const candidates = [+ process.resourcesPath && join(process.resourcesPath, 'bin', file),+ join(__dirname, '../../resources/bin', file),+ join(__dirname, '../../../resources/bin', file),+ join(__dirname, '../../../../resources/bin', file),+ ].filter((x): x is string => !!x)+ return candidates.find((c) => existsSync(c)) ?? candidates.at(-1)!+}+/** How a left-over process is looked up and killed; tests stand in for it */export type ProcessLookup = { name(pid: number): string | null; kill(pid: number): void }const realLookup: ProcessLookup = {@@ -54,9 +66,11 @@ const realLookup: ProcessLookup = {kill: (pid) => { try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ } },}+/** the speech programs Yogurt starts: a left-over one of either is cleaned up */+const SERVERS = ['whisper-server', 'parakeet-server']/**- * A whisper-server left over from a Yogurt that was killed would hold memory and a port forever.- * The pid file names it; it is killed only if that pid is still a program called whisper-server (pids get reused).+ * A whisper-server (or parakeet-server) left over from a Yogurt that was killed would hold memory and a port forever.+ * The pid file names it; it is killed only if that pid is still a program called that (pids get reused).*/export function killStale(pidFile: string, deps: ProcessLookup = realLookup) {let pid = NaN@@ -64,12 +78,14 @@ export function killStale(pidFile: string, deps: ProcessLookup = realLookup) {rmSync(pidFile, { force: true })if (!Number.isInteger(pid) || pid <= 1) returnconst name = deps.name(pid)- if (name && basename(name).replace(/\.exe$/i, '') === 'whisper-server') deps.kill(pid)+ if (name && SERVERS.includes(basename(name).replace(/\.exe$/i, ''))) deps.kill(pid)}type Opts = {binary: stringmodel: string+ /** parakeet: parakeet-server, which takes the model, the address and the threads, and has no VAD or beam */+ engine?: 'whisper' | 'parakeet'/** the VAD model: whisper skips what isn't speech */vadModel?: string/** how long loading the model may take before giving up (it takes seconds) */@@ -112,6 +128,8 @@ export const LIVE_CPU_RTF = 1const CPU_SAMPLES = 2export function createWhisperServer(o: Opts) {+ /** the program's name in the log and in errors */+ const name = o.engine === 'parakeet' ? 'parakeet-server' : 'whisper-server'let child: ChildProcess | null = nulllet starting: Promise<string> | null = nulllet address: string | null = null@@ -138,7 +156,7 @@ export function createWhisperServer(o: Opts) {cpuOnly = trueoffReason = `${why} (${new Date(now()).toISOString()})`cpuRtfs = []; slowOnCpu = 0- console.error(`whisper-server ${why}; starting it again without the graphics card`)+ console.error(`${name} ${why}; starting it again without the graphics card`)o.onGpuOff?.()}/** hangs on the graphics card (gpuFallback): the second one turns them off (#76) */@@ -153,11 +171,12 @@ export function createWhisperServer(o: Opts) {const port = await freePort()// beam 5, as in the model eval// 4 threads, never more than the computer has: with more, ggml's spinning threads made whisper 5 to 200 times slower- const args = ['-m', o.model, '--host', '127.0.0.1', '--port', String(port), '-t', String(o.threads ?? Math.min(4, availableParallelism())), '-bs', '5']- if (o.vadModel) args.push('--vad', '-vm', o.vadModel)+ const args = ['-m', o.model, '--host', '127.0.0.1', '--port', String(port), '-t', String(o.threads ?? Math.min(4, availableParallelism()))]+ if (o.engine !== 'parakeet') args.push('-bs', '5')+ if (o.vadModel && o.engine !== 'parakeet') args.push('--vad', '-vm', o.vadModel)if (cpuOnly) args.push('-ng')// which model goes in the log too: a report of poor transcripts needs to know if a smaller model was picked (#107)- console.info('ASR', `whisper-server starts with ${basename(o.model)} on ${cpuOnly ? 'the processor' : 'the graphics card if it can'}`)+ console.info('ASR', `${name} starts with ${basename(o.model)} on ${cpuOnly ? 'the processor' : 'the graphics card if it can'}`)const p = spawn(o.binary, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })launches++child = p@@ -168,12 +187,12 @@ export function createWhisperServer(o: Opts) {let told = falsep.stderr?.on('data', (d: Buffer) => {err = (err + d.toString()).slice(-2000)- const dev = !told && err.match(/whisper_backend_init_gpu: using (\S+) backend/)?.[1]- if (dev) { told = true; console.info('ASR', `whisper-server runs on ${dev}`) }+ const dev = !told && err.match(/(?:whisper|parakeet)_backend_init_gpu: using (\S+) backend/)?.[1]+ if (dev) { told = true; console.info('ASR', `${name} runs on ${dev}`) }})const gone = new Promise<never>((_, reject) => {- p.once('error', (e) => reject(new Error(`whisper-server could not start: ${e.message}`)))- p.once('exit', (code, sig) => reject(new Error(`whisper-server exited (${code ?? sig}) ${err.split('\n').filter(Boolean).slice(-2).join(' | ')}`.trim())))+ p.once('error', (e) => reject(new Error(`${name} could not start: ${e.message}`)))+ p.once('exit', (code, sig) => reject(new Error(`${name} exited (${code ?? sig}) ${err.split('\n').filter(Boolean).slice(-2).join(' | ')}`.trim())))})gone.catch(() => {})p.once('exit', () => {@@ -188,7 +207,7 @@ export function createWhisperServer(o: Opts) {try { if ((await fetch(url + '/', { signal: AbortSignal.timeout(2000) })).ok) return url } catch { /* not up yet */ }await new Promise((r) => setTimeout(r, 150))}- throw new Error('whisper-server did not start in time')+ throw new Error(`${name} did not start in time`)})()let up: stringtry { up = await Promise.race([healthy, gone]) } catch (e) {@@ -199,7 +218,7 @@ export function createWhisperServer(o: Opts) {}if (o.gpuFallback && !cpuOnly && o.checkGpu) {let hears = true- try { hears = await o.checkGpu(up) } catch (e) { console.warn('whisper-server: checking the graphics card failed', e) }+ try { hears = await o.checkGpu(up) } catch (e) { console.warn(`${name}: checking the graphics card failed`, e) }if (!hears) {gpuOff('heard no words on the graphics card')if (child === p) { child = null; died = false }@@ -227,7 +246,7 @@ export function createWhisperServer(o: Opts) {let wait = 0if (died) {if (used && now() - lastRelaunch >= HEALTHY_RESET_MS) used = 0- if (used >= backoff.length) return Promise.reject(new Error('whisper-server stopped and will not be started again this meeting'))+ if (used >= backoff.length) return Promise.reject(new Error(`${name} stopped and will not be started again this meeting`))wait = backoff[used]used++lastRelaunch = now()@@ -244,7 +263,7 @@ export function createWhisperServer(o: Opts) {*/gpuAgain(why: string): boolean {if (!o.gpuFallback || !cpuOnly || starting) return false- console.info('ASR', `whisper-server tries the graphics card again for ${why}; it was set aside because it ${offReason || 'failed earlier'}`)+ console.info('ASR', `${name} tries the graphics card again for ${why}; it was set aside because it ${offReason || 'failed earlier'}`)cpuOnly = false; gpuHangs = 0; cpuRtfs = []; slowOnCpu = 0const p = childif (p) { ended.add(p); child = null; address = null; p.kill('SIGKILL') }diff --git a/app/src/main/asr/speedCheck.ts b/app/src/main/asr/speedCheck.tsindex 0706349c..23085aeb 100644--- a/app/src/main/asr/speedCheck.ts+++ b/app/src/main/asr/speedCheck.ts@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path'import { AFTER_MEETING_RTF } from '@yogurt/picker'import type { SpeedDeps, SpeedResult } from '../setup'import { createWhisperServer, type WhisperServer } from './server'-import { createTranscriber } from './transcribe'+import { createParakeetReader, createTranscriber } from './transcribe'/*** Windows and Linux: how fast whisper reads speech on this computer, timed once at setup on a bundled clip with the app's@@ -44,8 +44,14 @@ type MeasureOpts = {cpu?: boolean/** for tests and the CI smoke: another launcher */server?: (model: string) => WhisperServer+ /** where the program's pid is kept while it is timed, so one left running by a quit is cleaned up later */+ pidFile?: string}+/** the servers being timed right now: quitting takes them along */+const timing = new Set<WhisperServer>()+export function stopTiming() { for (const s of timing) s.kill(); timing.clear() }+/*** The realtime factor of one careful (beam 5) reading of the clip: time taken over its length. The first 3 s are read* once beforehand, so loading and the graphics' first-run work are not counted. A reading that takes longer than@@ -53,9 +59,10 @@ type MeasureOpts = {* meeting, #107).*/export async function measureSpeed(model: string, o: MeasureOpts): Promise<{ rtf: number | null; gpuOff: boolean }> {- const srv = o.server?.(model) ?? createWhisperServer({ binary: o.binary, model, vadModel: o.vadModel, gpuFallback: !o.cpu, cpuOnly: o.cpu, startTimeoutMs: 180_000, backoffMs: [0], checkGpu: (url) => hearsClip(url, readWav(readFileSync(o.clip)).subarray(0, 5 * 16000)) })+ const srv = o.server?.(model) ?? createWhisperServer({ binary: o.binary, model, pidFile: o.pidFile, vadModel: o.vadModel, gpuFallback: !o.cpu, cpuOnly: o.cpu, startTimeoutMs: 180_000, backoffMs: [0], checkGpu: (url) => hearsClip(url, readWav(readFileSync(o.clip)).subarray(0, 5 * 16000)) })const samples = readWav(readFileSync(o.clip))const clipMs = samples.length / 16+ timing.add(srv)try {// a server that dies loading on the graphics card is started once more on the processor (gpuFallback)await srv.url().catch(() => srv.url())@@ -69,6 +76,38 @@ export async function measureSpeed(model: string, o: MeasureOpts): Promise<{ rtf}return { rtf: Math.round(((performance.now() - t0) / clipMs) * 1000) / 1000, gpuOff: srv.cpuOnly }} finally {+ timing.delete(srv)+ await srv.stop()+ }+}++/**+ * Parakeet's realtime factor, by the rules the whisper models are timed with: the same clip, the app's own launcher and+ * request, the same threads, the first 3 s read once beforehand, stopped at AFTER_MEETING_RTF times the clip (null).+ * Run the way meetings will run it: cpu on Windows and Linux (the processor alone), not on a Mac (Metal), where this+ * is the try that says Parakeet works here at all. A reading without the clip's words is null too: a Parakeet that+ * doesn't work here is never picked. Throws when the program won't start or stops answering.+ */+export async function measureParakeet(model: string, o: { binary: string; clip: string; cpu?: boolean; pidFile?: string; server?: (model: string) => WhisperServer }): Promise<number | null> {+ const srv = o.server?.(model) ?? createWhisperServer({ binary: o.binary, model, engine: 'parakeet', cpuOnly: !!o.cpu, pidFile: o.pidFile, startTimeoutMs: 180_000, backoffMs: [0] })+ const samples = readWav(readFileSync(o.clip))+ const clipMs = samples.length / 16+ timing.add(srv)+ try {+ await srv.url()+ await createParakeetReader({ url: () => srv.url(), timeoutMs: 120_000 })({ track: 'them', startMs: 0, samples: samples.subarray(0, 3 * 16000) })+ const read = createParakeetReader({ url: () => srv.url(), timeoutMs: Math.round(clipMs * AFTER_MEETING_RTF) })+ const t0 = performance.now()+ let heard = ''+ try { heard = (await read({ track: 'them', startMs: 0, samples })).text } catch (e) {+ if (e instanceof Error && e.name === 'TimeoutError') return null+ throw e+ }+ const rtf = Math.round(((performance.now() - t0) / clipMs) * 1000) / 1000+ if (heard.trim().split(/\s+/).filter(Boolean).length < 2) { console.warn('speed check: Parakeet heard no words in the clip'); return null }+ return rtf+ } finally {+ timing.delete(srv)await srv.stop()}}@@ -105,6 +144,16 @@ export function speedStore(file: string): Pick<SpeedDeps, 'load' | 'save'> & { f* Fake mode: YOGURT_FAKE_RTF gives every model that time ("2"), or some of them ("whisper-small-q5_1=0.9,whisper-tiny-q5_1=0.2",* the rest 0.1); "slow" never finishes in time.*/+/** Fake mode: Parakeet's time the same way ("parakeet-tdt-0.6b-v3-q8_0=0.8" for it alone) */+export const fakeParakeetMeasure = (env = process.env.YOGURT_FAKE_RTF ?? '', trouble = process.env.YOGURT_FAKE_PARAKEET) => async (path: string): Promise<number | null> => {+ // YOGURT_FAKE_PARAKEET=broken: parakeet-server will not start here; deaf: it runs and hears nothing+ if (trouble === 'broken') throw new Error('parakeet-server could not start (fake)')+ if (trouble === 'deaf') return null+ return (await fakeMeasure(env)(path)).rtf+}+/** Fake mode on a Mac: its try has no time to fail on (YOGURT_FAKE_RTF is about Windows and Linux), only the trouble above */+export const fakeParakeetTry = (trouble = process.env.YOGURT_FAKE_PARAKEET) => fakeParakeetMeasure('', trouble)+export function fakeMeasure(env = process.env.YOGURT_FAKE_RTF ?? ''): SpeedDeps['measure'] {return async (path) => {const parse = (v: string) => (v === 'slow' ? null : Number(v))diff --git a/app/src/main/asr/transcribe.ts b/app/src/main/asr/transcribe.tsindex fb1684d1..3fbf2fb4 100644--- a/app/src/main/asr/transcribe.ts+++ b/app/src/main/asr/transcribe.ts@@ -5,6 +5,7 @@ import { languageName } from './appleSpeech'import { tokens } from './echo'import { joinSaid, unspaced } from '../../shared/said'import { isPromptEcho, isSilenceGuess, isSubtitleCredit, withoutPromptLabel } from './hallucination'+import { engineFor, garbageSignal, garbageWatch, GARBAGE_MIN_CLEAR_MS, judgeable, parakeetCovers, parakeetPasses, parakeetSegments, type Engine, type ParakeetToken } from './parakeet'/** What a chunk turns into: lines on meeting time. The meeting and the speaker are added where they are saved. */export type Line = Omit<Segment, 'id' | 'meetingId' | 'speaker'> & {@@ -65,16 +66,20 @@ export function wholeSegments(segments: Heard[]): Heard[] {return out}-type Opts = {+/** One speech server: where it is, and what to do when a request to it fails or finishes */+export type Target = {/** where the server is; starts it if need be */url: () => Promise<string>/** a request failed: bring the server back (true) or give up (false). Asked on each failed call; the server decides how often it agrees. */recover?: (reason: 'gone' | 'timeout', used?: string) => Promise<boolean>- signal?: AbortSignal/** how long one request may take before the server is taken to be hung (default: requestTimeoutMs), or how long for this many samples */timeoutMs?: number | ((samples: number) => number)/** a careful (not partial) request to the server at `used` finished, after ms: how fast it reads */onTimed?: (samples: number, ms: number, used?: string) => void+}++type Opts = Target & {+ signal?: AbortSignalfetchFn?: typeof fetch/** the language a chunk was heard in, and how much was said in it (the notes are written in the main one) *//** locked: the track already had a language lock when this chunk was heard (one odd chunk before the lock should change nothing) */@@ -83,6 +88,29 @@ type Opts = {prompt?: () => string/** the language to tell whisper on every chunk (English only), read each time so a change counts from the next one; none: detect */language?: () => string | undefined+ /**+ * Parakeet's server, for tracks in a language it covers (asr/parakeet.ts): English only goes straight to it; in+ * Multi-language whisper hears which language a track is in first. None: whisper reads everything, as before.+ */+ parakeet?: Target & {+ /**+ * a small whisper that hears which language a track is in while the main one (url, above) is a bigger model kept+ * for the languages Parakeet doesn't cover; none: the main whisper hears the language too+ */+ lid?: Target+ /** a track got its reader, or changed it: which, and why (for the log; whisper that can't keep up live pauses here) */+ onEngine?: (track: Track, engine: Engine, why: string) => void+ /**+ * a language Parakeet doesn't cover was clearly heard (whisper's name for it), told once per language as soon as+ * it is: on the first such chunk, or when a track falls off Parakeet over it. A bigger whisper may be fetched.+ */+ onUncovered?: (language: string) => void+ /**+ * parakeet-server failed twice in a row on a track (it won't start, crashed, or answers with an error), so whisper+ * has the track for the rest of the meeting. never: it did not answer once in this meeting.+ */+ onFailed?: (f: { track: Track; error: unknown; never: boolean }) => void+ }}/** a chunk takes well under its own length to transcribe: 4 times that (at least 30 s) means the server hung */@@ -94,6 +122,90 @@ const MIN_LOCK_TOKENS = 2/** how sure whisper must be that a locked track is now in another language, and how many lines in a row, to follow it */const SWITCH_PROB = 0.9const SWITCH_LINES = 2+/** failures of parakeet-server in a row on a track before whisper takes the track for the rest of the meeting */+export const PARAKEET_FAILURES = 2+/**+ * With Parakeet, the lock decides who reads the rest of the track, and the small whisper that hears the language is+ * only reliable on about 10 s of speech (every clip right at 10 s, 95.5% at 5 s): a track is locked once that much of+ * it was clearly heard in one language.+ */+export const PARAKEET_LOCK_MS = 10_000++/**+ * One request to a speech server's /inference, the server brought back and the request tried again when it crashed or+ * hung: twice at most (a graphics card that hangs twice moves to the processor on the second, #76, and the chunk still gets read).+ */+async function post(t: Target, samples: Float32Array, fields: Record<string, string>, o: { signal?: AbortSignal; fetchFn?: typeof fetch; timed?: boolean; name?: string }): Promise<unknown> {+ const fetchFn = o.fetchFn ?? fetch+ let used: string | undefined+ const send = async () => {+ // stopped already: nothing is sent+ o.signal?.throwIfAborted()+ const form = new FormData()+ form.set('file', new Blob([new Uint8Array(wavBytes(samples))], { type: 'audio/wav' }), 'chunk.wav')+ for (const [k, v] of Object.entries(fields)) form.set(k, v)+ used = await t.url()+ const ms = typeof t.timeoutMs === 'function' ? t.timeoutMs(samples.length) : t.timeoutMs ?? requestTimeoutMs(samples.length)+ return fetchFn(`${used}/inference`, { method: 'POST', body: form, signal: o.signal ? AbortSignal.any([o.signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms) })+ }+ let res: Response | undefined+ let t0 = 0+ for (let tries = 0; !res; tries++) {+ try { t0 = Date.now(); res = await send() } catch (err) {+ o.signal?.throwIfAborted()+ const reason = err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'gone'+ if (tries >= 2 || !(await t.recover?.(reason, used).catch(() => false))) throw err+ }+ }+ if (res.ok && o.timed) t.onTimed?.(samples.length, Date.now() - t0, used)+ // (the answer's body is let go, or it is still being received when the request's time runs out)+ if (!res.ok) { await res.body?.cancel().catch(() => {}); throw new Error(`${o.name ?? 'whisper-server'} answered ${res.status}`) }+ return res.json()+}++/** a server's segments as lines on meeting time, less what was never said (noise tags, the prompt read back, stock lines over a faint sound) */+function linesOf(c: Chunk, segments: Heard[], prompt: string): Line[] {+ // under 300 ms of clearly loud audio: a faint sound, where whisper's stock lines are made up+ const faint = c.clearMs !== undefined && c.clearMs < MIN_CLEAR_MS+ const lines: Line[] = []+ for (const s of wholeSegments(segments)) {+ const said = s.text.replace(/\s+/g, ' ').trim()+ // names from the prompt read back as a speaker label ("Eric and Sam Lee: so..."): the speech after it stays+ const text = withoutPromptLabel(said, prompt)+ if (!text || NOISE.test(text)) continue+ if ((s.no_speech_prob ?? 0) > 0.6 && (s.avg_logprob ?? 0) < -1) continue+ // read back from the prompt, or a stock line over a faint sound: whisper had nothing to read+ // a subtitle credit is never said in a meeting, faint or not+ if (isPromptEcho(text, prompt) || isSubtitleCredit(text) || (faint && isSilenceGuess(text))) continue+ // the label's words (through the one carrying its colon) go with it+ const kept = text === said ? s.words : s.words?.slice((s.words.findIndex((w) => w.word.includes(':')) + 1) || 0)+ const words = kept?.map((w) => ({ text: w.word, startMs: Math.round(c.startMs + w.start * 1000), endMs: Math.round(c.startMs + w.end * 1000) }))+ lines.push({ track: c.track, startMs: Math.round(c.startMs + s.start * 1000), endMs: Math.round(c.startMs + s.end * 1000), text, ...(words?.length ? { words } : {}) })+ }+ return lines+}++export type ParakeetReading = { lines: Line[]; text: string; /** it reads like a language Parakeet doesn't know (asr/parakeet.ts garbageSignal) */ flagged: boolean; meanLogprob: number | null; tokensPerSecond: number }++/**+ * Sends a chunk to parakeet-server and makes lines of its tokens: the same shape whisper's lines have (times on meeting+ * time, words with their own). Parakeet takes no prompt and has one way of reading, so a partial is the same request.+ * Never more than 15 s in one pass.+ */+export function createParakeetReader(t: Target, o: { signal?: AbortSignal; fetchFn?: typeof fetch } = {}): (c: Chunk, opt?: { partial?: boolean }) => Promise<ParakeetReading> {+ return async (c, opt) => {+ const tokens: ParakeetToken[] = []+ for (const pass of parakeetPasses(c.samples)) {+ const body = (await post(t, pass.samples, {}, { ...o, timed: !opt?.partial, name: 'parakeet-server' })) as { tokens?: ParakeetToken[] }+ const at = pass.offset / 16000+ for (const k of body.tokens ?? []) tokens.push({ text: String(k.text ?? ''), start: at + Number(k.start), end: at + Number(k.end), logprob: Number(k.logprob) })+ }+ const lines = linesOf(c, parakeetSegments(tokens), '')+ // tokens a second of clear speech where that is known: a chunk is cut at pauses of 1 s, so a slow talker's shorter pauses are in it+ const spoken = (c.clearMs ?? 0) >= GARBAGE_MIN_CLEAR_MS ? c.clearMs! / 1000 : c.samples.length / 16000+ return { lines, text: joinSaid(lines.map((l) => l.text)), ...garbageSignal(tokens, spoken) }+ }+}/*** Sends chunks to whisper-server's /inference. Auto-detecting the language on every short chunk flips on short sentences,@@ -101,95 +213,198 @@ const SWITCH_LINES = 2* An empty or garbled answer on a locked track asks again with the language open; the lock goes only if that hears something.* People switch languages too: whisper still guesses each chunk's language from the audio, so a line clearly in another* one is read again in it, and two such lines in a row move the lock (one, like a name or a quote, doesn't).+ *+ * With Parakeet (o.parakeet), the language decides who reads a track: Parakeet where it covers the language picked+ * (English only) or the one the track is locked on, whisper otherwise. A chunk Parakeet reads like a language it+ * doesn't know (5 s or more, flagged) is read by whisper instead; when whisper hears a language Parakeet doesn't cover+ * in a few of those in a row, the track goes back to whisper: for good when the language was picked, to be heard+ * again when it was detected.*/export function createTranscriber(o: Opts): Transcribe {- const fetchFn = o.fetchFn ?? fetchconst locked: Partial<Record<Track, string>> = {}/** lines in a row a locked track was clearly heard in another language */const strays: Partial<Record<Track, number>> = {}+ const pk = o.parakeet+ const readParakeet = pk && createParakeetReader(pk, { signal: o.signal, fetchFn: o.fetchFn })+ /** whisper that hears a track's language (and reads it meanwhile): the small one where there is one */+ const hears: Target = pk?.lid ?? o+ const watch = garbageWatch<Track>()+ /** tracks Parakeet could not read although their language was picked: whisper keeps them */+ const fell: Partial<Record<Track, boolean>> = {}+ /** with Parakeet: how much of an unlocked track was clearly heard in one language so far */+ const evidence: Partial<Record<Track, { language: string; ms: number }>> = {}+ const reader: Partial<Record<Track, Engine>> = {}+ /** parakeet-server's failures in a row per track, and whether it ever answered in this meeting */+ const failures: Partial<Record<Track, number>> = {}+ let answered = false+ const toldUncovered = new Set<string>()+ const uncovered = (language: string) => {+ if (!pk || toldUncovered.has(language)) return+ toldUncovered.add(language)+ try { pk.onUncovered?.(language) } catch (e) { console.error('noting a language Parakeet does not cover failed', e) }+ }+ const route = (track: Track, language: string | undefined): Engine => {+ const r = engineFor({ parakeet: !!pk, language, fellBack: fell[track] })+ // not known yet: whisper only hears the language, nobody has the track+ if (pk && language && reader[track] !== r.engine) { reader[track] = r.engine; try { pk.onEngine?.(track, r.engine, r.why) } catch (e) { console.error('telling who reads a track failed', e) } }+ return r.engine+ }- const call = async (c: Chunk, language: string, partial = false, guess = !partial): Promise<{ lines: Line[]; text: string; language: string; prob: number }> => {- let used: string | undefined+ const call = async (c: Chunk, language: string, partial = false, guess = !partial, target: Target = o): Promise<{ lines: Line[]; text: string; language: string; prob: number }> => {const prompt = o.prompt?.() ?? ''- // under 300 ms of clearly loud audio: a faint sound, where whisper's stock lines are made up- const faint = c.clearMs !== undefined && c.clearMs < MIN_CLEAR_MS- const send = async () => {- const form = new FormData()- form.set('file', new Blob([new Uint8Array(wavBytes(c.samples))], { type: 'audio/wav' }), 'chunk.wav')- form.set('response_format', 'verbose_json')- form.set('language', language)- form.set('temperature', '0.0')- form.set('no_timestamps', 'false')- // a partial is read once, greedily: a few times faster than the server's beam search, good enough for a first look- if (partial) { form.set('beam_size', '1'); form.set('best_of', '1') }- // a language guess nobody reads costs a second pass of the encoder, about a third of the request- if (!guess) form.set('no_language_probabilities', 'true')- if (prompt) form.set('prompt', prompt)- used = await o.url()- const ms = typeof o.timeoutMs === 'function' ? o.timeoutMs(c.samples.length) : o.timeoutMs ?? requestTimeoutMs(c.samples.length)- return fetchFn(`${used}/inference`, { method: 'POST', body: form, signal: o.signal ? AbortSignal.any([o.signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms) })- }- let res: Response | undefined- let t0 = 0- // the server crashed or hung: it is brought back and the chunk tried again, twice at most (a graphics card that hangs- // twice moves to the processor on the second, #76, and the chunk still gets read)- for (let tries = 0; !res; tries++) {- try { t0 = Date.now(); res = await send() } catch (err) {- o.signal?.throwIfAborted()- const reason = err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'gone'- if (tries >= 2 || !(await o.recover?.(reason, used).catch(() => false))) throw err+ const fields: Record<string, string> = { response_format: 'verbose_json', language, temperature: '0.0', no_timestamps: 'false' }+ // a partial is read once, greedily: a few times faster than the server's beam search, good enough for a first look+ if (partial) { fields.beam_size = '1'; fields.best_of = '1' }+ // a language guess nobody reads costs a second pass of the encoder, about a third of the request+ if (!guess) fields.no_language_probabilities = 'true'+ if (prompt) fields.prompt = prompt+ const body = (await post(target, c.samples, fields, { signal: o.signal, fetchFn: o.fetchFn, timed: !partial })) as Verbose+ const lines = linesOf(c, body.segments ?? [], prompt)+ return { lines, text: joinSaid(lines.map((l) => l.text)), language: body.detected_language ?? body.language ?? 'auto', prob: body.detected_language_probability ?? 0 }+ }++ /**+ * Parakeet's reading of a finished chunk, or null when whisper should read it instead: it reads like a language+ * Parakeet doesn't know, and the chunk is long enough to say so (5 s, with someone clearly talking).+ */+ /**+ * Parakeet's reading, or 'failed' when parakeet-server would not give one (it won't start, crashed, answered with an+ * error): whisper then reads the chunk, so no audio goes unread over it. Two failures in a row and whisper keeps the+ * track for the rest of the meeting.+ */+ const tryParakeet = async (c: Chunk, opt?: { partial?: boolean }): Promise<ParakeetReading | 'failed'> => {+ try {+ const p = await readParakeet!(c, opt)+ failures[c.track] = 0+ answered = true+ return p+ } catch (error) {+ // stopped by the person: nothing failed+ o.signal?.throwIfAborted()+ const n = (failures[c.track] = (failures[c.track] ?? 0) + 1)+ const last = n >= PARAKEET_FAILURES+ console.warn(`ASR ${c.track}: parakeet-server failed (${error instanceof Error ? error.message : String(error)}): whisper reads this chunk${last ? ', and the track for the rest of this meeting' : ''}`)+ if (last && !fell[c.track]) {+ fell[c.track] = true+ try { pk!.onFailed?.({ track: c.track, error, never: !answered }) } catch (e) { console.error('telling that Parakeet failed did not work', e) }}+ return 'failed'}- if (res.ok && !partial) o.onTimed?.(c.samples.length, Date.now() - t0, used)- if (!res.ok) throw new Error(`whisper-server answered ${res.status}`)- const body = (await res.json()) as Verbose- const lines: Line[] = []- for (const s of wholeSegments(body.segments ?? [])) {- const said = s.text.replace(/\s+/g, ' ').trim()- // names from the prompt read back as a speaker label ("Eric and Sam Lee: so..."): the speech after it stays- const text = withoutPromptLabel(said, prompt)- if (!text || NOISE.test(text)) continue- if ((s.no_speech_prob ?? 0) > 0.6 && (s.avg_logprob ?? 0) < -1) continue- // read back from the prompt, or a stock line over a faint sound: whisper had nothing to read- // a subtitle credit is never said in a meeting, faint or not- if (isPromptEcho(text, prompt) || isSubtitleCredit(text) || (faint && isSilenceGuess(text))) continue- // the label's words (through the one carrying its colon) go with it- const kept = text === said ? s.words : s.words?.slice((s.words.findIndex((w) => w.word.includes(':')) + 1) || 0)- const words = kept?.map((w) => ({ text: w.word, startMs: Math.round(c.startMs + w.start * 1000), endMs: Math.round(c.startMs + w.end * 1000) }))- lines.push({ track: c.track, startMs: Math.round(c.startMs + s.start * 1000), endMs: Math.round(c.startMs + s.end * 1000), text, ...(words?.length ? { words } : {}) })- }- return { lines, text: joinSaid(lines.map((l) => l.text)), language: body.detected_language ?? body.language ?? 'auto', prob: body.detected_language_probability ?? 0 }+ }+ const viaParakeet = async (c: Chunk): Promise<ParakeetReading | null | 'failed'> => {+ const p = await tryParakeet(c)+ if (p === 'failed' || !judgeable(c)) return p+ if (!p.flagged) { watch.saw(c.track, false); return p }+ console.warn(`ASR ${c.track}: Parakeet's reading looks like a language it doesn't know (mean log-probability ${p.meanLogprob === null ? 'none' : p.meanLogprob.toFixed(2)}, ${p.tokensPerSecond.toFixed(1)} tokens a second): whisper reads this chunk`)+ return null+ }+ /**+ * whisper read a chunk Parakeet could not: did it hear a language Parakeet doesn't cover? Only then does the chunk+ * count against Parakeet (in a noisy room it is unsure of a language it knows now and then). true: a few in a row,+ * the track leaves Parakeet.+ */+ const givesUp = (c: Chunk, heard: string, prob: number): boolean => {+ // whisper only guessing (hold music, noise) says nothing about the language+ if (heard === 'auto' || parakeetCovers(heard) || prob < MIN_LOCK_PROB) return false+ const gaveUp = watch.saw(c.track, true)+ if (gaveUp) { console.warn(`ASR ${c.track}: whisper hears ${heard} where Parakeet could not read, several chunks in a row: Parakeet leaves this track`); uncovered(heard) }+ return gaveUp}return async (c, opt) => {const forced = o.language?.()if (forced) {+ if (route(c.track, forced) === 'parakeet') {+ const p = opt?.partial ? await tryParakeet(c, opt) : await viaParakeet(c)+ if (p && p !== 'failed') {+ if (!opt?.partial && p.text.trim()) o.onLanguage?.(c.track, languageName(forced), p.text.length, true)+ return p.lines+ }+ if (p === null) {+ // whisper reads it in the language picked, and says which language it hears in the audio+ const r = await call(c, forced, false, true)+ if (givesUp(c, r.language, r.prob)) { fell[c.track] = true; route(c.track, forced) }+ if (r.text.trim() && !isGarbled(r.text)) o.onLanguage?.(c.track, languageName(forced), r.text.length, true)+ return r.lines+ }+ // parakeet-server failed: whisper reads this chunk like any other in the language picked+ route(c.track, forced)+ }// the person said which language it is: nothing to detect, lock or look at againconst r = await call(c, forced, !!opt?.partial, false)if (!opt?.partial && r.text.trim() && !isGarbled(r.text)) o.onLanguage?.(c.track, languageName(forced), r.text.length, true)return r.lines}const had = locked[c.track]+ /** Parakeet has this track but not this chunk: whisper reads it with the language open, and the lock stays */+ let aside = false+ if (had && route(c.track, had) === 'parakeet') {+ const p = opt?.partial ? await tryParakeet(c, opt) : await viaParakeet(c)+ if (p && p !== 'failed') {+ if (!opt?.partial && p.text.trim()) o.onLanguage?.(c.track, had, p.text.length, true)+ return p.lines+ }+ // unsure of the language: whisper hears it again. parakeet-server failed: whisper reads it in the locked language+ if (p === null) aside = true+ else route(c.track, had)+ }// a partial neither locks the language nor counts towards it: the finished line does- if (opt?.partial) return (await call(c, had ?? 'auto', true)).lines- let r = await call(c, had ?? 'auto')- if (had && isGarbled(r.text)) {+ if (opt?.partial) return (await call(c, had ?? 'auto', true, false, had ? o : hears)).lines+ let r = await call(c, aside || !had ? 'auto' : had, false, true, aside || !had ? hears : o)+ if (pk && (aside || !had) && r.language !== 'auto' && r.text.trim()) {+ if (parakeetCovers(r.language) && !aside && r.prob >= MIN_LOCK_PROB) {+ // whisper clearly heard a language Parakeet covers: Parakeet's reading of the chunk is the better one, unless+ // it looks unsure itself (the track is not locked yet, so even a short chunk's doubt counts here)+ const p = fell[c.track] ? 'failed' : await tryParakeet(c)+ if (p !== 'failed' && p.text.trim() && !p.flagged) r = { ...r, lines: p.lines, text: p.text }+ } else if (!parakeetCovers(r.language) && !isGarbled(r.text) && r.prob >= MIN_LOCK_PROB) uncovered(r.language)+ if (!parakeetCovers(r.language) && pk.lid && !isGarbled(r.text)) {+ // the small whisper only heard which language it is: the bigger one reads it+ const again = await call(c, r.language)+ if (again.text.trim() && !isGarbled(again.text)) r = { ...again, language: r.language, prob: Math.max(again.prob, r.prob) }+ }+ }+ if (aside) {+ if (!givesUp(c, r.language, r.prob)) {+ if (r.language !== 'auto' && r.text.trim() && !isGarbled(r.text)) o.onLanguage?.(c.track, r.language, r.text.length, true)+ return r.lines+ }+ // a few in a row in a language Parakeet doesn't cover: the track is heard again from scratch, like one never+ // locked, starting with this chunk+ delete locked[c.track]; delete evidence[c.track]; delete reader[c.track]+ }+ /** the lock this chunk was read under (none once Parakeet gave the track up) */+ const was = aside ? undefined : had+ if (was && isGarbled(r.text)) {const open = await call(c, 'auto')// nothing in any language (VAD found no speech, or only made-up lines): the lock staysif (open.text.trim()) { delete locked[c.track]; r = open }}// told the locked language, yet clearly in another: read again in that one, and after a few such lines follow it- if (had && locked[c.track] === had && r.language !== 'auto' && r.language !== had && r.prob >= SWITCH_PROB && tokens(r.text).length >= MIN_LOCK_TOKENS) {+ if (was && locked[c.track] === was && r.language !== 'auto' && r.language !== was && r.prob >= SWITCH_PROB && tokens(r.text).length >= MIN_LOCK_TOKENS) {const heard = r.languageconst again = await call(c, heard)if (again.text.trim() && !isGarbled(again.text)) {r = { ...again, language: heard, prob: Math.max(again.prob, r.prob) }strays[c.track] = (strays[c.track] ?? 0) + 1- if (strays[c.track]! >= SWITCH_LINES) { locked[c.track] = heard; strays[c.track] = 0 }+ if (strays[c.track]! >= SWITCH_LINES) { locked[c.track] = heard; strays[c.track] = 0; lockedOn(c.track, heard) }}- } else if (r.language === had) strays[c.track] = 0- if (r.language !== 'auto' && r.text.trim() && !isGarbled(r.text)) o.onLanguage?.(c.track, r.language, r.text.length, !!had)- if (!locked[c.track] && r.language !== 'auto' && r.prob >= MIN_LOCK_PROB && !isGarbled(r.text) && tokens(r.text).length >= MIN_LOCK_TOKENS) locked[c.track] = r.language+ } else if (r.language === was) strays[c.track] = 0+ if (r.language !== 'auto' && r.text.trim() && !isGarbled(r.text)) o.onLanguage?.(c.track, r.language, r.text.length, !!was)+ if (!locked[c.track] && r.language !== 'auto' && r.prob >= MIN_LOCK_PROB && !isGarbled(r.text) && tokens(r.text).length >= MIN_LOCK_TOKENS) {+ const e = evidence[c.track]?.language === r.language ? evidence[c.track]! : { language: r.language, ms: 0 }+ e.ms += c.samples.length / 16+ evidence[c.track] = e+ // without Parakeet the first clear chunk locks, as it always did+ if (!pk || e.ms >= PARAKEET_LOCK_MS) { locked[c.track] = r.language; delete evidence[c.track]; lockedOn(c.track, r.language) }+ }return r.lines}++ /** a track is locked on a language: with Parakeet, that says who reads it from here on */+ function lockedOn(track: Track, language: string) {+ if (!pk) return+ watch.reset(track)+ if (route(track, language) === 'whisper' && !parakeetCovers(language)) uncovered(language)+ }}diff --git a/app/src/main/fake.ts b/app/src/main/fake.tsindex fba31c15..9d874562 100644--- a/app/src/main/fake.ts+++ b/app/src/main/fake.ts@@ -132,7 +132,7 @@ export const fakeHelper: Helper = async (args) => {}/** Fake mode: every prompt whisper and the notes model were given, for tests to read (prompts()) */-export const fakePrompts = { whisper: [] as string[], notes: [] as string[], /** what was read in ahead of a prompt */ preloads: [] as string[], /** the language whisper was told for each chunk ('auto': detect) */ languages: [] as string[] }+export const fakePrompts = { whisper: [] as string[], notes: [] as string[], /** what was read in ahead of a prompt */ preloads: [] as string[], /** the language whisper was told for each chunk ('auto': detect) */ languages: [] as string[], /** who read each chunk: parakeet, or whisper */ engines: [] as string[] }/** Fake mode: a clock tests can move forward, so "30 seconds without the mic" does not take 30 seconds. YOGURT_FAKE_CALL_GONE_MS shortens the wait before a recording stops by itself when its call ends */let skew = 0diff --git a/app/src/main/index.ts b/app/src/main/index.tsindex c9d8288e..2f8fd2d1 100644--- a/app/src/main/index.ts+++ b/app/src/main/index.ts@@ -45,8 +45,10 @@ import { createMedia } from './media'import { createTray, linuxTrayHost } from './tray'import { trayWindowEnd } from './trayMenu'import { asrFor, SetupController } from './setup'-import { fakeMeasure, measureSpeed, speedClipPath, speedStore } from './asr/speedCheck'-import { vadModelPath, whisperServerPath } from './asr/server'+import { fakeMeasure, fakeParakeetMeasure, fakeParakeetTry, measureParakeet, measureSpeed, speedClipPath, speedStore, stopTiming } from './asr/speedCheck'+import { killStale, parakeetServerPath, vadModelPath, whisperServerPath } from './asr/server'+import { asrKillSwitch, parakeetCovers } from './asr/parakeet'+import { createRereads } from './asr/reread'import { openStore, type Store } from './store'import { calendars, eventIds, matchesEvent, setCalendarSelection, setCalendarOwnEmail, calendarStatus, createHelperRunner, helperPath, killAllHelpers, refreshCalendarStatus, requestCalendarAccess, runHelper, setCalendarLinkSource, systemCalendarStatus, setCalendarSupported, setHelper, upcoming, type CalEvent } from './calendar'import { createCalendarLinks } from './calendarLink'@@ -62,7 +64,7 @@ import { isId, text, rewriteNote } from './ipcArgs'import { hookMics } from './mics'import { activeCapture, audioHelperPath, hookCapture, joinParts, onCaptureStart, onRecordingEvent, prepareAppend, recordingFinished, recordingPaused, recordingSettled, rejoinInterrupted, setMicMuted, setRecordingPaused, settleRecording, tell, type WarnCode } from './capture'import { createWidget } from './widget'-import { liveSilentMs, hookTranscription, transcribeRecorded, onWhisperGpuOff, meetingLanguage, settleTranscription, speechLocaleFor, spokenChanged, transcriptionBacklogMs, stopTranscriptionServer, releaseIdleSpeech, transcriptFinished, transcriptOpen, transcriptPartials } from './asr'+import { liveSilentMs, hookTranscription, transcribing, transcribeRecorded, onWhisperGpuOff, meetingLanguage, settleTranscription, speechLocaleFor, spokenChanged, transcriptionBacklogMs, stopTranscriptionServer, releaseIdleSpeech, transcriptFinished, transcriptOpen, transcriptPartials } from './asr'import { hookCallNames, type Watch } from './callNames'import { helperWatch, killAllWatches } from './callNames/watch'import { macFullName } from './user'@@ -233,9 +235,30 @@ function createSetup(): SetupController {download: isFake() ? fakeDownloadDeps({ stepMs: Number(process.env.YOGURT_FAKE_STEP_MS ?? 5), notesMs: Number(process.env.YOGURT_FAKE_NOTES_MODEL_MS ?? 0), notesFailOnce: process.env.YOGURT_FAKE_NOTES_MODEL_FAIL_ONCE === '1' }) : realDeps,...(isFake() ? { sha256Override: 'FAKE' } : {}),// Windows and Linux: speech models timed on this computer (asr/speedCheck.ts); a Mac never is- ...(platform === 'darwin' ? {} : { speed: { ...speedStore(speedFile()), measure: isFake() ? fakeMeasure() : (model: string, o?: { cpu?: boolean }) => measureSpeed(model, { binary: whisperServerPath(), vadModel: vadModelPath(), clip: speedClipPath() ?? '', cpu: o?.cpu }) } }),+ ...(platform === 'darwin' ? {} : { speed: { ...speedStore(speedFile()), measure: isFake() ? fakeMeasure() : (model: string, o?: { cpu?: boolean }) => measureSpeed(model, { binary: whisperServerPath(), vadModel: vadModelPath(), clip: speedClipPath() ?? '', cpu: o?.cpu, pidFile: timingPid() }) } }),+ // Parakeet for the languages it covers, tried on the bundled clip before it is used, the way meetings run it:+ // Windows and Linux time it on the processor, like the whisper models; a Mac runs it once on its graphics (Metal)+ parakeet: {+ off: parakeetOff,+ measure: isFake() ? (platform === 'darwin' ? fakeParakeetTry() : fakeParakeetMeasure()) : (model: string) => measureParakeet(model, { binary: parakeetServerPath(), clip: speedClipPath() ?? '', cpu: process.platform !== 'darwin', pidFile: timingPid() }),+ wantsWhisper,+ quiet: () => !transcribing(),+ },})}+/** why Parakeet is not used: the kill switch (YOGURT_ASR=whisper, or "asr": "whisper" in settings.json), or a build without parakeet-server */+const parakeetOff = (): string | null => asrKillSwitch(process.env, loadSettings(join(userDataDir(), 'settings.json')))+ ?? (isFake() || existsSync(parakeetServerPath()) ? null : 'parakeet-server is not in this build')+/**+ * The bigger whisper is wanted next to Parakeet: a meeting was in a language Parakeet doesn't cover, or Multi-language+ * is picked on a computer whose own language is one (so its first such meeting is already read well).+ */+const wantsWhisper = (): boolean => {+ const s = loadSettings(join(userDataDir(), 'settings.json'))+ return s.asrWhisperWanted === true || (spokenSetting(s) === 'multi' && !parakeetCovers(localeOf(s, systemLocale())))+}+/** the speech program being timed keeps its pid here: one left running when Yogurt quit mid-timing is ended at the next start */+const timingPid = () => join(userDataDir(), 'speech-timing.pid')/** what the speed check found (Windows and Linux) */const speedFile = () => join(userDataDir(), 'speech-speed.json')@@ -628,7 +651,7 @@ app.whenReady().then(() => {return true},slowStartMs: isFake() ? Number(process.env.YOGURT_FAKE_BOOT_MS ?? 0) : 0,- onSpoken: () => spokenChanged(),+ onSpoken: () => { spokenChanged(); if (wantsWhisper()) setup.wantWhisper() },})// Music and Spotify pause while a meeting records, and play again afterconst media = createMedia({ helper: runHelper })@@ -637,6 +660,7 @@ app.whenReady().then(() => {onMeetingStart(() => void media.pause())onMeetingStop(() => void media.resume())}+ if (!isFake()) killStale(timingPid())const setup = createSetup()setup.onState((st) => win?.webContents.send('setup:state', st))ipcMain.handle('setup:state', () => setup.state)@@ -671,8 +695,21 @@ app.whenReady().then(() => {onWhisperGpuOff(() => speedStore(speedFile()).forget())// the speech model for the spoken language: where base keeps up live but is poor outside English, Multi-language// meetings are read with a better one from the recording after they end (#107)+ let rereads: ReturnType<typeof createRereads> | undefinedconst asrNow = () => { const i = setup.installed(); return i && asrFor(i, spokenSetting(loadSettings(settingsFile))) }hookTranscription({ store, modelPath: () => asrNow()?.path, smallerModels: () => setup.installed()?.smallerAsr ?? [],+ // Parakeet for the languages it covers, once it is downloaded and checked (whisper reads everything until then, and with the kill switch)+ parakeet: () => { const i = setup.installed(); return i?.parakeet && i.lid && !parakeetOff() ? { model: i.parakeet, lid: i.lid } : undefined },+ parakeetOff,+ // parakeet-server failed in a meeting: whisper reads instead, and the bigger one is fetched where there is only the small one+ wantWhisper: () => setup.wantWhisper(),+ // read by the small whisper because the bigger one is still on its way: read again from the recording once it is in+ weakWhisper: (id) => rereads?.note(id),+ // a language Parakeet doesn't cover: remembered, and the bigger whisper is fetched where there is only the small one+ uncovered: (language) => {+ if (!loadSettings(settingsFile).asrWhisperWanted) { console.info('ASR', `a meeting is in ${language}, which Parakeet does not cover: the bigger whisper is kept for it`); updateSettings(settingsFile, { asrWhisperWanted: true }) }+ setup.wantWhisper()+ },// the speed check's findings: whisper on the processor (faster there than on built-in graphics), or after the meetingcpuOnly: () => !!asrNow()?.cpu, afterMeeting: () => !!asrNow()?.afterMeeting, send: (seg) => {const order = seg.track === 'them' && seg.speaker ? store.speakerOrder(seg.meetingId, seg.speaker) : []@@ -804,7 +841,11 @@ app.whenReady().then(() => {},transcribe: (id,tracks,options) => transcribeRecorded(id,tracks,undefined,options),draft:id=>win?.webContents.send('transcript:draft',id),- changed: (id,replaced) => {win?.webContents.send('meetings:changed');if(replaced){win?.webContents.send('transcript:replaced',id);void indexer.schedule()}},+ changed: (id,replaced) => {+ win?.webContents.send('meetings:changed');if(replaced){win?.webContents.send('transcript:replaced',id);void indexer.schedule()}+ // read again with the bigger whisper: notes nobody edited were written from the small one's transcript, so they are written again+ if(replaced&&rereads?.reread(id)&&store.notes(id).enhanced?.trim()&&!store.notes(id).edited)void notes.writeAgain(id)+ },summarize: id => {void notes.writeAgain(id)},})const uploads = hookAudioUploads({@@ -812,6 +853,21 @@ app.whenReady().then(() => {recording: () => !!activeMeeting() || !!resumingId || finishing,prepared: id => {void savedTranscriptions.start(id)}, changed: () => win?.webContents.send('meetings:changed'),})+ // meetings the small whisper read while the bigger one downloaded (a language Parakeet doesn't cover on a new install)+ rereads = createRereads({+ load: () => loadSettings(settingsFile).asrReread ?? [], save: (ids) => { updateSettings(settingsFile, { asrReread: ids }) },+ ready: () => { const i = setup.installed(); return !!i?.lid && i.asr !== i.lid },+ meeting: (id) => {+ const m = store.meeting(id)+ if (!m || m.trashedAt != null) return null+ return { busy: m.state === 'recording' || transcriptOpen(id) || savedTranscriptions.owns(id) || !!m.transcriptionPending, audio: (['me', 'them'] as const).some((t) => !!trackFile(meetingDir(id), t, audioKinds)) }+ },+ start: (id) => savedTranscriptions.start(id, true),+ })+ setup.onWhisper(() => void rereads?.run())+ onMeetingStopSaved((m) => { void recordingFinished(m.id).then(() => transcriptFinished(m.id)).then(() => rereads?.run()).catch((e) => console.error('reading a meeting again failed', e)) })+ let rereadAtStart = false+ setup.onState((s) => { if (s.phase === 'ready' && !rereadAtStart) { rereadAtStart = true; void rereads?.run() } })setup.onState(() => {uploads.resume();savedTranscriptions.resume()})onMeetingStart(m => {store.clearTranscriptionState(m.id);savedTranscriptions.pause()})onMeetingStopSaved(() => {uploads.resume();savedTranscriptions.resume()})@@ -1112,6 +1168,7 @@ app.whenReady().then(() => {})})app.on('will-quit', stopTranscriptionServer)+ app.on('will-quit', stopTiming)const reminder = createRecordingReminder(() => recordingReminderOn(loadSettings(settingsFile)))onMeetingStart(reminder.started)onMeetingStop(reminder.stopped)diff --git a/app/src/main/settings.ts b/app/src/main/settings.tsindex 4134e9f3..703f5103 100644--- a/app/src/main/settings.ts+++ b/app/src/main/settings.ts@@ -12,6 +12,12 @@ export type Settings = { theme?: 'light' | 'dark'; language?: string; /** what tintroSeen?: boolean/** The optional bigger notes model stays off until explicitly downloaded again. */notesUpgradeSkipped?: boolean+ /** no screen sets this: "whisper" turns Parakeet off and transcribes as before it existed (also YOGURT_ASR=whisper) */+ asr?: string+ /** a meeting was in a language Parakeet doesn't cover: the bigger whisper for this computer is kept (and fetched where it is missing) */+ asrWhisperWanted?: boolean+ /** meetings the small whisper read while the bigger one was still downloading: read again from their recordings once it is in (asr/reread.ts) */+ asrReread?: string[]/** Windows and Linux: the notes engine found the graphics card with Vulkan, not its default (CUDA) build (#32) */notesGpuBackend?: 'vulkan'/** Windows and Linux: the most layers this notes model may put on the graphics card, after it ran out of memory with more (#165); 0: the processor */diff --git a/app/src/main/setup.ts b/app/src/main/setup.tsindex 616f0565..ed1afbc5 100644--- a/app/src/main/setup.ts+++ b/app/src/main/setup.ts@@ -1,6 +1,6 @@-import { asrCandidates, pick, pickAsr, pickBySpeed, speedKey, type Catalog, type CatalogAsr, type Choice, type Hardware } from '@yogurt/picker'-import { rmSync } from 'node:fs'-import { join } from 'node:path'+import { asrCandidates, parakeetKeepsUp, pick, pickAsr, pickBySpeed, speedKey, type Catalog, type CatalogAsr, type Choice, type Hardware } from '@yogurt/picker'+import { readFileSync, rmSync, writeFileSync } from 'node:fs'+import { basename, join } from 'node:path'import { setTimeout as delay } from 'node:timers/promises'import { ChecksumError, DiskSpaceError, ensureFile, fileNameFor, isVerified, partialDownloadGB, type DownloadDeps } from './downloader'import type { SetupState } from '../shared/types'@@ -13,7 +13,9 @@ export type SpeedResult = { key: string; model: string | null; rtf: Record<strin/** times on the processor alone, for models too slow on the graphics */ cpuRtf?: Record<string, number | null>/** the model kept up on the processor, not the graphics: whisper stays there */ cpu?: boolean/** none keeps up live: meetings are transcribed from the recording after they end */ afterMeeting?: boolean- /** the model kept is weak outside English: this better one reads meetings in other languages after they end (#107) */ multi?: { model: string; cpu?: boolean } }+ /** the model kept is weak outside English: this better one reads meetings in other languages after they end (#107) */ multi?: { model: string; cpu?: boolean }+ /** Parakeet's time on the processor (null: out of time); not there: not timed yet */ parakeet?: number | null+ /** false: Parakeet keeps up, so the whisper models were not timed (model is the small one that hears languages); they are once a bigger whisper is wanted */ whisperTimed?: boolean }/** Windows and Linux: time a speech model on this computer (null: it ran out of time), and keep what was found */export type SpeedDeps = {/** cpu: on the processor alone, never the graphics */@@ -38,10 +40,32 @@ export type SetupDeps = {upgradePreference?: { load(): boolean; save(skipped: boolean): void }/** Windows and Linux: the speed check picks the speech model (a Mac never has it: turbo, as always) */speed?: SpeedDeps+ /** Parakeet for the languages it covers (asr/parakeet.ts); left out: whisper only, as before it existed */+ parakeet?: ParakeetDeps+}++export type ParakeetDeps = {+ /** why Parakeet may not be used here (the kill switch, no parakeet-server in this build), for the log; null: it may */+ off(): string | null+ /**+ * Parakeet tried on the bundled clip the way meetings will run it (the processor on Windows and Linux, Metal on a+ * Mac): its time over the clip's length, null when it ran out of time or heard no words. It may throw (the helper+ * won't start): that is "not usable now", never a setup error. Left out: adopted untried.+ */+ measure?(modelPath: string): Promise<number | null>+ /** a bigger whisper is wanted too: a language Parakeet doesn't cover was heard in a meeting, or is the computer's own */+ wantsWhisper(): boolean+ /** nothing is being recorded or transcribed: timing a model now disturbs no meeting (left out: always) */+ quiet?(): boolean+ /** how often to look again while waiting for quiet (tests: at once) */+ quietPollMs?: number}/** Where the models ended up, for the parts of the app that use them; llm once the first notes model is in (after ready) */-export type Installed = { asr: string; /** whisper runs on the processor: it kept up there and not on the graphics */ asrCpu?: true; /** whisper can't keep up live here: meetings are transcribed after they end */ asrAfterMeeting?: true; /** asr is weak outside English: meetings in other languages are read with this one after they end (#107) */ asrMulti?: string; /** asrMulti runs on the processor */ asrMultiCpu?: true; /** smaller speech models already on disk, best first: one takes over when the processor is too slow for asr (#156) */ smallerAsr?: string[]; llm?: string; recommendedLlm?: string; /** meaning search across meetings; word search works without it */ embed?: string }+export type Installed = { asr: string; /** whisper runs on the processor: it kept up there and not on the graphics */ asrCpu?: true; /** whisper can't keep up live here: meetings are transcribed after they end */ asrAfterMeeting?: true; /** asr is weak outside English: meetings in other languages are read with this one after they end (#107) */ asrMulti?: string; /** asrMulti runs on the processor */ asrMultiCpu?: true; /** smaller speech models already on disk, best first: one takes over when the processor is too slow for asr (#156) */ smallerAsr?: string[]+ /** Parakeet's model, once it is downloaded, checked and (Windows and Linux) fast enough: it reads the languages it covers, asr the rest */ parakeet?: string+ /** with parakeet: the small whisper that hears which language a track is in (asr itself until a bigger one is there) */ lid?: string+ llm?: string; recommendedLlm?: string; /** meaning search across meetings; word search works without it */ embed?: string }/*** The speech model for a meeting in this spoken language: English only reads with asr as always; Multi-language with@@ -92,6 +116,12 @@ export class SetupController {private embedding: Promise<void> | undefined/** Try again after an error: time the speech models again instead of trusting what was stored */private recheck = false+ /** Parakeet arriving on a computer that already transcribes with whisper, and a bigger whisper fetched later: after ready */+ private speech: Promise<void> | undefined+ /** fetches (and on Windows and Linux picks by speed) the bigger whisper; set at ready when one may still be wanted */+ private whisperLater: (() => Promise<void>) | undefined+ private whisperAsked = false+ private whisperListeners = new Set<() => void>()constructor(private deps: SetupDeps) {}@@ -193,11 +223,62 @@ export class SetupController {/** Resolves when the notes and embedding models have finished downloading (or the bigger one gave up). Ready never waits for them. */async idle(): Promise<void> {+ await this.speechawait this.backgroundawait this.upgradeDownloadawait this.embedding}+ /**+ * A language Parakeet doesn't cover was heard: the bigger whisper (the one this computer got before Parakeet) is+ * fetched in the background, once. Until it is in, the small whisper reads those meetings.+ */+ wantWhisper() {+ if (this.whisperAsked || !this.whisperLater) return+ this.whisperAsked = true+ const run = this.whisperLater+ this.speech = (this.speech ?? Promise.resolve()).then(run).catch((err) => { this.whisperAsked = false; console.warn('ASR', 'the bigger whisper model did not download; it is tried again at the next start', err) })+ }++ /** called when the bigger whisper is in next to Parakeet (meetings the small one had to read can be read again) */+ onWhisper(cb: () => void) { this.whisperListeners.add(cb); return () => this.whisperListeners.delete(cb) }+ private whisperLanded() { for (const l of this.whisperListeners) { try { l() } catch (e) { console.error('bigger whisper listener failed', e) } } }++ /** a Mac has no speed check's store: a file beside the model says Parakeet passed its try on this computer */+ private tested(i: Item): boolean { try { return readFileSync(join(i.dir, i.fileName + '.tested'), 'utf8') === this.sha(i) } catch { return false } }+ private markTested(i: Item) { try { writeFileSync(join(i.dir, i.fileName + '.tested'), this.sha(i)) } catch (e) { console.warn('ASR', "could not note that Parakeet passed its try", e) } }++ /**+ * Parakeet tried on this computer: its time, null (too slow, or no words heard), or 'failed' when it would not run+ * at all, which is logged and never thrown. background: only while no meeting runs, and a time taken while one+ * started is thrown away and taken again.+ */+ private async tryParakeet(pk: ParakeetDeps, model: string, background = false): Promise<number | null | 'failed'> {+ try {+ return background ? await this.quietly(() => pk.measure!(model)) : await pk.measure!(model)+ } catch (err) {+ console.warn('ASR', `Parakeet could not be tried on this computer (${err instanceof Error ? err.message : String(err)}): whisper reads every language, and it is tried again at the next start`)+ return 'failed'+ }+ }++ /** Runs a timing while no meeting is on; one that a meeting started during is skewed, so it is run again after */+ private async quietly<T>(run: () => Promise<T>): Promise<T> {+ const pk = this.deps.parakeet+ for (;;) {+ await this.whenQuiet()+ const r = await run()+ if (!pk?.quiet || pk.quiet()) return r+ console.info('ASR', 'a meeting started while a speech model was being timed: that time is thrown away, and it is timed again after')+ }+ }++ /** resolves once no meeting is being recorded or transcribed */+ private async whenQuiet() {+ const pk = this.deps.parakeet+ while (pk?.quiet && !pk.quiet()) await delay(pk.quietPollMs ?? 15_000)+ }+async start() {if (this.busy) returnthis.busy = true@@ -228,6 +309,15 @@ export class SetupController {// Speech first: ready (recording works) once it is in. The notes models come after.let asr = pickAsr(hw, catalog)const asrItem = (m: CatalogAsr): Item => ({ url: m.url, sha256: m.sha256, bytes: m.bytes, dir: dirs.asr, fileName: fileNameFor(m.url) })+ const here = (i: Item) => isVerified(i.dir, i.fileName, this.sha(i))+ const pathOf = (i: Item) => join(i.dir, i.fileName)+ // Parakeet for the languages it covers, with the small whisper that hears which language a track is in+ const lidModel = catalog.parakeet && catalog.asr.find((a) => a.id === catalog.parakeet!.languageId)+ const off = !this.deps.parakeet ? 'off' : !catalog.parakeet || !lidModel ? 'it is not in this catalog' : this.deps.parakeet.off()+ if (this.deps.parakeet && off) console.info('ASR', `Parakeet is not used, whisper reads every language: ${off}`)+ const pk = off || !catalog.parakeet || !lidModel ? undefined : { deps: this.deps.parakeet!, item: asrItem(catalog.parakeet), lid: asrItem(lidModel), lidId: lidModel.id }+ this.whisperLater = undefined+ this.whisperAsked = false// whisper-server is built into the app (catalog.whisperServer.bundled), so only the speech model is downloaded for it.const starterItem = llmItem(dirs.llm, starter)this.firstItem = starterItem@@ -247,12 +337,18 @@ export class SetupController {const known = saved?.key === key && saved.model ? saved : undefinedconst candidates = speed ? asrCandidates(hw, catalog) : []if (speed && !candidates.length) return this.set({ phase: 'error', fraction: 0, message: tooSlow(hw.os) })- const keep = known && candidates.find((a) => a.id === known.model)- let how: Pick<Installed, 'asrCpu' | 'asrAfterMeeting'> = keep ? { ...(known.cpu ? { asrCpu: true } : {}), ...(known.afterMeeting ? { asrAfterMeeting: true } : {}) } : {}- const keepMulti = keep && known.multi && candidates.find((a) => a.id === known.multi!.model)+ // whisperTimed false: an earlier start kept Parakeet and timed no whisper; the model named is only the small one beside it+ const keep = known && known.whisperTimed !== false ? candidates.find((a) => a.id === known.model) : undefined+ // a whisper model this computer already transcribes with: Parakeet then arrives in the background, after ready+ const macHas = !speed && pk ? [asr.model, ...(asr.fallback ? [asr.fallback] : [])].map(asrItem).find(here) : undefined+ const existing = speed ? !!keep && here(asrItem(keep)) : !!macHas+ // nothing here yet: Parakeet and the small whisper are the first download, and (Windows and Linux) Parakeet is timed+ const pkFirst = !!pk && !existing+ let how: Pick<Installed, 'asrCpu' | 'asrAfterMeeting'> = keep ? { ...(known?.cpu ? { asrCpu: true } : {}), ...(known?.afterMeeting ? { asrAfterMeeting: true } : {}) } : {}+ const keepMulti = keep && known?.multi && candidates.find((a) => a.id === known.multi!.model)let multi: Pick<Installed, 'asrMulti' | 'asrMultiCpu'> = {}- const waitFor: Item[] = [asrItem(speed ? keep ?? candidates[0] : asr.model), ...(keepMulti ? [asrItem(keepMulti)] : [])]+ const waitFor: Item[] = pkFirst ? [pk.item, pk.lid] : [macHas ?? asrItem(speed ? keep ?? candidates[0] : asr.model), ...(keepMulti ? [asrItem(keepMulti)] : [])]const total = waitFor.reduce((n, i) => n + i.bytes, 0)// room for the first notes model too, so it never runs out of disk after readyawait this.checkDisk([...waitFor, ...(hasUpgrade ? [] : [starterItem]), embedItem])@@ -270,12 +366,57 @@ export class SetupController {// speech: if the first choice downloads corrupted twice, the smaller one takes its placeconst tried: string[] = []let asrPath: string | undefined- if (speed && keep) {+ /** Parakeet's model and the small whisper, once both are in and Parakeet may read live here */+ let parakeet: Pick<Installed, 'parakeet' | 'lid'> = {}+ /** this start's finding about Parakeet's speed (Windows and Linux), kept with the whisper models' */+ let pkRtf: number | null | undefined = known?.parakeet+ let whisperTimed = known?.whisperTimed+ if (pkFirst) {+ try {+ const [model, lid] = [await get(pk.item), await get(pk.lid)]+ let ok = true+ if (pk.deps.measure) {+ // "Preparing the transcription model" while it is tried+ this.set({ phase: 'downloading', fraction: 1 })+ // tried on this computer before: not again+ let r: number | null | 'failed' | undefined = speed ? pkRtf : this.tested(pk.item) ? 0 : undefined+ if (r === undefined) {+ r = await this.tryParakeet(pk.deps, model)+ if (r !== 'failed') console.log(`speed check: ${catalog.parakeet!.id} took ${r === null ? 'too long, or heard no words' : `${r.toFixed(2)} x the clip's length`}`)+ }+ // would not run: nothing is noted, its file stays, and the next start tries again+ if (r === 'failed') ok = false+ else {+ if (speed) pkRtf = r+ ok = parakeetKeepsUp(r)+ if (ok && !speed) this.markTested(pk.item)+ if (!ok) {+ console.warn('ASR', speed ? "Parakeet does not keep up live on this computer's processor: whisper is picked as before" : 'Parakeet did not read the test clip on this computer: whisper is picked as before')+ // too slow here for good (the speed check remembers); a Mac tries again at the next start+ if (speed) this.removeFiles(model)+ }+ }+ }+ if (ok) {+ parakeet = { parakeet: model, lid }+ asrPath = lid+ // the whisper models are not timed (or fetched) until a language Parakeet doesn't cover turns up+ if (speed) { whisperTimed = false; speed.save({ key, model: pk.lidId, rtf: {}, ...(pkRtf !== undefined ? { parakeet: pkRtf } : {}), whisperTimed, at: Date.now() }) }+ }+ } catch (err) {+ // never without a speech model over this: whisper as before+ if (!(err instanceof ChecksumError)) throw err+ console.warn('ASR', 'Parakeet downloaded damaged twice: whisper is picked as before')+ }+ }+ if (asrPath) { /* Parakeet and the small whisper */ }+ else if (macHas) asrPath = await get(macHas)+ else if (speed && keep) {asrPath = await get(asrItem(keep))- if (keepMulti) multi = { asrMulti: await get(asrItem(keepMulti)), ...(known.multi!.cpu ? { asrMultiCpu: true } : {}) }+ if (keepMulti) multi = { asrMulti: await get(asrItem(keepMulti)), ...(known?.multi?.cpu ? { asrMultiCpu: true } : {}) }} else if (speed) {const r = await this.timeSpeech(speed, candidates, get, asrItem, hw.gpu.kind !== 'none')- speed.save({ key, ...r.result, at: Date.now() })+ speed.save({ key, ...r.result, ...(pkRtf !== undefined ? { parakeet: pkRtf } : {}), at: Date.now() })// every model downloaded corrupted: nothing to transcribe withif (!r.path) return this.set({ phase: 'error', fraction: this._state.fraction, message: tooSlow(hw.os) })asrPath = r.path@@ -296,13 +437,17 @@ export class SetupController {// never downloaded for this: only what is already there (a model the speed check or an earlier pick left)const picked = catalog.asr.findIndex((a) => join(dirs.asr, fileNameFor(a.url)) === asrPath)const smallerAsr = picked < 0 ? [] : catalog.asr.slice(picked + 1).map(asrItem).filter((i) => isVerified(i.dir, i.fileName, this.sha(i))).map((i) => join(i.dir, i.fileName))- this.paths = { asr: asrPath, ...how, ...multi, ...(smallerAsr.length ? { smallerAsr } : {}) }+ // an earlier start already fetched (and timed) Parakeet next to the whisper this computer had+ if (pk && existing && !parakeet.parakeet && here(pk.item) && here(pk.lid) && (!pk.deps.measure || (speed ? parakeetKeepsUp(pkRtf) : this.tested(pk.item)))) parakeet = { parakeet: pathOf(pk.item), lid: pathOf(pk.lid) }+ this.paths = { asr: asrPath, ...how, ...multi, ...(smallerAsr.length ? { smallerAsr } : {}), ...parakeet }+ console.info('ASR', parakeet.parakeet ? `Parakeet reads the languages it covers, whisper (${basename(asrPath)}) the rest` : `whisper (${basename(asrPath)}) reads every language`)if (hasUpgrade) {this.paths.recommendedLlm = join(bigger!.dir, bigger!.fileName)if (isVerified(starterItem.dir, starterItem.fileName, this.sha(starterItem))) this.paths.llm = join(starterItem.dir, starterItem.fileName)}this.set({ phase: 'ready', fraction: 1, notesUpgradeBytes: bigger?.bytes, notesUpgradeSkipped: skipped, notesUpgradeInstalled: hasUpgrade })this.startNotes(starterItem, embedItem)+ if (pk) this.startSpeech({ pk, existing, speed, key, pkRtf, whisperTimed, candidates, asrItem, hw, big: asrItem(asr.model) })} catch (err) {console.error('setup failed', err)this.set({ phase: 'error', fraction: this._state.fraction, message: friendly(err) })@@ -313,7 +458,7 @@ export class SetupController {* Windows and Linux: download each speech model in turn and time it on a short clip, until one reads two voices as fast* as they talk. The ones that were too slow are deleted again. A model that downloads corrupted is skipped.*/- private async timeSpeech(speed: SpeedDeps, candidates: CatalogAsr[], get: (i: Item) => Promise<string>, asrItem: (m: CatalogAsr) => Item, graphics: boolean) {+ private async timeSpeech(speed: SpeedDeps, candidates: CatalogAsr[], get: (i: Item) => Promise<string>, asrItem: (m: CatalogAsr) => Item, graphics: boolean, o: { /** after ready: nothing is shown */ quiet?: boolean; /** a file to leave alone whichever model is kept (the small whisper Parakeet needs) */ keep?: string } = {}) {const paths = new Map<string, string>()let gpuOff = false/** models whose graphics run fell back to the processor: timing them there again would measure the same */@@ -328,7 +473,7 @@ export class SetupController {}}// "Preparing the transcription model" while it is timed- this.set({ phase: 'downloading', fraction: 1 })+ if (!o.quiet) this.set({ phase: 'downloading', fraction: 1 })const t = await speed.measure(paths.get(m.id)!, onCpu ? { cpu: true } : undefined)if (t.gpuOff && !onCpu) { gpuOff = true; ranOnCpu.add(m.id) }console.log(`speed check: ${m.id}${onCpu ? ' on the processor' : ''} took ${t.rtf === null ? 'too long' : `${t.rtf.toFixed(2)} x`} the clip's length`)@@ -340,10 +485,68 @@ export class SetupController {// the smallest fallback may be one that downloaded corrupted: then the smallest that did notconst model = r.model && !corrupt.has(r.model.id) ? r.model : [...candidates].reverse().find((c) => paths.has(c.id) && !corrupt.has(c.id)) ?? nullconst multi = model === r.model && r.multi && paths.has(r.multi.model.id) ? r.multi : undefined- for (const [id, p] of paths) if (id !== model?.id && id !== multi?.model.id) rmSync(p, { force: true })+ for (const [id, p] of paths) if (id !== model?.id && id !== multi?.model.id && p !== o.keep) rmSync(p, { force: true })return { path: model && paths.get(model.id), multiPath: multi && paths.get(multi.model.id), result: { model: model?.id ?? null, rtf: r.rtf, ...(r.cpuRtf ? { cpuRtf: r.cpuRtf } : {}), ...(gpuOff ? { gpuOff } : {}), ...(r.cpu && model === r.model ? { cpu: true } : {}), ...(r.afterMeeting || model !== r.model ? { afterMeeting: true } : {}), ...(multi ? { multi: { model: multi.model.id, ...(multi.cpu ? { cpu: true } : {}) } } : {}) } }}+ /**+ * After ready, without holding anything up. A computer that already transcribes with whisper gets Parakeet and the+ * small whisper now, checked (and on Windows and Linux timed, while no meeting runs) before the next meeting uses+ * them; until then, and if any of it fails, whisper keeps reading everything. And where Parakeet is the reader, the+ * bigger whisper is fetched once a language it doesn't cover is wanted.+ */+ private startSpeech(a: { pk: { deps: ParakeetDeps; item: Item; lid: Item; lidId: string }; existing: boolean; speed: SpeedDeps | undefined; key: string; pkRtf: number | null | undefined; whisperTimed: boolean | undefined; candidates: CatalogAsr[]; asrItem: (m: CatalogAsr) => Item; hw: Hardware; big: Item }) {+ const { pk, speed } = a+ const here = (i: Item) => isVerified(i.dir, i.fileName, this.sha(i))+ const arrive = async () => {+ if (!a.existing || this.paths?.parakeet) return+ // timed before and too slow here: it is not fetched again+ if (speed && pk.deps.measure && a.pkRtf !== undefined && !parakeetKeepsUp(a.pkRtf)) return+ if (!here(pk.item)) console.info('ASR', `downloading Parakeet (${(pk.item.bytes / 1e6).toFixed(0)} MB) in the background; whisper keeps reading every language until it is in`)+ const [model, lid] = [await this.fetch(pk.item), await this.fetch(pk.lid)]+ if (pk.deps.measure && (speed ? a.pkRtf === undefined : !this.tested(pk.item))) {+ const r = await this.tryParakeet(pk.deps, model, true)+ if (r === 'failed') return+ console.log(`speed check: Parakeet took ${r === null ? 'too long, or heard no words' : `${r.toFixed(2)} x the clip's length`}`)+ if (speed) { const saved = speed.load(); if (saved?.key === a.key) speed.save({ ...saved, parakeet: r }) }+ if (!parakeetKeepsUp(r)) {+ console.warn('ASR', speed ? "Parakeet does not keep up live on this computer's processor: whisper keeps reading every language" : 'Parakeet did not read the test clip on this computer: whisper keeps reading every language')+ if (speed) this.removeFiles(model)+ return+ }+ if (!speed) this.markTested(pk.item)+ }+ if (!this.paths) return+ this.paths = { ...this.paths, parakeet: model, lid }+ console.info('ASR', 'Parakeet is in and checked: from the next meeting it reads the languages it covers')+ }+ // a bigger whisper for the languages Parakeet doesn't cover, where the small one is all there is+ if (!a.existing) this.whisperLater = async () => {+ if (!this.paths?.parakeet || this.paths.asr !== this.paths.lid) return+ if (!speed) {+ if (!here(a.big)) console.info('ASR', `downloading ${a.big.fileName} in the background for the languages Parakeet does not cover`)+ const path = await this.fetch(a.big)+ if (this.paths) this.paths = { ...this.paths, asr: path }+ console.info('ASR', `${a.big.fileName} is in: it reads the languages Parakeet does not cover`)+ this.whisperLanded()+ return+ }+ // the first one downloads at once, also while a meeting runs; only the timing waits for it to end+ if (a.candidates[0]) await this.fetch(a.asrItem(a.candidates[0])).catch((err) => { if (!(err instanceof ChecksumError)) throw err })+ await this.whenQuiet()+ console.info('ASR', 'timing the whisper models in the background for the languages Parakeet does not cover')+ const calm: SpeedDeps = { ...speed, measure: (path, o) => this.quietly(() => speed.measure(path, o)) }+ const r = await this.timeSpeech(calm, a.candidates, (i) => this.fetch(i), a.asrItem, a.hw.gpu.kind !== 'none', { quiet: true, keep: this.paths.lid })+ if (!r.path || !this.paths) return+ speed.save({ key: a.key, ...r.result, parakeet: a.pkRtf ?? speed.load()?.parakeet, whisperTimed: true, at: Date.now() })+ this.paths = { ...this.paths, asr: r.path, asrCpu: r.result.cpu ? true : undefined, asrAfterMeeting: r.result.afterMeeting ? true : undefined, asrMulti: r.multiPath, asrMultiCpu: r.result.multi?.cpu ? true : undefined }+ console.info('ASR', `${r.result.model} reads the languages Parakeet does not cover${r.result.afterMeeting ? ', after the meeting' : ''}`)+ if (this.paths.asr !== this.paths.lid) this.whisperLanded()+ }+ this.speech = arrive().catch((err) => console.warn('ASR', 'Parakeet did not download yet; whisper keeps reading every language, and it is tried again at the next start', err))+ if (pk.deps.wantsWhisper()) this.wantWhisper()+ }+/*** The first notes model downloads while Yogurt already records: it is tried until it lands (meetings recorded* meanwhile get their notes then). The bigger one follows.diff --git a/app/src/shared/platform.ts b/app/src/shared/platform.tsindex e192dba6..d2a1812e 100644--- a/app/src/shared/platform.ts+++ b/app/src/shared/platform.ts@@ -44,10 +44,10 @@ export function platformOf(real: string, env: Record<string, string | undefined>return fake === 'darwin' || fake === 'win32' || fake === 'linux' ? fake : real}-export type HelperKind = 'system' | 'audio' | 'mcp' | 'whisper'+export type HelperKind = 'system' | 'audio' | 'mcp' | 'whisper' | 'parakeet'/** The helper programs in resources/bin. The Mac's system helper is yogurt-mac; on Windows and Linux it is yogurt-system. */export function helperFile(kind: HelperKind, platform: string): string {- const base = { system: platform === 'darwin' ? 'yogurt-mac' : 'yogurt-system', audio: 'yogurt-audio', mcp: 'yogurt-mcp', whisper: 'whisper-server' }[kind]+ const base = { system: platform === 'darwin' ? 'yogurt-mac' : 'yogurt-system', audio: 'yogurt-audio', mcp: 'yogurt-mcp', whisper: 'whisper-server', parakeet: 'parakeet-server' }[kind]return platform === 'win32' ? `${base}.exe` : base}diff --git a/app/test/builderConfig.test.ts b/app/test/builderConfig.test.tsindex 567cc2c5..83b2b36d 100644--- a/app/test/builderConfig.test.ts+++ b/app/test/builderConfig.test.ts@@ -37,10 +37,9 @@ it("only Windows and Linux carry the colour tray icons (the Mac's package keeps}})-it("only Windows and Linux carry the speed check's clip: a Mac never times its speech model", () => {- const block = (name: string) => config.match(new RegExp(`^${name}:\\n((?: .*\\n|\\n)*)`, 'm'))?.[1] ?? ''- for (const os of ['win', 'linux']) expect(block(os)).toContain('{ from: resources/speed, to: speed }')- expect(config.split(/^win:$/m)[0]).not.toContain('resources/speed')+it("every system carries the speed check's clip: Windows and Linux time their speech models on it, and a Mac tries Parakeet on it before using it", () => {+ // in the list every system's package gets (a system's own extra resources are added to it)+ expect(config.split(/^electronFuses:$/m)[0]).toContain('{ from: resources/speed, to: speed }')})it('the Linux build starts through the launcher that picks X11 on Wayland (#8)', () => {diff --git a/app/test/parakeet.test.ts b/app/test/parakeet.test.tsnew file mode 100644index 00000000..b2f9dfa7--- /dev/null+++ b/app/test/parakeet.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from 'vitest'+import { asrKillSwitch, engineFor, garbageSignal, garbageWatch, GARBAGE_CHUNKS, judgeable, PARAKEET_LANGUAGES, PARAKEET_MAX_PASS_S, parakeetCovers, parakeetPasses, parakeetSegments, type ParakeetToken } from '../src/main/asr/parakeet'+import { wholeSegments } from '../src/main/asr/transcribe'+import { chunker, type Chunk } from '../src/main/asr/chunker'++const tok = (text: string, start: number, end: number, logprob = -0.01): ParakeetToken => ({ text, start, end, logprob })++describe('the languages Parakeet covers', () => {+ it('is the 25 of Parakeet TDT v3', () => {+ expect(Object.keys(PARAKEET_LANGUAGES).sort()).toEqual(['bg', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fi', 'fr', 'hr', 'hu', 'it', 'lt', 'lv', 'mt', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sv', 'uk'])+ })+ it('knows them by code, by locale and by the name whisper gives its guesses', () => {+ for (const l of ['en', 'de', 'EN', 'de-AT', 'pt_BR', 'english', 'German', 'ukrainian', 'slovenian']) expect(parakeetCovers(l), l).toBe(true)+ })+ it('leaves every other language to whisper', () => {+ for (const l of ['ja', 'zh', 'ar', 'hi', 'ko', 'tr', 'japanese', 'chinese', 'arabic', 'hindi', 'norwegian', 'catalan', 'auto', '', undefined, null]) expect(parakeetCovers(l), String(l)).toBe(false)+ })+})++describe('which engine reads a track', () => {+ it('Parakeet for English only and for a track heard in a language it covers', () => {+ expect(engineFor({ parakeet: true, language: 'en' }).engine).toBe('parakeet')+ expect(engineFor({ parakeet: true, language: 'german' }).engine).toBe('parakeet')+ })+ it('whisper for other languages, and while the language is not known', () => {+ expect(engineFor({ parakeet: true, language: 'japanese' })).toMatchObject({ engine: 'whisper', why: expect.stringContaining('japanese') })+ expect(engineFor({ parakeet: true }).engine).toBe('whisper')+ })+ it('whisper when Parakeet is not there (not downloaded yet, too slow here, switched off), whatever the language', () => {+ expect(engineFor({ parakeet: false, language: 'en' }).engine).toBe('whisper')+ })+ it('whisper for a track Parakeet read as gibberish', () => {+ expect(engineFor({ parakeet: true, language: 'en', fellBack: true }).engine).toBe('whisper')+ })+})++describe('the kill switch', () => {+ it('YOGURT_ASR=whisper, or "asr": "whisper" in the settings file, turns Parakeet off and says which', () => {+ expect(asrKillSwitch({ YOGURT_ASR: 'whisper' })).toBe('YOGURT_ASR=whisper')+ expect(asrKillSwitch({ YOGURT_ASR: ' Whisper ' })).toBeTruthy()+ expect(asrKillSwitch({}, { asr: 'whisper' })).toContain('settings.json')+ })+ it('anything else leaves it on', () => {+ expect(asrKillSwitch({})).toBeNull()+ expect(asrKillSwitch({ YOGURT_ASR: 'parakeet' }, { asr: 'auto' })).toBeNull()+ expect(asrKillSwitch({ YOGURT_ASR: '' }, { asr: 1 })).toBeNull()+ })+})++describe("Parakeet's tokens as lines", () => {+ const tokens = [tok('▁H', 0.64, 0.96), tok('owe', 0.96, 1.28), tok('ver', 1.28, 1.52), tok(',', 1.52, 1.52), tok('▁due', 1.76, 2.08), tok('▁to', 2.08, 2.16), tok('▁it', 2.2, 2.3), tok('.', 2.3, 2.3),+ tok('▁Is', 3.0, 3.2), tok('▁that', 3.2, 3.5), tok('▁so', 3.5, 3.8), tok('?', 3.8, 3.8), tok('▁Yes', 4.4, 4.9)]+ it('a line per sentence, with times, each starting with a space like whisper\'s', () => {+ const segs = parakeetSegments(tokens)+ expect(segs.map((s) => s.text)).toEqual([' However, due to it.', ' Is that so?', ' Yes'])+ expect(segs.map((s) => [s.start, s.end])).toEqual([[0.64, 2.3], [3.0, 3.8], [4.4, 4.9]])+ })+ it('words with their own times, pieces of a word and its punctuation joined', () => {+ const [first] = parakeetSegments(tokens)+ expect(first.words).toEqual([{ word: ' However,', start: 0.64, end: 1.52 }, { word: ' due', start: 1.76, end: 2.08 }, { word: ' to', start: 2.08, end: 2.16 }, { word: ' it.', start: 2.2, end: 2.3 }])+ })+ it('stays whole through the split-word join whisper needs (no line is glued to the one before)', () => {+ const segs = parakeetSegments(tokens)+ expect(wholeSegments(segs).map((s) => s.text)).toEqual(segs.map((s) => s.text))+ })+ it('nothing heard is no lines; control pieces are not text', () => {+ expect(parakeetSegments([])).toEqual([])+ expect(parakeetSegments([tok('<unk>', 0, 0.1), tok('▁Hi', 0.2, 0.4)]).map((s) => s.text)).toEqual([' Hi'])+ })+ it('an abbreviation\'s full stop inside a word ends no line', () => {+ expect(parakeetSegments([tok('▁v', 0, 0.1), tok('1.', 0.1, 0.2), tok('5', 0.2, 0.3), tok('▁is', 0.4, 0.5), tok('▁out', 0.5, 0.6), tok('.', 0.6, 0.6)]).map((s) => s.text)).toEqual([' v1.5 is out.'])+ })+})++describe('the sign that Parakeet is reading a language it does not know', () => {+ const sure = Array.from({ length: 36 }, (_, i) => tok('▁a', i * 0.25, i * 0.25 + 0.2, -0.004))+ it('sure tokens at a talking pace are fine', () => {+ expect(garbageSignal(sure, 10)).toMatchObject({ flagged: false, tokensPerSecond: 3.6 })+ })+ it('unsure tokens (a mean log-probability under -0.2) are flagged', () => {+ const r = garbageSignal(sure.map((t) => ({ ...t, logprob: -0.76 })), 10)+ expect(r.flagged).toBe(true)+ expect(r.meanLogprob).toBeCloseTo(-0.76)+ })+ it('too few tokens for the time (under 1.5 a second) are flagged, and so is none at all', () => {+ expect(garbageSignal(sure.slice(0, 14), 10).flagged).toBe(true)+ expect(garbageSignal(sure.slice(0, 15), 10).flagged).toBe(false)+ expect(garbageSignal([], 10)).toMatchObject({ flagged: true, meanLogprob: null })+ })+})++describe('falling back to whisper', () => {+ it('takes several bad chunks in a row', () => {+ const w = garbageWatch()+ expect(GARBAGE_CHUNKS).toBe(3)+ expect(w.saw('them', true)).toBe(false)+ expect(w.saw('them', true)).toBe(false)+ expect(w.saw('them', true)).toBe(true)+ })+ it('a good chunk in between starts the count again', () => {+ const w = garbageWatch()+ w.saw('them', true); w.saw('them', true)+ expect(w.saw('them', false)).toBe(false)+ expect(w.saw('them', true)).toBe(false)+ expect(w.saw('them', true)).toBe(false)+ expect(w.saw('them', true)).toBe(true)+ })+ it('each track is counted on its own, and the count starts over after a fall back', () => {+ const w = garbageWatch()+ w.saw('them', true); w.saw('them', true)+ expect(w.saw('me', true)).toBe(false)+ expect(w.saw('them', true)).toBe(true)+ expect(w.saw('them', true)).toBe(false)+ })+ it('only chunks of 5 s or more with someone clearly talking are judged: shorter ones are flagged by chance', () => {+ const chunk = (seconds: number, clearMs?: number) => ({ samples: new Float32Array(seconds * 16000), clearMs })+ expect(judgeable(chunk(10, 4000))).toBe(true)+ expect(judgeable(chunk(5, 1000))).toBe(true)+ expect(judgeable(chunk(4.9, 4000))).toBe(false)+ // a long faint sound, and a chunk nobody measured+ expect(judgeable(chunk(12, 300))).toBe(false)+ expect(judgeable(chunk(12))).toBe(false)+ })+})++describe('how much audio Parakeet gets at once', () => {+ const noise = (seconds: number) => Float32Array.from({ length: seconds * 16000 }, (_, i) => Math.sin(i / 7) * 0.3)+ it('15 s or less goes in one pass', () => {+ expect(PARAKEET_MAX_PASS_S).toBe(15)+ const one = parakeetPasses(noise(15))+ expect(one).toHaveLength(1)+ expect(one[0]).toMatchObject({ offset: 0 })+ expect(one[0].samples.length).toBe(15 * 16000)+ })+ it('longer audio is cut into passes of 15 s at most, at the quietest spot of each one\'s last 2 s, losing nothing', () => {+ const x = noise(40)+ // a pause from 13.5 s to 13.9 s+ x.fill(0, 13.5 * 16000, 13.9 * 16000)+ const passes = parakeetPasses(x)+ expect(passes.length).toBeGreaterThanOrEqual(3)+ for (const p of passes) expect(p.samples.length).toBeLessThanOrEqual(15 * 16000)+ expect(passes[1].offset / 16000).toBeGreaterThanOrEqual(13.5)+ expect(passes[1].offset / 16000).toBeLessThanOrEqual(13.9)+ expect(passes.reduce((n, p) => n + p.samples.length, 0)).toBe(x.length)+ passes.reduce((at, p) => { expect(p.offset).toBe(at); return at + p.samples.length }, 0)+ })+ it('the chunker itself never hands over more than 15 s, however long someone talks', () => {+ const chunks: Chunk[] = []+ const cut = chunker((c) => chunks.push(c))+ const talk = noise(50)+ for (let i = 0; i < talk.length; i += 1600) cut.push('them', i / 16, talk.subarray(i, i + 1600))+ cut.flush()+ expect(chunks.length).toBeGreaterThanOrEqual(4)+ for (const c of chunks) expect(c.samples.length / 16000).toBeLessThanOrEqual(PARAKEET_MAX_PASS_S)+ })+})diff --git a/app/test/parakeetServer.test.ts b/app/test/parakeetServer.test.tsnew file mode 100644index 00000000..d1d1085e--- /dev/null+++ b/app/test/parakeetServer.test.ts@@ -0,0 +1,157 @@+import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:http'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { createRequire } from 'node:module'+import { afterEach, describe, expect, it } from 'vitest'+import { createWhisperServer, killStale } from '../src/main/asr/server'+import { fakeParakeetMeasure, fakeParakeetTry, measureParakeet } from '../src/main/asr/speedCheck'+import { wavBytes } from '../src/main/asr/transcribe'+import type { WhisperServer } from '../src/main/asr/server'+import { helperFile } from '../src/shared/platform'+import bundled from '../../catalog/catalog.json'+import licenses from '../../catalog/licenses.json'++const dir = () => mkdtempSync(join(tmpdir(), 'yogurt-pk-'))++/** a stand-in for the parakeet-server program: writes down its arguments and answers GET / */+function fakeBinary() {+ const d = dir(), js = join(d, 'pk.js')+ writeFileSync(js, `+ const fs = require('fs'), a = process.argv+ fs.writeFileSync(${JSON.stringify(join(d, 'args'))}, JSON.stringify(a.slice(2)))+ process.stderr.write('parakeet_backend_init_gpu: using MTL0 backend\\n')+ require('http').createServer((q, r) => { if (q.method === 'POST') { q.resume(); r.statusCode = 500; return r.end('{}') } r.end('ok') }).listen(Number(a[a.indexOf('--port') + 1]), a[a.indexOf('--host') + 1])+ `)+ const bin = join(d, 'parakeet-server')+ writeFileSync(bin, `#!/bin/sh\nexec "${process.execPath}" "${js}" "$@"\n`)+ chmodSync(bin, 0o755)+ return { bin, args: () => JSON.parse(readFileSync(join(d, 'args'), 'utf8')) as string[] }+}++describe('parakeet-server', () => {+ it('is a helper next to whisper-server on every system', () => {+ expect(helperFile('parakeet', 'darwin')).toBe('parakeet-server')+ expect(helperFile('parakeet', 'linux')).toBe('parakeet-server')+ expect(helperFile('parakeet', 'win32')).toBe('parakeet-server.exe')+ })+ // the stand-in is a shell script, which Windows can't start+ it.skipIf(process.platform === 'win32')('is started with the model, the address and the threads: no beam and no VAD, which it does not have; -ng keeps it on the processor', async () => {+ const f = fakeBinary()+ const s = createWhisperServer({ binary: f.bin, engine: 'parakeet', model: '/m/pk.bin', vadModel: '/vad.bin', cpuOnly: true, pidFile: join(dir(), 'parakeet-server.pid') })+ try {+ expect(await s.url()).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)+ const a = f.args()+ expect(a.slice(0, 4)).toEqual(['-m', '/m/pk.bin', '--host', '127.0.0.1'])+ expect(a).toContain('-t')+ expect(a).toContain('-ng')+ for (const no of ['-bs', '--vad', '-vm']) expect(a).not.toContain(no)+ } finally { await s.stop() }+ })+ it('one left over from a Yogurt that was killed is cleaned up like a whisper-server; another program with that pid is left alone', () => {+ const killed: number[] = []+ const run = (name: string) => { const f = join(dir(), 'x.pid'); writeFileSync(f, '4242'); killStale(f, { name: () => name, kill: (pid) => killed.push(pid) }); return existsSync(f) }+ expect(run('/Applications/Yogurt.app/Contents/Resources/bin/parakeet-server')).toBe(false)+ expect(run('parakeet-server.exe')).toBe(false)+ expect(killed).toEqual([4242, 4242])+ run('Safari')+ expect(killed).toHaveLength(2)+ })+ it('is signed like whisper-server: with no entitlements of its own', () => {+ const { helperEntitlements } = createRequire(import.meta.url)('../scripts/sign.cjs') as { helperEntitlements(file: string, buildDir: string): string | null }+ expect(helperEntitlements('/x/Yogurt.app/Contents/Resources/bin/parakeet-server', '/build')).toBe(join('/build', 'entitlements.none.plist'))+ })+})++describe('timing Parakeet for the speed check', () => {+ let close: (() => void) | undefined+ afterEach(() => close?.())+ /** a stand-in parakeet-server: each reading after the first (the warm-up) takes delayMs and gives these words */+ async function standIn(delayMs: number, words = 'ask not what your country can do') {+ let asked = 0+ const http = createServer((req, res) => {+ req.resume()+ req.on('end', () => {+ const n = asked+++ const tokens = words.split(' ').filter(Boolean).map((w, i) => ({ text: `▁${w}`, start: i * 0.3, end: i * 0.3 + 0.2, logprob: -0.01 }))+ setTimeout(() => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ duration: 1, text: words, tokens })) }, n === 0 ? 0 : delayMs)+ })+ })+ await new Promise<void>((r) => http.listen(0, '127.0.0.1', r))+ close = () => http.close()+ const url = `http://127.0.0.1:${(http.address() as { port: number }).port}`+ let stopped = false+ return { srv: { url: async () => url, stop: async () => { stopped = true }, cpuOnly: true } as unknown as WhisperServer, asked: () => asked, stopped: () => stopped }+ }+ const clip = (seconds: number) => { const f = join(dir(), 'clip.wav'); writeFileSync(f, wavBytes(new Float32Array(seconds * 16000))); return f }++ it('by the whisper models\' rules: one reading of the clip over its length, after a warm-up that is not counted; the server is stopped after', async () => {+ const s = await standIn(200)+ const rtf = await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })+ expect(rtf).toBeGreaterThan(0.15)+ expect(rtf).toBeLessThan(0.5)+ expect(s.asked()).toBe(2)+ expect(s.stopped()).toBe(true)+ })+ it('longer than twice the clip is stopped: too slow', async () => {+ const s = await standIn(2500)+ expect(await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })).toBeNull()+ expect(s.stopped()).toBe(true)+ })+ it('a Parakeet that hears no words in the clip is never picked, however fast', async () => {+ const s = await standIn(10, '')+ expect(await measureParakeet('/m/pk.bin', { binary: 'x', clip: clip(1), server: () => s.srv })).toBeNull()+ })+ // the stand-in is a shell script, which Windows can't start+ it.skipIf(process.platform === 'win32')('runs the way meetings will: on the processor where asked (Windows and Linux), with the graphics on a Mac; its pid is kept while it runs, so one left behind by a quit is cleaned up', async () => {+ const f = fakeBinary()+ const pidFile = join(dir(), 'speech-timing.pid')+ // one left by a Yogurt that quit while timing (the pid is nobody's now): cleared when the next one starts+ writeFileSync(pidFile, '999999')+ // the stand-in answers no readings: the try fails, after the program was started as asked+ await expect(measureParakeet('/m/pk.bin', { binary: f.bin, clip: clip(1), cpu: true, pidFile })).rejects.toThrow()+ expect(f.args()).toContain('-ng')+ expect(existsSync(pidFile)).toBe(false)+ await expect(measureParakeet('/m/pk.bin', { binary: f.bin, clip: clip(1), pidFile })).rejects.toThrow()+ expect(f.args()).not.toContain('-ng')+ expect(existsSync(pidFile)).toBe(false)+ })+ it('fake mode: Parakeet gets the time every model gets, or its own', async () => {+ const path = '/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin'+ expect(await fakeParakeetMeasure('')(path)).toBe(0.1)+ expect(await fakeParakeetMeasure('2')(path)).toBe(2)+ expect(await fakeParakeetMeasure('slow')(path)).toBeNull()+ expect(await fakeParakeetMeasure('parakeet-tdt-0.6b-v3-q8_0=0.8,whisper-small-q5_1=1.4')(path)).toBe(0.8)+ expect(await fakeParakeetMeasure('whisper-small-q5_1=1.4')(path)).toBe(0.1)+ // a Mac's try knows no times, and either can be told the helper is broken or hears nothing+ expect(await fakeParakeetTry()(path)).toBe(0.1)+ await expect(fakeParakeetMeasure('', 'broken')(path)).rejects.toThrow(/could not start/)+ await expect(fakeParakeetTry('broken')(path)).rejects.toThrow(/could not start/)+ expect(await fakeParakeetTry('deaf')(path)).toBeNull()+ })+})++describe('the credit Parakeet\'s licence asks for', () => {+ const root = join(__dirname, '../..')+ it('the catalog names NVIDIA, the licence (CC-BY-4.0, on the allowed list) and that the weights are converted', () => {+ const p = bundled.parakeet+ expect(p.license).toBe('CC-BY-4.0')+ expect(licenses).toContain('CC-BY-4.0')+ expect(p.attribution).toMatch(/NVIDIA/)+ expect(p.attribution).toMatch(/CC BY 4\.0/)+ expect(p.attribution).toMatch(/converted/i)+ expect(p.attribution).toContain('ggml-org/parakeet-GGUF')+ })+ it('the licences shipped with the app have its credit, the converted-weights note and the licence text', () => {+ const text = readFileSync(join(root, 'app/resources/licenses/parakeet-tdt-0.6b-v3-CC-BY-4.0.txt'), 'utf8')+ expect(text).toMatch(/Parakeet TDT 0\.6B v3 by NVIDIA/)+ expect(text).toMatch(/converted\s+weights/i)+ expect(text).toContain('35156454d1a39de06863303dd209fd2bed6ee079')+ expect(text).toContain('Creative Commons Attribution 4.0 International Public License')+ })+ it('the third-party notices list it with the other models', () => {+ const notices = readFileSync(join(root, 'THIRD_PARTY_NOTICES.md'), 'utf8')+ expect(notices).toMatch(/Parakeet TDT 0\.6B v3.*NVIDIA.*CC BY 4\.0/)+ expect(notices).toMatch(/converted weights/)+ })+})diff --git a/app/test/plainNodeSpeech.test.ts b/app/test/plainNodeSpeech.test.tsindex a20bf987..abe87df0 100644--- a/app/test/plainNodeSpeech.test.ts+++ b/app/test/plainNodeSpeech.test.ts@@ -8,7 +8,8 @@ import { expect, it } from 'vitest'// The release build runs the speech engine's sources in plain Node (scripts/whisper-smoke.mjs,// scripts/speed-check-smoke.mjs). Anything they import must load without the bundler: one import of the// translations (import.meta.glob) there stopped the 0.3.85 Windows and Linux builds.-const LOADED_BY_SMOKE = ['src/main/asr/server.ts', 'src/main/asr/speedCheck.ts']+// Parakeet's logic and the transcriber come in through both; the picker's speed rules are loaded by the speed check's smoke script itself+const LOADED_BY_SMOKE = ['src/main/asr/server.ts', 'src/main/asr/speedCheck.ts', 'src/main/asr/transcribe.ts', 'src/main/asr/parakeet.ts', '../packages/picker/src/asr.ts']it.each(LOADED_BY_SMOKE)('%s loads in plain Node, as the release smoke tests load it', (file) => {const dir = mkdtempSync(join(tmpdir(), 'yogurt-plain-node-'))diff --git a/app/test/reread.test.ts b/app/test/reread.test.tsnew file mode 100644index 00000000..ff40358a--- /dev/null+++ b/app/test/reread.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest'+import { createRereads } from '../src/main/asr/reread'++/** meetings by id: still being recorded or finished, with or without a kept recording */+function rig(o: { ready?: boolean } = {}) {+ let list: string[] = []+ const meetings = new Map<string, { busy?: boolean; audio?: boolean }>()+ const started: string[] = []+ const state = { ready: o.ready ?? false }+ const r = createRereads({+ load: () => list, save: (ids) => { list = ids }, ready: () => state.ready,+ meeting: (id) => { const m = meetings.get(id); return m ? { busy: !!m.busy, audio: m.audio !== false } : null },+ start: (id) => { started.push(id); return true },+ })+ return { r, meetings, started, state, list: () => list }+}++describe('meetings the small whisper had to read (the bigger one was not downloaded yet)', () => {+ it('are remembered, once each, and read again from their recording when the bigger whisper is in and they have ended', async () => {+ const t = rig()+ t.meetings.set('a', { busy: true })+ t.r.note('a'); t.r.note('a')+ expect(t.list()).toEqual(['a'])+ // not in yet+ await t.r.run()+ expect(t.started).toEqual([])+ // in, but the meeting still runs+ t.state.ready = true+ await t.r.run()+ expect(t.started).toEqual([])+ expect(t.list()).toEqual(['a'])+ t.meetings.set('a', {})+ await t.r.run()+ expect(t.started).toEqual(['a'])+ expect(t.list()).toEqual([])+ // only once+ await t.r.run()+ expect(t.started).toEqual(['a'])+ })+ it('one that was deleted, or whose recording was not kept, is let go without an error', async () => {+ const t = rig({ ready: true })+ t.meetings.set('kept', {}); t.meetings.set('no-audio', { audio: false })+ for (const id of ['gone', 'no-audio', 'kept']) t.r.note(id)+ await t.r.run()+ expect(t.started).toEqual(['kept'])+ expect(t.list()).toEqual([])+ })+ it('says which meetings it started, so their unedited notes can be written again from the better transcript', async () => {+ const t = rig({ ready: true })+ t.meetings.set('a', {})+ t.r.note('a')+ expect(t.r.reread('a')).toBe(false)+ await t.r.run()+ expect(t.r.reread('a')).toBe(true)+ // asked once+ expect(t.r.reread('a')).toBe(false)+ })+ it('a start that did not take (something else is transcribing it) is tried again later', async () => {+ let list: string[] = []+ let ok = false+ const started: string[] = []+ const r = createRereads({ load: () => list, save: (ids) => { list = ids }, ready: () => true, meeting: () => ({ busy: false, audio: true }), start: (id) => { started.push(id); return ok } })+ r.note('a')+ await r.run()+ expect(list).toEqual(['a'])+ ok = true+ await r.run()+ expect(list).toEqual([])+ expect(started).toEqual(['a', 'a'])+ })+})diff --git a/app/test/setupParakeet.test.ts b/app/test/setupParakeet.test.tsnew file mode 100644index 00000000..0dbfbc3e--- /dev/null+++ b/app/test/setupParakeet.test.ts@@ -0,0 +1,437 @@+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'+import { speedKey, validateCatalog, type Catalog, type Hardware } from '@yogurt/picker'+import bundled from '../../catalog/catalog.json'+import licenses from '../../catalog/licenses.json'+import { SetupController, type ParakeetDeps, type SetupDeps, type SpeedDeps, type SpeedResult } from '../src/main/setup'+import { fakeDownloadDeps } from '../src/main/fake'+import { ChecksumError, type DownloadDeps } from '../src/main/downloader'++const catalog = bundled as unknown as Catalog+const mac: Hardware = { os: 'darwin', arch: 'arm64', cpuModel: 'Apple M1 Max', totalRamGB: 32, freeDiskGB: 500, gpu: { kind: 'unified', name: 'Apple M1 Max', vramGB: 24 } }+const cpuPc: Hardware = { os: 'win32', arch: 'x64', cpuModel: 'Intel Core i5-1135G7', totalRamGB: 16, freeDiskGB: 500, gpu: { kind: 'none', name: '', vramGB: 0 }, cores: 8 }+const gpuPc: Hardware = { os: 'linux', arch: 'x64', cpuModel: 'AMD Ryzen 5 5600X', totalRamGB: 16, freeDiskGB: 500, gpu: { kind: 'discrete', name: 'NVIDIA GeForce RTX 3060', vramGB: 12 }, cores: 12 }++const file = (url: string) => decodeURIComponent(new URL(url).pathname.split('/').pop()!)+const asr = (id: string) => catalog.asr.find((a) => a.id === id)!+const PARAKEET = file(catalog.parakeet!.url), BASE = file(asr('whisper-base-q5_1').url), SMALL = file(asr('whisper-small-q5_1').url), TURBO = file(asr('whisper-large-v3-turbo-q5_0').url)++/** downloads that record what was asked for; `hold` keeps chosen files back until released, `fail` makes them arrive damaged */+function recorder(o: { hold?: (name: string) => boolean; fail?: (name: string) => boolean } = {}) {+ const asked: string[] = []+ const released: (() => void)[] = []+ const inner = fakeDownloadDeps({ stepMs: 0 })+ const download: DownloadDeps['download'] = async (url, dir, name, onProgress, signal) => {+ asked.push(file(url))+ if (o.hold?.(file(url))) await new Promise<void>((r) => released.push(r))+ if (o.fail?.(file(url))) throw new ChecksumError('damaged')+ return inner.download(url, dir, name, onProgress, signal)+ }+ return { asked, release: () => released.splice(0).forEach((r) => r()), deps: { ...inner, download } as DownloadDeps }+}++const parakeet = (over: Partial<ParakeetDeps> = {}): ParakeetDeps => ({ off: () => null, wantsWhisper: () => false, quietPollMs: 1, ...over })++/** a profile that already transcribes with these whisper models, as every install before Parakeet does */+function profileWith(...names: string[]) {+ const root = mkdtempSync(join(tmpdir(), 'yogurt-setup-pk-'))+ mkdirSync(join(root, 'asr'), { recursive: true })+ for (const n of names) { writeFileSync(join(root, 'asr', n), 'fake'); writeFileSync(join(root, 'asr', n + '.ok'), 'FAKE') }+ return root+}++function setup(over: Partial<SetupDeps> = {}, rec = recorder()) {+ const root = over.modelsDir ?? mkdtempSync(join(tmpdir(), 'yogurt-setup-pk-'))+ const c = new SetupController({ getHardware: async () => mac, getCatalog: async () => catalog, modelsDir: root, download: rec.deps, sha256Override: 'FAKE', retryDelaysMs: [0, 0], parakeet: parakeet(), ...over })+ return { c, root, rec }+}++/** fake timings per whisper model file, kept in memory */+function speed(rtf: Record<string, number | null>, saved?: SpeedResult) {+ const timed: string[] = []+ let stored = saved+ const deps: SpeedDeps = {+ measure: async (path) => { const id = catalog.asr.find((a) => path.includes(file(a.url)))!.id; timed.push(id); return { rtf: rtf[id] ?? null } },+ load: () => stored, save: (r) => { stored = r },+ }+ return { deps, timed, stored: () => stored }+}++describe('the catalog', () => {+ it('has Parakeet TDT 0.6B v3 q8_0, pinned to a revision with its checksum and size, and names the whisper that hears languages', () => {+ const p = catalog.parakeet!+ expect(p.url).toBe('https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q8_0.bin')+ expect(p.sha256).toBe('4d64e9e96c2792186d072fde0034df0ad670cf680a2f53069052ead827fd600e')+ expect(p.bytes).toBe(668757119)+ expect(p.languageId).toBe('whisper-base-q5_1')+ expect(asr(p.languageId).bytes).toBeLessThan(70e6)+ expect(validateCatalog(bundled, licenses).ok).toBe(true)+ })+ it('a Parakeet entry that names no whisper in the catalog, or a licence not on the list, is refused', () => {+ const bad = validateCatalog({ ...bundled, parakeet: { ...bundled.parakeet, languageId: 'whisper-nowhere' } }, licenses)+ expect(bad.ok).toBe(false)+ expect(validateCatalog(bundled, licenses.filter((l) => l !== 'CC-BY-4.0')).ok).toBe(false)+ })+})++describe('a new install', () => {+ it('a Mac downloads Parakeet and whisper base, nothing bigger, and is ready', async () => {+ const { c, rec } = setup()+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(rec.asked.slice(0, 2)).toEqual([PARAKEET, BASE])+ expect(rec.asked).not.toContain(TURBO)+ expect(rec.asked).not.toContain(SMALL)+ const i = c.installed()!+ expect(i.parakeet).toContain(PARAKEET)+ expect(i.lid).toContain(BASE)+ // never without a whisper: the small one reads what Parakeet can't until a bigger one is wanted+ expect(i.asr).toBe(i.lid)+ })+ it('the next start finds both in place and downloads no speech model', async () => {+ const first = setup()+ await first.c.start(); await first.c.idle()+ const again = setup({ modelsDir: first.root })+ await again.c.start(); await again.c.idle()+ expect(again.rec.asked.filter((n) => n.endsWith('.bin'))).toEqual([])+ expect(again.c.installed()).toMatchObject({ parakeet: expect.stringContaining(PARAKEET), lid: expect.stringContaining(BASE) })+ })+ it('the bigger whisper comes in the background once a language Parakeet does not cover is wanted', async () => {+ const { c, rec } = setup()+ await c.start(); await c.idle()+ expect(rec.asked).not.toContain(TURBO)+ c.wantWhisper()+ c.wantWhisper()+ await c.idle()+ expect(rec.asked.filter((n) => n === TURBO)).toHaveLength(1)+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO), lid: expect.stringContaining(BASE), parakeet: expect.stringContaining(PARAKEET) })+ })+ it('wanted from the start (the computer speaks a language Parakeet does not cover): ready does not wait for it', async () => {+ const rec = recorder({ hold: (n) => n === TURBO })+ const { c } = setup({ parakeet: parakeet({ wantsWhisper: () => true }) }, rec)+ await c.start()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()!.asr).toContain(BASE)+ await vi.waitFor(() => expect(rec.asked).toContain(TURBO))+ rec.release()+ await c.idle()+ expect(c.installed()!.asr).toContain(TURBO)+ })+ it('Parakeet arriving damaged twice leaves nobody without transcription: whisper as before', async () => {+ const rec = recorder({ fail: (n) => n === PARAKEET })+ const { c } = setup({}, rec)+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()!.asr).toContain(TURBO)+ expect(c.installed()!.parakeet).toBeUndefined()+ })+})++describe('the kill switch', () => {+ it('with Parakeet off nothing of it is downloaded: turbo as before', async () => {+ const { c, rec } = setup({ parakeet: parakeet({ off: () => 'YOGURT_ASR=whisper' }) })+ const log = vi.spyOn(console, 'info').mockImplementation(() => {})+ try {+ await c.start(); await c.idle()+ expect(rec.asked[0]).toBe(TURBO)+ expect(rec.asked).not.toContain(PARAKEET)+ expect(c.installed()!.parakeet).toBeUndefined()+ expect(log.mock.calls.map((a) => a.join(' ')).join('\n')).toMatch(/ASR Parakeet is not used.*YOGURT_ASR=whisper/)+ } finally { log.mockRestore() }+ })+ it('switched off on an install that has Parakeet: its files stay, and whisper reads everything', async () => {+ const first = setup()+ await first.c.start(); await first.c.idle()+ const off = setup({ modelsDir: first.root, parakeet: parakeet({ off: () => 'YOGURT_ASR=whisper' }) })+ await off.c.start(); await off.c.idle()+ expect(off.c.installed()!.parakeet).toBeUndefined()+ expect(off.c.installed()!.asr).toContain(TURBO)+ expect(existsSync(join(first.root, 'asr', PARAKEET))).toBe(true)+ })+})++describe('an install from before Parakeet', () => {+ it('a Mac is ready at once on the whisper it has, and keeps it until Parakeet is downloaded and checked', async () => {+ const rec = recorder({ hold: (n) => n === PARAKEET })+ const { c } = setup({ modelsDir: profileWith(TURBO) }, rec)+ await c.start()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO) })+ expect(c.installed()!.parakeet).toBeUndefined()+ await vi.waitFor(() => expect(rec.asked).toContain(PARAKEET))+ // still downloading: whisper only+ expect(c.installed()!.parakeet).toBeUndefined()+ rec.release()+ await c.idle()+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO), parakeet: expect.stringContaining(PARAKEET), lid: expect.stringContaining(BASE) })+ expect(rec.asked).toContain(BASE)+ })+ it('a download that fails changes nothing, and the next start tries again', async () => {+ const root = profileWith(TURBO)+ const failing = recorder()+ const real = failing.deps.download+ failing.deps.download = async (url, ...rest) => { if (file(url) === PARAKEET) throw new Error('fetch failed'); return real(url, ...rest) }+ const first = setup({ modelsDir: root }, failing)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ await first.c.start(); await first.c.idle()+ expect(first.c.state.phase).toBe('ready')+ expect(first.c.installed()!.asr).toContain(TURBO)+ expect(first.c.installed()!.parakeet).toBeUndefined()+ } finally { warn.mockRestore() }+ const next = setup({ modelsDir: root })+ await next.c.start(); await next.c.idle()+ expect(next.c.installed()!.parakeet).toContain(PARAKEET)+ })+ it('once Parakeet is in, later starts use it from the beginning and keep the bigger whisper for other languages', async () => {+ const root = profileWith(TURBO)+ const first = setup({ modelsDir: root })+ await first.c.start(); await first.c.idle()+ const rec = recorder({ hold: () => true })+ const next = setup({ modelsDir: root }, rec)+ void next.c.start()+ await vi.waitFor(() => expect(next.c.state.phase).toBe('ready'))+ expect(next.c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO), parakeet: expect.stringContaining(PARAKEET), lid: expect.stringContaining(BASE) })+ rec.release()+ })+})++describe('Windows and Linux: Parakeet in the speed check', () => {+ const pkSpeed = (rtf: number | null) => { const timed: string[] = []; return { timed, measure: async (path: string) => { timed.push(path); return rtf } } }++ it('a new install on the processor alone: Parakeet is timed first, and where it keeps up it is the live engine, with whisper base beside it and no other whisper downloaded or timed', async () => {+ const s = speed({ 'whisper-small-q5_1': 0.9, 'whisper-base-q5_1': 0.3 })+ const pk = pkSpeed(0.21)+ const { c, rec } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pk.measure }) })+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(pk.timed).toHaveLength(1)+ expect(s.timed).toEqual([])+ expect(rec.asked.filter((n) => n.startsWith('ggml-'))).toEqual([PARAKEET, BASE])+ expect(c.installed()).toMatchObject({ parakeet: expect.stringContaining(PARAKEET), lid: expect.stringContaining(BASE), asr: expect.stringContaining(BASE) })+ expect(c.installed()!.asrAfterMeeting).toBeUndefined()+ expect(s.stored()).toMatchObject({ key: speedKey(cpuPc), parakeet: 0.21, whisperTimed: false })+ })+ it('the same rule as whisper: over half the clip\'s length does not keep up with two voices, so whisper is picked as before and Parakeet\'s file goes', async () => {+ const s = speed({ 'whisper-small-q5_1': 0.88 })+ const pk = pkSpeed(0.62)+ const { c, root } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pk.measure }) })+ await c.start(); await c.idle()+ expect(c.installed()!.parakeet).toBeUndefined()+ expect(c.installed()!.asr).toContain(SMALL)+ expect(s.timed).toEqual(['whisper-small-q5_1'])+ expect(existsSync(join(root, 'asr', PARAKEET))).toBe(false)+ expect(s.stored()).toMatchObject({ model: 'whisper-small-q5_1', parakeet: 0.62 })+ })+ it('out of time counts as too slow', async () => {+ const s = speed({ 'whisper-small-q5_1': 2, 'whisper-base-q5_1': 0.4 })+ const { c } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pkSpeed(null).measure }) })+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()!.parakeet).toBeUndefined()+ expect(c.installed()!.asr).toContain(BASE)+ })+ it('the stored result is used on the next start: nothing is timed or downloaded again', async () => {+ const s = speed({})+ const pk = pkSpeed(0.21)+ const first = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pk.measure }) })+ await first.c.start(); await first.c.idle()+ const again = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pk.measure }), modelsDir: first.root })+ await again.c.start(); await again.c.idle()+ expect(pk.timed).toHaveLength(1)+ expect(s.timed).toEqual([])+ expect(again.rec.asked.filter((n) => n.startsWith('ggml-'))).toEqual([])+ expect(again.c.installed()).toMatchObject({ parakeet: expect.stringContaining(PARAKEET), asr: expect.stringContaining(BASE) })+ })+ it('a language Parakeet does not cover turns up: the whisper models are timed then, while no meeting runs, and whisper base stays for hearing languages', async () => {+ const s = speed({ 'whisper-small-q5_1': 0.9 })+ let meeting = true+ const { c, root } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: pkSpeed(0.2).measure, quiet: () => !meeting }) })+ await c.start(); await c.idle()+ c.wantWhisper()+ await new Promise((r) => setTimeout(r, 20))+ expect(s.timed).toEqual([])+ meeting = false+ await c.idle()+ expect(s.timed).toEqual(['whisper-small-q5_1'])+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(SMALL), lid: expect.stringContaining(BASE), parakeet: expect.stringContaining(PARAKEET) })+ expect(existsSync(join(root, 'asr', BASE))).toBe(true)+ expect(s.stored()).toMatchObject({ model: 'whisper-small-q5_1', parakeet: 0.2, whisperTimed: true })+ })+ it('an install from before Parakeet keeps its whisper (here: one that only transcribes after the meeting); Parakeet is fetched, timed while no meeting runs, and takes over live when it keeps up', async () => {+ const saved: SpeedResult = { key: speedKey(cpuPc), model: 'whisper-small-q5_1', rtf: { 'whisper-small-q5_1': 1.6 }, afterMeeting: true, at: 1 }+ const s = speed({}, saved)+ const pk = pkSpeed(0.3)+ let meeting = true+ const rec = recorder({ hold: (n) => n === PARAKEET })+ const { c } = setup({ getHardware: async () => cpuPc, speed: s.deps, modelsDir: profileWith(SMALL), parakeet: parakeet({ measure: pk.measure, quiet: () => !meeting }) }, rec)+ await c.start()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(SMALL), asrAfterMeeting: true })+ expect(c.installed()!.parakeet).toBeUndefined()+ rec.release()+ await new Promise((r) => setTimeout(r, 20))+ // downloaded, but a meeting is on: not timed, not used+ expect(pk.timed).toHaveLength(0)+ expect(c.installed()!.parakeet).toBeUndefined()+ meeting = false+ await c.idle()+ expect(pk.timed).toHaveLength(1)+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(SMALL), asrAfterMeeting: true, parakeet: expect.stringContaining(PARAKEET), lid: expect.stringContaining(BASE) })+ expect(s.stored()).toMatchObject({ model: 'whisper-small-q5_1', afterMeeting: true, parakeet: 0.3 })+ expect(s.timed).toEqual([])+ })+ it('an install from before Parakeet where it is too slow: its file goes, whisper stays, and it is not fetched again', async () => {+ const saved: SpeedResult = { key: speedKey(gpuPc), model: 'whisper-large-v3-turbo-q5_0', rtf: { 'whisper-large-v3-turbo-q5_0': 0.1 }, at: 1 }+ const s = speed({}, saved)+ const root = profileWith(TURBO)+ const first = setup({ getHardware: async () => gpuPc, speed: s.deps, modelsDir: root, parakeet: parakeet({ measure: pkSpeed(0.8).measure }) })+ await first.c.start(); await first.c.idle()+ expect(first.c.installed()!.parakeet).toBeUndefined()+ expect(first.c.installed()!.asr).toContain(TURBO)+ expect(existsSync(join(root, 'asr', PARAKEET))).toBe(false)+ expect(s.stored()).toMatchObject({ parakeet: 0.8 })+ const next = setup({ getHardware: async () => gpuPc, speed: s.deps, modelsDir: root, parakeet: parakeet({ measure: pkSpeed(0.8).measure }) })+ await next.c.start(); await next.c.idle()+ expect(next.rec.asked).not.toContain(PARAKEET)+ })+ it('with a graphics card too: Parakeet on the processor for its languages, the whisper it had on the card for the rest', async () => {+ const saved: SpeedResult = { key: speedKey(gpuPc), model: 'whisper-large-v3-turbo-q5_0', rtf: { 'whisper-large-v3-turbo-q5_0': 0.1 }, at: 1 }+ const s = speed({}, saved)+ const { c } = setup({ getHardware: async () => gpuPc, speed: s.deps, modelsDir: profileWith(TURBO), parakeet: parakeet({ measure: pkSpeed(0.12).measure }) })+ await c.start(); await c.idle()+ expect(c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO), parakeet: expect.stringContaining(PARAKEET) })+ })+})++describe('Parakeet is tried before it is adopted', () => {+ const quiet = () => { const w = vi.spyOn(console, 'warn').mockImplementation(() => {}); return () => w.mockRestore() }++ it('Windows and Linux, a new install: a speed check that fails outright (the helper will not start) is no setup error; whisper is timed and picked as before', async () => {+ const restore = quiet()+ try {+ const s = speed({ 'whisper-small-q5_1': 0.4 })+ let tries = 0+ const { c, root } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: async () => { tries++; throw new Error('parakeet-server exited (3221225781)') } }) })+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()!.parakeet).toBeUndefined()+ expect(c.installed()!.asr).toContain(SMALL)+ expect(s.timed).toEqual(['whisper-small-q5_1'])+ // not a time: nothing is stored about Parakeet, so the next start tries it again (the file is still there)+ expect(s.stored()).toMatchObject({ model: 'whisper-small-q5_1' })+ expect(s.stored()).not.toHaveProperty('parakeet')+ expect(existsSync(join(root, 'asr', PARAKEET))).toBe(true)+ // the next start: it works now, and is adopted next to the whisper already picked+ const again = setup({ getHardware: async () => cpuPc, speed: s.deps, modelsDir: root, parakeet: parakeet({ measure: async () => 0.2 }) })+ await again.c.start(); await again.c.idle()+ expect(again.c.installed()).toMatchObject({ asr: expect.stringContaining(SMALL), parakeet: expect.stringContaining(PARAKEET) })+ expect(again.rec.asked).not.toContain(PARAKEET)+ expect(tries).toBe(1)+ } finally { restore() }+ })+ it('an install from before Parakeet: a failing try in the background changes nothing', async () => {+ const restore = quiet()+ try {+ const saved: SpeedResult = { key: speedKey(cpuPc), model: 'whisper-small-q5_1', rtf: { 'whisper-small-q5_1': 0.4 }, at: 1 }+ const s = speed({}, saved)+ const { c } = setup({ getHardware: async () => cpuPc, speed: s.deps, modelsDir: profileWith(SMALL), parakeet: parakeet({ measure: async () => { throw new Error('boom') } }) })+ await c.start(); await c.idle()+ expect(c.state.phase).toBe('ready')+ expect(c.installed()!.parakeet).toBeUndefined()+ expect(s.stored()).not.toHaveProperty('parakeet')+ } finally { restore() }+ })+ it('a Mac tries it once on the bundled clip, the way meetings run it, before a new install adopts it', async () => {+ const tried: string[] = []+ const first = setup({ parakeet: parakeet({ measure: async (m) => { tried.push(m); return 0.01 } }) })+ await first.c.start(); await first.c.idle()+ expect(tried).toHaveLength(1)+ expect(tried[0]).toContain(PARAKEET)+ expect(first.c.installed()!.parakeet).toContain(PARAKEET)+ expect(first.rec.asked).not.toContain(TURBO)+ // it passed: later starts don't try it again+ const next = setup({ modelsDir: first.root, parakeet: parakeet({ measure: async (m) => { tried.push(m); return 0.01 } }) })+ await next.c.start(); await next.c.idle()+ expect(tried).toHaveLength(1)+ expect(next.c.installed()!.parakeet).toContain(PARAKEET)+ })+ it('a Mac where it hears nothing in the clip, or will not run: not adopted, whisper as before, and tried again at the next start', async () => {+ const restore = quiet()+ try {+ for (const broken of [async () => null, async () => { throw new Error('Metal: no device') }]) {+ const first = setup({ parakeet: parakeet({ measure: broken }) })+ await first.c.start(); await first.c.idle()+ expect(first.c.state.phase).toBe('ready')+ expect(first.c.installed()!.parakeet).toBeUndefined()+ expect(first.c.installed()!.asr).toContain(TURBO)+ let tries = 0+ const next = setup({ modelsDir: first.root, parakeet: parakeet({ measure: async () => { tries++; return 0.01 } }) })+ await next.c.start(); await next.c.idle()+ expect(tries).toBe(1)+ expect(next.c.installed()).toMatchObject({ asr: expect.stringContaining(TURBO), parakeet: expect.stringContaining(PARAKEET) })+ }+ } finally { restore() }+ })+ it('a Mac from before Parakeet: downloaded in the background, tried, and only then used', async () => {+ const restore = quiet()+ try {+ const bad = setup({ modelsDir: profileWith(TURBO), parakeet: parakeet({ measure: async () => null }) })+ await bad.c.start(); await bad.c.idle()+ expect(bad.c.installed()!.parakeet).toBeUndefined()+ const good = setup({ modelsDir: profileWith(TURBO), parakeet: parakeet({ measure: async () => 0.01 }) })+ await good.c.start(); await good.c.idle()+ expect(good.c.installed()!.parakeet).toContain(PARAKEET)+ } finally { restore() }+ })+ it('a meeting that starts while Parakeet is timed in the background: that time is thrown away, and it is timed again once the meeting is over', async () => {+ const saved: SpeedResult = { key: speedKey(cpuPc), model: 'whisper-small-q5_1', rtf: { 'whisper-small-q5_1': 0.4 }, at: 1 }+ const s = speed({}, saved)+ let meeting = false, tries = 0+ const measure = async () => { tries++; if (tries === 1) { meeting = true; setTimeout(() => { meeting = false }, 30); return 0.9 } return 0.2 }+ const { c } = setup({ getHardware: async () => cpuPc, speed: s.deps, modelsDir: profileWith(SMALL), parakeet: parakeet({ measure, quiet: () => !meeting }) })+ await c.start(); await c.idle()+ expect(tries).toBe(2)+ expect(s.stored()).toMatchObject({ parakeet: 0.2 })+ expect(c.installed()!.parakeet).toContain(PARAKEET)+ })+ it('the same for the whisper models timed later: a time taken while a meeting started is not kept', async () => {+ let meeting = false, tries = 0+ const stored: { r?: SpeedResult } = {}+ const deps: SpeedDeps = {+ measure: async () => { tries++; if (tries === 1) { meeting = true; setTimeout(() => { meeting = false }, 30); return { rtf: 1.9 } } return { rtf: 0.3 } },+ load: () => stored.r, save: (r) => { stored.r = r },+ }+ const { c } = setup({ getHardware: async () => cpuPc, speed: deps, parakeet: parakeet({ measure: async () => 0.2, quiet: () => !meeting }) })+ await c.start(); await c.idle()+ c.wantWhisper()+ await c.idle()+ expect(tries).toBe(2)+ expect(stored.r).toMatchObject({ model: 'whisper-small-q5_1', rtf: { 'whisper-small-q5_1': 0.3 }, whisperTimed: true })+ expect(c.installed()!.asr).toContain(SMALL)+ })+ it('Windows and Linux: the bigger whisper starts downloading the moment it is wanted, even mid-meeting; only its timing waits', async () => {+ const s = speed({ 'whisper-small-q5_1': 0.3 })+ let meeting = true+ const { c, rec } = setup({ getHardware: async () => cpuPc, speed: s.deps, parakeet: parakeet({ measure: async () => 0.2, quiet: () => !meeting }) })+ await c.start(); await c.idle()+ c.wantWhisper()+ await vi.waitFor(() => expect(rec.asked).toContain(SMALL))+ expect(s.timed).toEqual([])+ meeting = false+ await c.idle()+ expect(s.timed).toEqual(['whisper-small-q5_1'])+ })+ it('tells when the bigger whisper is in, so meetings the small one read can be read again', async () => {+ const { c } = setup()+ const landed: number[] = []+ c.onWhisper(() => landed.push(1))+ await c.start(); await c.idle()+ expect(landed).toEqual([])+ c.wantWhisper()+ await c.idle()+ expect(landed).toEqual([1])+ })+})diff --git a/app/test/transcribeParakeet.test.ts b/app/test/transcribeParakeet.test.tsnew file mode 100644index 00000000..f0ca04c2--- /dev/null+++ b/app/test/transcribeParakeet.test.ts@@ -0,0 +1,353 @@+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { createParakeetReader, createTranscriber, PARAKEET_LOCK_MS } from '../src/main/asr/transcribe'+import type { Chunk } from '../src/main/asr/chunker'+import type { ParakeetToken } from '../src/main/asr/parakeet'++const servers: Server[] = []+afterEach(async () => { await Promise.all(servers.splice(0).map((s) => new Promise<void>((r) => s.close(() => r())))) })++/** a stand-in server: counts requests, remembers their form fields and audio length, answers what `reply` says */+async function stub(reply: (n: number, fields: Record<string, string>) => unknown) {+ const seen: Array<{ fields: Record<string, string>; samples: number }> = []+ const server = createServer((req, res) => {+ const parts: Buffer[] = []+ req.on('data', (d: Buffer) => parts.push(d))+ req.on('end', () => {+ const body = Buffer.concat(parts)+ const fields: Record<string, string> = {}+ for (const m of body.toString('latin1').matchAll(/name="([^"]+)"(?!; filename)\r\n\r\n([^\r]*)\r\n/g)) fields[m[1]] = m[2]+ const riff = body.indexOf('RIFF')+ seen.push({ fields, samples: body.readUInt32LE(riff + 40) / 2 })+ res.setHeader('content-type', 'application/json')+ const answer = reply(seen.length - 1, fields) as { __status?: number }+ if (answer?.__status) res.statusCode = answer.__status+ res.end(JSON.stringify(answer))+ })+ })+ servers.push(server)+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))+ return { url: async () => `http://127.0.0.1:${(server.address() as AddressInfo).port}`, seen }+}++/** whisper's answer: what it heard, in which language, how sure */+const whisperSays = (text: string, language = 'english', prob = 0.99) => ({ language, detected_language: language, detected_language_probability: prob, segments: text ? [{ start: 0.2, end: 2, text: ` ${text}`, avg_logprob: -0.1, no_speech_prob: 0.01 }] : [] })+/** Parakeet's answer: the words as sure tokens at a talking pace, or as the unsure ones of a language it doesn't know */+const parakeetSays = (text: string, logprob = -0.01) => {+ // pieces of two letters, the first of a word with its space+ const tokens: ParakeetToken[] = text.split(' ').filter(Boolean).flatMap((w) => (w.match(/.{1,2}/gu) ?? []).map((piece, i) => (i ? piece : `▁${piece}`)))+ .map((piece, i) => ({ text: piece, start: i * 0.1, end: i * 0.1 + 0.08, logprob }))+ return { duration: tokens.length * 0.1, text, tokens }+}+const GIBBERISH = 'Intannetodektaj tik kankjok sen citi Kensak Suratok u sorakka Gen Xiu no Ze detik show intannet odek tajtik kank jok sen citi'+/** a chunk with this much clear speech in it */+const chunk = (track: 'me' | 'them', startMs: number, sec = 10, clearMs = sec * 800): Chunk => ({ track, startMs, samples: new Float32Array(16000 * sec), clearMs })++describe("Parakeet's reader", () => {+ it('gives lines on meeting time with word times, like whisper\'s', async () => {+ const pk = await stub(() => ({ duration: 3, text: 'Hello there. Fine.', tokens: [+ { text: '▁Hel', start: 0.5, end: 0.7, logprob: -0.01 }, { text: 'lo', start: 0.7, end: 0.9, logprob: -0.01 }, { text: '▁there', start: 1.0, end: 1.3, logprob: -0.01 }, { text: '.', start: 1.3, end: 1.3, logprob: -0.01 },+ { text: '▁Fine', start: 2.0, end: 2.4, logprob: -0.01 }, { text: '.', start: 2.4, end: 2.4, logprob: -0.01 }] }))+ const r = await createParakeetReader(pk)(chunk('them', 60_000, 3))+ expect(r.lines).toEqual([+ { track: 'them', startMs: 60_500, endMs: 61_300, text: 'Hello there.', words: [{ text: ' Hello', startMs: 60_500, endMs: 60_900 }, { text: ' there.', startMs: 61_000, endMs: 61_300 }] },+ { track: 'them', startMs: 62_000, endMs: 62_400, text: 'Fine.', words: [{ text: ' Fine.', startMs: 62_000, endMs: 62_400 }] },+ ])+ expect(r.flagged).toBe(false)+ expect(pk.seen[0].fields.prompt).toBeUndefined()+ })+ it('never sends more than 15 s in one pass, and puts the passes back on one clock', async () => {+ const pk = await stub((n) => ({ duration: 15, text: n ? 'two' : 'one', tokens: [{ text: n ? '▁two.' : '▁one.', start: 1, end: 1.5, logprob: -0.01 }] }))+ const r = await createParakeetReader(pk)(chunk('them', 0, 28))+ expect(pk.seen).toHaveLength(2)+ for (const s of pk.seen) expect(s.samples / 16000).toBeLessThanOrEqual(15)+ expect(r.lines.map((l) => l.text)).toEqual(['one.', 'two.'])+ expect(r.lines[1].startMs).toBe(Math.round((pk.seen[0].samples / 16 + 1000)))+ })+})++describe('English only', () => {+ it('goes straight to Parakeet: whisper is never asked', async () => {+ const w = await stub(() => whisperSays('whisper heard this'))+ const pk = await stub(() => parakeetSays('Thanks for joining everyone.'))+ const engines: string[] = [], heard: string[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', onLanguage: (_t, l) => heard.push(l), parakeet: { url: pk.url, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`) } })+ expect((await tr(chunk('me', 0))).map((l) => l.text)).toEqual(['Thanks for joining everyone.'])+ await tr(chunk('me', 12_000), { partial: true })+ expect(w.seen).toHaveLength(0)+ expect(pk.seen).toHaveLength(2)+ expect(engines).toEqual(['me parakeet: Parakeet knows en'])+ expect(heard).toEqual(['english'])+ })+ it('a pinned language Parakeet does not cover stays with whisper', async () => {+ const w = await stub(() => whisperSays('こんにちは', 'japanese'))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))+ const tr = createTranscriber({ url: w.url, language: () => 'ja', parakeet: { url: pk.url } })+ expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual(['こんにちは'])+ expect(pk.seen).toHaveLength(0)+ expect(w.seen[0].fields.language).toBe('ja')+ })+ it('gibberish on several chunks in a row, where whisper hears a language Parakeet does not cover, sends the track back to whisper for good; the other track stays', async () => {+ const w = await stub(() => whisperSays('what whisper makes of it', 'japanese', 0.97))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.76))+ const engines: string[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })+ // each flagged chunk is read by whisper instead, so no gibberish is saved even before the track moves+ for (let i = 0; i < 3; i++) expect((await tr(chunk('them', i * 12_000))).map((l) => l.text)).toEqual(['what whisper makes of it'])+ expect(pk.seen).toHaveLength(3)+ await tr(chunk('them', 40_000))+ await tr(chunk('them', 52_000), { partial: true })+ expect(pk.seen).toHaveLength(3)+ expect(w.seen).toHaveLength(5)+ expect(engines).toEqual(['them parakeet', 'them whisper'])+ await tr(chunk('me', 60_000))+ expect(pk.seen).toHaveLength(4)+ })+ it('a noisy room: Parakeet unsure of chunk after chunk, but whisper hears English in them, so the track stays with Parakeet', async () => {+ const w = await stub(() => whisperSays('whisper reads the unsure ones', 'english', 0.9))+ let unsure = true+ const pk = await stub(() => (unsure ? parakeetSays('We can uh use uh the total topic for the music hyper scale that', -0.28) : parakeetSays('Now it is clear again, thanks for waiting everyone.')))+ const engines: string[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })+ for (let i = 0; i < 5; i++) expect((await tr(chunk('them', i * 12_000))).map((l) => l.text)).toEqual(['whisper reads the unsure ones'])+ unsure = false+ expect((await tr(chunk('them', 70_000))).map((l) => l.text)).toEqual(['Now it is clear again, thanks for waiting everyone.'])+ expect(engines).toEqual(['them parakeet'])+ expect(pk.seen).toHaveLength(6)+ })+ it('short flagged chunks change nothing: Parakeet keeps the track and its words', async () => {+ const w = await stub(() => whisperSays('whisper'))+ const pk = await stub(() => parakeetSays('Yeah sure', -0.5))+ // 2 s chunks: too short to judge+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url } })+ for (let i = 0; i < 6; i++) expect((await tr(chunk('them', i * 3000, 2))).map((l) => l.text)).toEqual(['Yeah sure'])+ expect(w.seen).toHaveLength(0)+ })+})++describe('Multi-language', () => {+ it('whisper hears the language of the first 10 s of speech; a covered one moves the track to Parakeet', async () => {+ const lid = await stub(() => whisperSays('hallo zusammen wir fangen an', 'german', 0.97))+ const big = await stub(() => whisperSays('never asked'))+ const pk = await stub(() => parakeetSays('Hallo zusammen, wir fangen an.'))+ const engines: string[] = [], heard: Array<[string, boolean]> = []+ const tr = createTranscriber({ url: big.url, onLanguage: (_t, l, _n, locked) => heard.push([l, locked]), parakeet: { url: pk.url, lid, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`) } })+ expect(PARAKEET_LOCK_MS).toBe(10_000)+ // 6 s heard: not locked yet, but the line is Parakeet's already (whisper is sure it is German)+ expect((await tr(chunk('them', 0, 6))).map((l) => l.text)).toEqual(['Hallo zusammen, wir fangen an.'])+ expect(engines).toEqual([])+ expect((await tr(chunk('them', 7000, 6))).map((l) => l.text)).toEqual(['Hallo zusammen, wir fangen an.'])+ expect(engines).toEqual(['them parakeet: Parakeet knows german'])+ expect(lid.seen).toHaveLength(2)+ expect(lid.seen[0].fields.language).toBe('auto')+ // locked: whisper is done with this track+ await tr(chunk('them', 14_000, 6))+ await tr(chunk('them', 21_000, 6), { partial: true })+ expect(lid.seen).toHaveLength(2)+ expect(big.seen).toHaveLength(0)+ expect(pk.seen).toHaveLength(4)+ expect(heard).toEqual([['german', false], ['german', false], ['german', true]])+ })+ it('a language Parakeet does not cover stays with whisper: the bigger model reads it, and a fetch of one is asked for', async () => {+ const lid = await stub(() => whisperSays('konnichiwa', 'japanese', 0.98))+ const big = await stub(() => whisperSays('こんにちは、始めましょう', 'japanese', 0.98))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))+ const engines: string[] = [], uncovered: string[] = []+ const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e, why) => engines.push(`${t} ${e}: ${why}`), onUncovered: (l) => uncovered.push(l) } })+ expect((await tr(chunk('them', 0, 12))).map((l) => l.text)).toEqual(['こんにちは、始めましょう'])+ expect(engines).toEqual(['them whisper: Parakeet does not know japanese'])+ expect(uncovered).toEqual(['japanese'])+ await tr(chunk('them', 13_000, 8))+ expect(pk.seen).toHaveLength(0)+ expect(lid.seen).toHaveLength(1)+ expect(big.seen.map((s) => s.fields.language)).toEqual(['japanese', 'japanese'])+ })+ it('with one whisper only (no bigger one on disk), it hears the language and reads what Parakeet cannot', async () => {+ const w = await stub(() => whisperSays('こんにちは', 'japanese', 0.98))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))+ const tr = createTranscriber({ url: w.url, parakeet: { url: pk.url } })+ expect((await tr(chunk('them', 0, 12))).map((l) => l.text)).toEqual(['こんにちは'])+ await tr(chunk('them', 13_000, 8))+ expect(w.seen.map((s) => s.fields.language)).toEqual(['auto', 'japanese'])+ expect(pk.seen).toHaveLength(0)+ })+ it('whisper unsure of the language, or Parakeet unsure of its own reading, keeps whisper\'s line before the lock', async () => {+ const lid = await stub((n) => (n === 0 ? whisperSays('maybe english', 'english', 0.55) : whisperSays('sure english now', 'english', 0.95)))+ const pk = await stub(() => parakeetSays('Mumble jumble', -0.6))+ const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })+ expect((await tr(chunk('me', 0, 3))).map((l) => l.text)).toEqual(['maybe english'])+ expect(pk.seen).toHaveLength(0)+ expect((await tr(chunk('me', 4000, 3))).map((l) => l.text)).toEqual(['sure english now'])+ expect(pk.seen).toHaveLength(1)+ })+ it('a track on Parakeet that turns to gibberish is heard again by whisper, and follows the language it is in now', async () => {+ let japanese = false+ const lid = await stub(() => (japanese ? whisperSays('nihongo', 'japanese', 0.98) : whisperSays('good morning all', 'english', 0.98)))+ const big = await stub(() => whisperSays('日本語で話します', 'japanese', 0.98))+ const pk = await stub(() => (japanese ? parakeetSays(GIBBERISH, -0.8) : parakeetSays('Good morning all, shall we start now?')))+ const engines: string[] = []+ const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e) => engines.push(`${t} ${e}`) } })+ await tr(chunk('them', 0, 12))+ expect(engines).toEqual(['them parakeet'])+ japanese = true+ // each gibberish chunk is read by whisper instead; the third in a row gives the track up+ for (let i = 1; i <= 3; i++) expect((await tr(chunk('them', i * 13_000, 12))).map((l) => l.text)).toEqual(['日本語で話します'])+ expect(engines).toEqual(['them parakeet', 'them whisper'])+ const asked = pk.seen.length+ await tr(chunk('them', 60_000, 12))+ expect(pk.seen).toHaveLength(asked)+ })+ it('one good chunk between flagged ones keeps the track on Parakeet', async () => {+ let bad = false+ const lid = await stub(() => whisperSays('good morning all', 'english', 0.98))+ const pk = await stub(() => (bad ? parakeetSays(GIBBERISH, -0.8) : parakeetSays('Good morning all, shall we start now?')))+ const engines: string[] = []+ const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })+ await tr(chunk('them', 0, 12))+ for (const flags of [true, true, false, true, true]) { bad = flags; await tr(chunk('them', 20_000, 12)) }+ expect(engines).toEqual(['them parakeet'])+ })+ it('each track has its own language and its own reader', async () => {+ const lid = await stub((_n, f) => whisperSays('x y z', f.language === 'auto' ? 'english' : f.language))+ const pk = await stub(() => parakeetSays('Fine by me, go ahead.'))+ const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })+ await tr(chunk('me', 0, 12))+ expect(pk.seen).toHaveLength(1)+ // the other track is not locked by that+ await tr(chunk('them', 0, 2), { partial: true })+ expect(lid.seen.at(-1)!.fields.language).toBe('auto')+ })+})++describe('without Parakeet (not downloaded yet, too slow here, or switched off)', () => {+ it('whisper reads everything and locks on the first clear chunk, as before', async () => {+ const w = await stub(() => whisperSays('hola a todos empezamos', 'spanish', 0.95))+ const tr = createTranscriber({ url: w.url })+ await tr(chunk('them', 0, 2))+ await tr(chunk('them', 3000, 2))+ expect(w.seen.map((s) => s.fields.language)).toEqual(['auto', 'spanish'])+ })+})++describe('parakeet-server fails while a meeting runs (it will not start, crashes, or answers with an error)', () => {+ const down = { __status: 500 }+ const quiet = () => { const w = vi.spyOn(console, 'warn').mockImplementation(() => {}); return () => w.mockRestore() }+ it('English only: whisper reads the chunk instead, and after two failures in a row the track stays with whisper', async () => {+ const restore = quiet()+ try {+ const w = await stub(() => whisperSays('whisper reads it'))+ const pk = await stub(() => down)+ const engines: string[] = [], failed: Array<{ never: boolean }> = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push({ never: f.never }) } })+ expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual(['whisper reads it'])+ expect((await tr(chunk('them', 12_000))).map((l) => l.text)).toEqual(['whisper reads it'])+ expect(engines).toEqual(['them parakeet', 'them whisper'])+ const asked = pk.seen.length+ expect((await tr(chunk('them', 24_000))).map((l) => l.text)).toEqual(['whisper reads it'])+ await tr(chunk('them', 36_000), { partial: true })+ expect(pk.seen).toHaveLength(asked)+ // Parakeet never answered once: the caller is told, so the next meetings start on whisper+ expect(failed).toEqual([{ never: true }])+ } finally { restore() }+ })+ it('one failure between good readings changes nothing', async () => {+ const restore = quiet()+ try {+ let broken = false+ const w = await stub(() => whisperSays('whisper covers the gap'))+ const pk = await stub(() => (broken ? down : parakeetSays('Parakeet reads this one fine, thanks.')))+ const engines: string[] = [], failed: unknown[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push(f) } })+ for (const b of [false, true, false, true, false]) { broken = b; expect((await tr(chunk('them', 0))).map((l) => l.text)).toEqual([b ? 'whisper covers the gap' : 'Parakeet reads this one fine, thanks.']) }+ expect(engines).toEqual(['them parakeet'])+ expect(failed).toEqual([])+ } finally { restore() }+ })+ it('Multi-language, a track locked on Parakeet: whisper reads in the locked language, and takes the track after two failures', async () => {+ const restore = quiet()+ try {+ let broken = false+ const lid = await stub(() => whisperSays('guten morgen zusammen', 'german', 0.97))+ const big = await stub(() => whisperSays('Guten Morgen zusammen (whisper)', 'german', 0.97))+ const pk = await stub(() => (broken ? down : parakeetSays('Guten Morgen zusammen, wir fangen an.')))+ const engines: string[] = [], failed: Array<{ never: boolean }> = []+ const tr = createTranscriber({ url: big.url, parakeet: { url: pk.url, lid, onEngine: (t, e) => engines.push(`${t} ${e}`), onFailed: (f) => failed.push({ never: f.never }) } })+ await tr(chunk('them', 0, 12))+ expect(engines).toEqual(['them parakeet'])+ broken = true+ expect((await tr(chunk('them', 13_000, 8))).map((l) => l.text)).toEqual(['Guten Morgen zusammen (whisper)'])+ expect((await tr(chunk('them', 22_000, 8))).map((l) => l.text)).toEqual(['Guten Morgen zusammen (whisper)'])+ expect(big.seen.map((x) => x.fields.language)).toEqual(['german', 'german'])+ expect(engines).toEqual(['them parakeet', 'them whisper'])+ const asked = pk.seen.length+ await tr(chunk('them', 31_000, 8))+ expect(pk.seen).toHaveLength(asked)+ // it had answered before: only this meeting's track leaves it+ expect(failed).toEqual([{ never: false }])+ } finally { restore() }+ })+ it('before the lock, whisper\'s finished reading is kept when Parakeet fails', async () => {+ const restore = quiet()+ try {+ const lid = await stub(() => whisperSays('good morning everyone', 'english', 0.97))+ const pk = await stub(() => down)+ const tr = createTranscriber({ url: lid.url, parakeet: { url: pk.url } })+ expect((await tr(chunk('me', 0, 4))).map((l) => l.text)).toEqual(['good morning everyone'])+ } finally { restore() }+ })+ it('a stopped transcription is not taken for a failing Parakeet', async () => {+ const w = await stub(() => whisperSays('never'))+ const pk = await stub(() => parakeetSays('never either'))+ const abort = new AbortController()+ abort.abort()+ const tr = createTranscriber({ url: w.url, language: () => 'en', signal: abort.signal, parakeet: { url: pk.url } })+ await expect(tr(chunk('them', 0))).rejects.toThrow()+ expect(w.seen).toHaveLength(0)+ })+})++describe('leaving Parakeet needs whisper to be sure of what it hears', () => {+ it('hold music or noise: Parakeet unsure and whisper only guessing at a language keeps an English only track on Parakeet', async () => {+ const restore = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const w = await stub(() => whisperSays('la la la', 'japanese', 0.41))+ let music = true+ const pk = await stub(() => (music ? parakeetSays(GIBBERISH, -0.6) : parakeetSays('Sorry about the wait, shall we begin now?')))+ const engines: string[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onEngine: (t, e) => engines.push(`${t} ${e}`) } })+ for (let i = 0; i < 6; i++) await tr(chunk('them', i * 12_000))+ music = false+ expect((await tr(chunk('them', 90_000))).map((l) => l.text)).toEqual(['Sorry about the wait, shall we begin now?'])+ expect(engines).toEqual(['them parakeet'])+ } finally { restore.mockRestore() }+ })+})++describe('a language Parakeet does not cover is told at once, so the bigger whisper can be fetched', () => {+ it('Multi-language: on the first chunk clearly heard in it, before the track is locked', async () => {+ const w = await stub(() => whisperSays('こんにちは', 'japanese', 0.95))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.8))+ const uncovered: string[] = []+ const tr = createTranscriber({ url: w.url, parakeet: { url: pk.url, onUncovered: (l) => uncovered.push(l) } })+ await tr(chunk('them', 0, 3))+ expect(uncovered).toEqual(['japanese'])+ await tr(chunk('them', 4000, 3))+ await tr(chunk('them', 8000, 12))+ // once per language+ expect(uncovered).toEqual(['japanese'])+ })+ it('English only: when a track falls off Parakeet because whisper hears another language', async () => {+ const restore = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const w = await stub(() => whisperSays('what whisper makes of it', 'hindi', 0.93))+ const pk = await stub(() => parakeetSays(GIBBERISH, -0.76))+ const uncovered: string[] = []+ const tr = createTranscriber({ url: w.url, language: () => 'en', parakeet: { url: pk.url, onUncovered: (l) => uncovered.push(l) } })+ await tr(chunk('them', 0)); await tr(chunk('them', 12_000))+ expect(uncovered).toEqual([])+ await tr(chunk('them', 24_000))+ expect(uncovered).toEqual(['hindi'])+ } finally { restore.mockRestore() }+ })+})diff --git a/app/test/transcriptionParakeet.test.ts b/app/test/transcriptionParakeet.test.tsnew file mode 100644index 00000000..6d5f3763--- /dev/null+++ b/app/test/transcriptionParakeet.test.ts@@ -0,0 +1,182 @@+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { forgetParakeetTrouble, hookTranscription, releaseIdleSpeech, settleTranscription, stopTranscriptionServer, transcribeRecorded } from '../src/main/asr'+import type { WhisperServer } from '../src/main/asr/server'+import type { Spoken } from '../src/shared/spoken'+import { openStore, type Meeting, type Store } from '../src/main/store'++// the session around the pipeline; the echo canceller is tested on its own+vi.mock('../src/main/asr/aec3', () => ({ loadAec3: async () => {}, aec3: vi.fn(() => null) }))++let store: Store+beforeEach(() => { store = openStore(':memory:') })+const meeting = (): Meeting => store.createMeeting({ title: 't', startedAt: 1, endedAt: null, eventId: null, app: null, attendees: [], state: 'recording' })+const disposers: Array<() => void> = []+afterEach(async () => { disposers.splice(0).forEach((d) => d()); await settleTranscription(2000); stopTranscriptionServer() })++/** stand-in speech servers, remembered by the model they were started for */+function fakeServers() {+ const made: Array<{ model: string; pidFile?: string; urls: number; stops: number }> = []+ const make = (model: string, pidFile?: string) => {+ const rec = { model, pidFile, urls: 0, stops: 0 }+ made.push(rec)+ return { url: async () => { rec.urls++; return 'http://127.0.0.1:1' }, resetBudget: () => {}, gpuAgain: () => false, timeoutMs: () => 30_000, timed: () => {}, tooSlow: false, cpuRtf: null, cpuOnly: false, wedged: async () => 'http://127.0.0.1:1', alive: async () => true, kill: () => {}, stop: async () => { rec.stops++ } } as unknown as WhisperServer+ }+ return { made, make, of: (model: string) => made.filter((m) => m.model === model) }+}++function hooks(o: { whisper: string; parakeet?: { model: string; lid: string }; spoken?: Spoken; off?: string | null; afterMeeting?: boolean }) {+ const s = fakeServers()+ const starts: Array<(m: Meeting) => void> = [], stops: Array<(m: Meeting) => void> = []+ const warns: string[] = []+ disposers.push(hookTranscription({+ store, modelPath: () => o.whisper, send: () => {}, warn: (c) => warns.push(c), server: s.make, serverIdleMs: 60_000, pidFile: join('/profile', 'whisper-server.pid'),+ parakeet: () => o.parakeet, parakeetOff: () => o.off ?? null, spoken: () => o.spoken ?? 'en', afterMeeting: () => !!o.afterMeeting,+ onStart: (fn) => { starts.push(fn) }, onStop: (fn) => { stops.push(fn) },+ }))+ return { s, warns, begin: (m: Meeting) => starts.forEach((f) => f(m)), end: async (m: Meeting) => { stops.forEach((f) => f(m)); await settleTranscription(2000) } }+}++/** what the log said under the ASR tag */+function asrLog() {+ const spy = vi.spyOn(console, 'info').mockImplementation(() => {})+ return { lines: () => spy.mock.calls.filter((a) => a[0] === 'ASR').map((a) => String(a[1])), restore: () => spy.mockRestore() }+}++describe('a meeting with Parakeet', () => {+ it('English only: parakeet-server is warmed up, whisper is not started at all, and the log says who reads and why', async () => {+ const log = asrLog()+ try {+ const h = hooks({ whisper: '/m/ggml-base-q5_1.bin', parakeet: { model: '/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin', lid: '/m/ggml-base-q5_1.bin' } })+ const m = meeting()+ h.begin(m)+ expect(h.s.of('/m/ggml-parakeet-tdt-0.6b-v3-q8_0.bin')[0]).toMatchObject({ urls: 1, pidFile: join('/profile', 'parakeet-server.pid') })+ expect(h.s.of('/m/ggml-base-q5_1.bin').reduce((n, x) => n + x.urls, 0)).toBe(0)+ expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/Parakeet \(ggml-parakeet-tdt-0\.6b-v3-q8_0\.bin\) reads both tracks, the language is given as en; whisper \(ggml-base-q5_1\.bin\) stands by/)+ await h.end(m)+ } finally { log.restore() }+ })+ it('Multi-language: Parakeet and the small whisper that hears languages are warmed up; the bigger whisper waits until a track needs it', async () => {+ const log = asrLog()+ try {+ const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, spoken: 'multi' })+ const m = meeting()+ h.begin(m)+ expect(h.s.of('/m/pk.bin')[0].urls).toBe(1)+ expect(h.s.of('/m/ggml-base-q5_1.bin')[0]).toMatchObject({ urls: 1, pidFile: join('/profile', 'whisper-server-lid.pid') })+ expect(h.s.of('/m/ggml-large-v3-turbo-q5_0.bin')[0].urls).toBe(0)+ expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/Multi-language: whisper \(ggml-base-q5_1\.bin\) hears each track's language first, then Parakeet \(pk\.bin\) reads the languages it covers and whisper \(ggml-large-v3-turbo-q5_0\.bin\) the rest/)+ await h.end(m)+ } finally { log.restore() }+ })+ it('Multi-language with only the small whisper: it hears the languages itself, and no third server is made', async () => {+ const h = hooks({ whisper: '/m/ggml-base-q5_1.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, spoken: 'multi' })+ const m = meeting()+ h.begin(m)+ expect(h.s.made.map((x) => x.model).sort()).toEqual(['/m/ggml-base-q5_1.bin', '/m/pk.bin'])+ expect(h.s.of('/m/ggml-base-q5_1.bin')[0].urls).toBe(1)+ await h.end(m)+ })+ it('a computer whose whisper only transcribes after the meeting is live with Parakeet', async () => {+ const h = hooks({ whisper: '/m/ggml-small-q5_1.bin', parakeet: { model: '/m/pk.bin', lid: '/m/ggml-base-q5_1.bin' }, afterMeeting: true })+ const m = meeting()+ h.begin(m)+ await new Promise((r) => setTimeout(r, 450))+ expect(h.warns).not.toContain('live-paused')+ await h.end(m)+ })+ it('every speech server goes when they are let go, and the next meeting starts new ones', async () => {+ const h = hooks({ whisper: '/m/turbo.bin', parakeet: { model: '/m/pk.bin', lid: '/m/base.bin' }, spoken: 'multi' })+ const a = meeting()+ h.begin(a); await h.end(a)+ await releaseIdleSpeech()+ expect(h.s.made.map((x) => x.stops)).toEqual([1, 1, 1])+ const b = meeting()+ h.begin(b)+ expect(h.s.made).toHaveLength(6)+ await h.end(b)+ })+})++describe('a meeting without Parakeet', () => {+ it('the kill switch: whisper reads every language as before, and the log says the switch is why', async () => {+ const log = asrLog()+ try {+ const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin', off: 'YOGURT_ASR=whisper' })+ const m = meeting()+ h.begin(m)+ expect(h.s.made.map((x) => x.model)).toEqual(['/m/ggml-large-v3-turbo-q5_0.bin'])+ expect(h.s.made[0].urls).toBe(1)+ expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/whisper \(ggml-large-v3-turbo-q5_0\.bin\) reads every language: YOGURT_ASR=whisper/)+ await h.end(m)+ } finally { log.restore() }+ })+ it('not downloaded yet (an install from before it): whisper as before, and the log says so', async () => {+ const log = asrLog()+ try {+ const h = hooks({ whisper: '/m/ggml-large-v3-turbo-q5_0.bin' })+ const m = meeting()+ h.begin(m)+ expect(h.s.made).toHaveLength(1)+ expect(log.lines().find((l) => l.startsWith('meeting start'))).toMatch(/reads every language: Parakeet is not in use on this computer/)+ await h.end(m)+ } finally { log.restore() }+ })+ it('a computer that transcribes after the meeting still does', async () => {+ const h = hooks({ whisper: '/m/ggml-small-q5_1.bin', afterMeeting: true })+ const m = meeting()+ h.begin(m)+ await vi.waitFor(() => expect(h.warns).toContain('live-paused'))+ await h.end(m)+ })+})++describe('parakeet-server will not start', () => {+ const RATE = 16000+ /** n phrases of 1 s of tone with 1 s of quiet after each, as a saved recording's track */+ async function* track(n: number) { for (let i = 0; i < n; i++) { yield Float32Array.from({ length: RATE }, (_, k) => 0.3 * Math.sin(k / 10)); yield new Float32Array(RATE) } }+ const http: Array<import('node:http').Server> = []+ afterEach(async () => { await Promise.all(http.splice(0).map((s) => new Promise<void>((r) => s.close(() => r())))); forgetParakeetTrouble() })+ /** a whisper that answers every chunk in English */+ async function whisper() {+ const { createServer } = await import('node:http')+ const s = createServer((req, res) => { req.resume(); req.on('end', () => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ detected_language: 'english', detected_language_probability: 0.99, segments: [{ start: 0, end: 1, text: ' Whisper read this' }] })) }) })+ http.push(s)+ await new Promise<void>((r) => s.listen(0, '127.0.0.1', r))+ return `http://127.0.0.1:${(s.address() as import('node:net').AddressInfo).port}`+ }++ it('the saved-recording pass (and Transcribe again) falls back to whisper, finishes whole, and the next meeting starts on whisper', async () => {+ const url = await whisper()+ const made: Array<{ model: string; urls: number }> = []+ const make = (model: string) => {+ const rec = { model, urls: 0 }+ made.push(rec)+ const dead = model.includes('parakeet')+ return { url: async () => { rec.urls++; if (dead) throw new Error('parakeet-server could not start: spawn ENOENT'); return url }, resetBudget: () => {}, gpuAgain: () => false, timeoutMs: () => 30_000, timed: () => {}, tooSlow: false, cpuRtf: null, cpuOnly: false, wedged: async () => { if (dead) throw new Error('parakeet-server stopped and will not be started again this meeting'); return url }, alive: async () => !dead, kill: () => {}, stop: async () => {} } as unknown as WhisperServer+ }+ const wanted: number[] = [], warns: string[] = []+ const info = vi.spyOn(console, 'info').mockImplementation(() => {}), warn = vi.spyOn(console, 'warn').mockImplementation(() => {}), err = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ disposers.push(hookTranscription({+ store, modelPath: () => '/m/ggml-base-q5_1.bin', send: () => {}, warn: (c) => warns.push(c), server: make, serverIdleMs: 60_000, holdMs: 0,+ parakeet: () => ({ model: '/m/ggml-parakeet.bin', lid: '/m/ggml-base-q5_1.bin' }), parakeetOff: () => null, spoken: () => 'en', wantWhisper: () => wanted.push(1),+ onStart: () => {}, onStop: () => {},+ }))+ const m = store.createMeeting({ title: 't', startedAt: 1, endedAt: 2, eventId: null, app: null, attendees: [], state: 'done' })+ expect(await transcribeRecorded(m.id, { them: track(4) })).toBe(true)+ // every chunk was read, by whisper, and nothing is left waiting or in error+ expect(store.segments(m.id).map((l) => l.text)).toEqual(Array(4).fill('Whisper read this'))+ expect(store.meeting(m.id)?.transcriptionPending).toBeFalsy()+ expect(warns).toEqual([])+ expect(warn.mock.calls.map((a) => a.join(' ')).join('\n')).toMatch(/ASR them: parakeet-server failed \(.*could not start.*\): whisper reads this chunk/)+ expect(wanted.length).toBeGreaterThan(0)+ // it never answered: the next meeting does not try it+ const before = made.filter((x) => x.model.includes('parakeet')).reduce((n, x) => n + x.urls, 0)+ const next = store.createMeeting({ title: 'n', startedAt: 3, endedAt: 4, eventId: null, app: null, attendees: [], state: 'done' })+ expect(await transcribeRecorded(next.id, { them: track(2) })).toBe(true)+ expect(made.filter((x) => x.model.includes('parakeet')).reduce((n, x) => n + x.urls, 0)).toBe(before)+ expect(info.mock.calls.filter((a) => a[0] === 'ASR').map((a) => String(a[1])).at(-1)).toMatch(/whisper \(ggml-base-q5_1\.bin\) reads every language: parakeet-server failed earlier/)+ } finally { info.mockRestore(); warn.mockRestore(); err.mockRestore() }+ })+})diff --git a/catalog/catalog.json b/catalog/catalog.jsonindex 2aa133f1..44d2fe8a 100644--- a/catalog/catalog.json+++ b/catalog/catalog.json@@ -231,12 +231,30 @@"minMemGB": 0}],+ "parakeet": {+ "id": "parakeet-tdt-0.6b-v3-q8_0",+ "name": "Parakeet TDT 0.6B v3",+ "license": "CC-BY-4.0",+ "attribution": "Parakeet TDT 0.6B v3 by NVIDIA (https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3), licensed under CC BY 4.0. Yogurt downloads converted weights: the GGML q8_0 file from ggml-org/parakeet-GGUF, converted from NVIDIA's original and quantized to 8 bits.",+ "url": "https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q8_0.bin",+ "sha256": "4d64e9e96c2792186d072fde0034df0ad670cf680a2f53069052ead827fd600e",+ "sizeGB": 0.67,+ "bytes": 668757119,+ "minMemGB": 0,+ "languageId": "whisper-base-q5_1"+ },"whisperServer": {"id": "whisper-server","tag": "v1.9.5","bundled": true,"note": "Built by app/scripts/native.sh from whisper.cpp at the commit under whisperCpp and shipped inside the app, so setup downloads nothing for it"},+ "parakeetServer": {+ "id": "parakeet-server",+ "tag": "v1.9.5",+ "bundled": true,+ "note": "Built by app/scripts/native.sh and whisper-build.mjs from app/native/parakeet-server inside whisper.cpp at the commit under whisperCpp (its own parakeet.h), and shipped inside the app"+ },"embedding": {"id": "embeddinggemma-300m-q8_0","name": "EmbeddingGemma 300M",diff --git a/packages/picker/src/asr.ts b/packages/picker/src/asr.tsindex a0d6451f..ee48250a 100644--- a/packages/picker/src/asr.ts+++ b/packages/picker/src/asr.ts@@ -28,6 +28,13 @@ export const KEEPS_UP_RTF = 0.5* transcript ends at most about a quarter of its length after the meeting does.*/export const LAGS_A_LITTLE_RTF = 1.25+/**+ * Parakeet is timed like the whisper models (the same clip, threads and warm-up, a careful reading, on the processor)+ * and judged by the same rule: it reads live only where it keeps up with two voices. Slower than that, or out of time+ * (null), and whisper is picked as before.+ */+export const parakeetKeepsUp = (rtf: number | null | undefined): boolean => typeof rtf === 'number' && rtf <= KEEPS_UP_RTF+/** part of the speed check's key: a change to how it picks measures every computer again, once */export const SPEED_CHECK_VERSION = 'v3'/**diff --git a/packages/picker/src/catalog-schema.ts b/packages/picker/src/catalog-schema.tsindex a3f9d3e1..02a49230 100644--- a/packages/picker/src/catalog-schema.ts+++ b/packages/picker/src/catalog-schema.ts@@ -38,6 +38,9 @@ const Asr = z.object({gpuOnly: z.boolean().optional(), lastResort: z.boolean().optional(),})+/** Parakeet for the languages it covers; languageId is the whisper in `asr` that hears which language a track is in */+const Parakeet = Asr.extend({ languageId: Id, attribution: z.string().min(1) })+/** the model that turns text into vectors for meaning search across meetings (EmbeddingGemma); dims: the length Yogurt keeps */const Embedding = z.object({id: Id, name: z.string().min(1), license: z.string().min(1),@@ -56,7 +59,9 @@ export const CatalogSchema = z.object({models: z.array(Model).min(1),whisperCpp: z.object({ tag: z.string().min(1), commit: z.string().regex(/^[a-f0-9]{40}$/) }),asr: z.array(Asr).min(1),+ parakeet: Parakeet.optional(),whisperServer: Binary,+ parakeetServer: Binary.optional(),embedding: Embedding,})@@ -71,6 +76,9 @@ export function validateCatalog(raw: unknown, allowedLicenses: string[]): { ok:if (!allowedLicenses.includes(m.license)) errors.push(`${m.id}: license ${m.license} not allowed`)}for (const a of parsed.data.asr) if (!allowedLicenses.includes(a.license)) errors.push(`${a.id}: license ${a.license} not allowed`)+ const pk = parsed.data.parakeet+ if (pk && !allowedLicenses.includes(pk.license)) errors.push(`${pk.id}: license ${pk.license} not allowed`)+ if (pk && !parsed.data.asr.some((a) => a.id === pk.languageId)) errors.push(`${pk.id}: languageId ${pk.languageId} is not a speech model in the catalog`)if (!allowedLicenses.includes(parsed.data.embedding.license)) errors.push(`${parsed.data.embedding.id}: license ${parsed.data.embedding.license} not allowed`)if (!parsed.data.models.some((m) => m.starter)) errors.push('catalog needs at least one starter model')return errors.length ? { ok: false, errors } : { ok: true, catalog: parsed.data as Catalog }diff --git a/packages/picker/src/index.ts b/packages/picker/src/index.tsindex acccf164..1165b99d 100644--- a/packages/picker/src/index.ts+++ b/packages/picker/src/index.ts@@ -2,4 +2,4 @@ export * from './types'export { bandwidthGBs } from './bandwidth'export { pick, MIN_TOK_PER_SEC, LITE_AGENT_SCORE } from './pick'export { CatalogSchema, validateCatalog } from './catalog-schema'-export { AFTER_MEETING_RTF, asrCandidates, KEEPS_UP_RTF, LAGS_A_LITTLE_RTF, pickAsr, pickBySpeed, SPEED_CHECK_VERSION, speedKey } from './asr'+export { AFTER_MEETING_RTF, asrCandidates, KEEPS_UP_RTF, LAGS_A_LITTLE_RTF, parakeetKeepsUp, pickAsr, pickBySpeed, SPEED_CHECK_VERSION, speedKey } from './asr'diff --git a/packages/picker/src/types.ts b/packages/picker/src/types.tsindex e0243b22..c03fc880 100644--- a/packages/picker/src/types.ts+++ b/packages/picker/src/types.ts@@ -59,6 +59,16 @@ export interface CatalogAsr {lastResort?: boolean}+/**+ * Parakeet TDT (a ggml file run by parakeet-server): the speech model for the languages it covers. languageId names the+ * small whisper in `asr` that hears which language a track is in, so Parakeet only gets the ones it knows.+ */+export interface CatalogParakeet extends CatalogAsr {+ languageId: string+ /** the credit its licence asks for (CC-BY-4.0), with the note that the weights are converted */+ attribution: string+}+/** The embedding model for meaning search across meetings: one GGUF file, run by the notes model's worker */export interface CatalogEmbedding {id: string@@ -98,7 +108,10 @@ export interface Catalog {models: CatalogModel[]whisperCpp: { tag: string; commit: string }asr: CatalogAsr[]+ /** left out: whisper reads every language */+ parakeet?: CatalogParakeetwhisperServer: CatalogBinary+ parakeetServer?: CatalogBinaryembedding: CatalogEmbedding}diff --git a/packages/picker/test/asr.test.ts b/packages/picker/test/asr.test.tsindex a9a641d3..c56a6673 100644--- a/packages/picker/test/asr.test.ts+++ b/packages/picker/test/asr.test.ts@@ -166,3 +166,19 @@ describe('speedKey: the speed check runs again only when the computer changes',expect(speedKey({ ...machines.linux3060, cores: 6 })).not.toBe(speedKey({ ...machines.linux3060, cores: 12 }))})})++describe('Parakeet in the speed check', () => {+ it('is judged by the rule the whisper models are: it reads live only where it keeps up with two voices', async () => {+ const { parakeetKeepsUp } = await import('../src/asr')+ expect(parakeetKeepsUp(0.21)).toBe(true)+ expect(parakeetKeepsUp(KEEPS_UP_RTF)).toBe(true)+ expect(parakeetKeepsUp(0.51)).toBe(false)+ // out of time, or not timed yet+ expect(parakeetKeepsUp(null)).toBe(false)+ expect(parakeetKeepsUp(undefined)).toBe(false)+ })+ it('is no whisper candidate: the whisper models are picked from the same list as before', () => {+ expect(catalog.asr.map((a) => a.id)).not.toContain(catalog.parakeet!.id)+ expect(asrCandidates(machines.m1max32, catalog)).toEqual([])+ })+})diff --git a/packages/picker/test/catalog.test.ts b/packages/picker/test/catalog.test.tsindex a589d207..60dae964 100644--- a/packages/picker/test/catalog.test.ts+++ b/packages/picker/test/catalog.test.ts@@ -17,6 +17,22 @@ describe('validateCatalog', () => {if (!r.ok) throw new Error(r.errors.join('; '))expect(r.catalog.models.find((m) => m.id === 'gemma-4-26b-a4b')?.gpuOnly).toBe(true)})+ it('pins Parakeet like the other speech models: a URL at a fixed revision, a sha256, its size, an allowed licence with its credit', () => {+ const r = validateCatalog(real, licenses)+ if (!r.ok) throw new Error(r.errors.join('; '))+ const p = r.catalog.parakeet!+ expect(p.url).toMatch(/^https:\/\/huggingface\.co\/ggml-org\/parakeet-GGUF\/resolve\/[a-f0-9]{40}\/ggml-parakeet-tdt-0\.6b-v3-q8_0\.bin$/)+ expect(p.sha256).toMatch(sha)+ expect(p.bytes / 1e9).toBeCloseTo(p.sizeGB, 1)+ expect(p.license).toBe('CC-BY-4.0')+ expect(p.attribution).toMatch(/NVIDIA/)+ expect(r.catalog.asr.some((a) => a.id === p.languageId)).toBe(true)+ expect(r.catalog.parakeetServer).toMatchObject({ bundled: true })+ })+ it('a catalog without Parakeet is still a catalog (whisper reads everything)', () => {+ const { parakeet: _p, parakeetServer: _s, ...rest } = shipped+ expect(validateCatalog(rest, licenses).ok).toBe(true)+ })it('pins every ASR model with a sha256', () => {const r = validateCatalog(real, licenses)if (!r.ok) throw new Error(r.errors.join('; '))