Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(dictation): use the newer Windows speech when the desktop recognizer lacks the language

AdityaUmaledfbf80de8272
diff --git a/electron/resources/speech-helper-windows-onecore.ps1 b/electron/resources/speech-helper-windows-onecore.ps1
new file mode 100644
index 0000000000..f13a4d4739
--- /dev/null
+++ b/electron/resources/speech-helper-windows-onecore.ps1
@@ -0,0 +1,140 @@
+# Windows dictation through the newer Windows speech (Windows.Media.SpeechRecognition), for display languages the
+# desktop recognizer has no recognizer for (Portuguese (Brazil) and others Windows covers only with its newer speech
+# packs). speech-helper-windows.ps1 runs this script in its own session, so Send-Line and Join-Text are its functions,
+# and the output lines and stdin commands are the same.
+# Exit code 3, with nothing written, means this script cannot listen here (no newer speech, the language is not
+# installed, or Windows' online speech recognition setting is off): the caller goes on without it.
+param([int]$EndpointMs = 0)
+
+$ErrorActionPreference = 'Stop'
+$cannotListen = 3
+
+# The display language first, then the same language in another region; $null when Windows has neither.
+function Select-SpeechLanguage($tags, [string]$name) {
+ $exact = @($tags | Where-Object { $_ -eq $name })
+ if ($exact.Count) { return $exact[0] }
+ $base = ($name -split '-')[0]
+ $same = @($tags | Where-Object { ($_ -split '-')[0] -eq $base })
+ if ($same.Count) { return $same[0] }
+ return $null
+}
+
+try {
+ Add-Type -AssemblyName System.Runtime.WindowsRuntime
+ $null = [Windows.Media.SpeechRecognition.SpeechRecognizer, Windows.Media.SpeechRecognition, ContentType = WindowsRuntime]
+ $null = [Windows.Globalization.Language, Windows.Globalization, ContentType = WindowsRuntime]
+} catch {
+ exit $cannotListen
+}
+
+$asTask = @([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 })
+$asTaskAction = $asTask | Where-Object { $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncAction' } | Select-Object -First 1
+$asTaskOperation = $asTask | Where-Object { $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' } | Select-Object -First 1
+function Wait-Action($action) {
+ $asTaskAction.Invoke($null, @($action)).Wait() | Out-Null
+}
+function Wait-Operation($operation, [Type]$type) {
+ $task = $asTaskOperation.MakeGenericMethod($type).Invoke($null, @($operation))
+ $task.Wait() | Out-Null
+ return $task.Result
+}
+
+$sources = 'omb-onecore-heard', 'omb-onecore-recognized', 'omb-onecore-completed'
+$recognizer = $null
+function Exit-CannotListen {
+ foreach ($source in $sources) { Unregister-Event -SourceIdentifier $source -ErrorAction SilentlyContinue }
+ if ($recognizer) { $recognizer.Dispose() }
+ exit $cannotListen
+}
+try {
+ $tags = @([Windows.Media.SpeechRecognition.SpeechRecognizer]::SupportedTopicLanguages | ForEach-Object { $_.LanguageTag })
+ $tag = Select-SpeechLanguage $tags ([System.Globalization.CultureInfo]::CurrentUICulture.Name)
+ if (-not $tag) { Exit-CannotListen }
+ $recognizer = [Windows.Media.SpeechRecognition.SpeechRecognizer]::new([Windows.Globalization.Language]::new($tag))
+ # No constraint added: the recognizer compiles its own dictation grammar.
+ $compiled = Wait-Operation ($recognizer.CompileConstraintsAsync()) ([Windows.Media.SpeechRecognition.SpeechRecognitionCompilationResult])
+ if ($compiled.Status -ne [Windows.Media.SpeechRecognition.SpeechRecognitionResultStatus]::Success) { Exit-CannotListen }
+ $session = $recognizer.ContinuousRecognitionSession
+ # Its default ends a dictation after a few seconds of quiet; the app ends it with "finish" or -EndpointMs instead.
+ $session.AutoStopSilenceTimeout = [TimeSpan]::FromMinutes(10)
+ Register-ObjectEvent -InputObject $recognizer -EventName HypothesisGenerated -SourceIdentifier $sources[0] | Out-Null
+ Register-ObjectEvent -InputObject $session -EventName ResultGenerated -SourceIdentifier $sources[1] | Out-Null
+ Register-ObjectEvent -InputObject $session -EventName Completed -SourceIdentifier $sources[2] | Out-Null
+ Wait-Action ($session.StartAsync())
+} catch {
+ # Windows refuses to start when its online speech recognition setting is off.
+ Exit-CannotListen
+}
+
+$commands = New-Object System.IO.StreamReader([Console]::OpenStandardInput())
+$command = $commands.ReadLineAsync()
+$committed = ''
+$shown = ''
+$changedAt = [DateTime]::UtcNow
+$finishedAt = $null
+$success = [Windows.Media.SpeechRecognition.SpeechRecognitionResultStatus]::Success
+
+# A failure while listening ends the dictation with an error, never by trying the desktop recognizer.
+try {
+ while ($true) {
+ foreach ($received in @(Get-Event)) {
+ Remove-Event -EventIdentifier $received.EventIdentifier
+ switch ($received.SourceIdentifier) {
+ 'omb-onecore-heard' {
+ $text = Join-Text $committed $received.SourceEventArgs.Hypothesis.Text
+ if ($text -ne $shown) {
+ $shown = $text
+ $changedAt = [DateTime]::UtcNow
+ Send-Line @{ partial = $true; text = $text }
+ }
+ }
+ 'omb-onecore-recognized' {
+ $result = $received.SourceEventArgs.Result
+ if ($result.Status -eq $success -and $result.Text) {
+ $committed = Join-Text $committed $result.Text
+ }
+ $shown = $committed
+ $changedAt = [DateTime]::UtcNow
+ Send-Line @{ partial = $true; text = $committed }
+ }
+ 'omb-onecore-completed' {
+ # Success after "finish", TimeoutExceeded after the long quiet above: both end with what was heard.
+ $status = $received.SourceEventArgs.Status
+ if ($status -ne $success -and $status -ne [Windows.Media.SpeechRecognition.SpeechRecognitionResultStatus]::TimeoutExceeded) {
+ Send-Line @{ error = 'helper-exited' }
+ exit 1
+ }
+ Send-Line @{ partial = $false; text = $committed }
+ exit 0
+ }
+ }
+ }
+ if (-not $finishedAt -and $command.IsCompleted) {
+ $line = $null
+ if (-not $command.IsFaulted) { $line = $command.Result }
+ if ($null -eq $line) {
+ $session.CancelAsync() | Out-Null
+ exit 0
+ }
+ if ($line.Trim() -eq 'finish') {
+ $finishedAt = [DateTime]::UtcNow
+ $session.StopAsync() | Out-Null
+ } else {
+ $command = $commands.ReadLineAsync()
+ }
+ }
+ if (-not $finishedAt -and $EndpointMs -gt 0 -and $shown -and ([DateTime]::UtcNow - $changedAt).TotalMilliseconds -ge $EndpointMs) {
+ $finishedAt = [DateTime]::UtcNow
+ $session.StopAsync() | Out-Null
+ }
+ # Windows normally reports Completed soon after the stop; if it never does, end with what was heard.
+ if ($finishedAt -and ([DateTime]::UtcNow - $finishedAt).TotalSeconds -ge 5) {
+ Send-Line @{ partial = $false; text = $committed }
+ exit 0
+ }
+ Start-Sleep -Milliseconds 50
+ }
+} catch {
+ Send-Line @{ error = 'helper-exited' }
+ exit 1
+}
diff --git a/electron/resources/speech-helper-windows.ps1 b/electron/resources/speech-helper-windows.ps1
index 92c8203956..f2efb4a6c9 100644
--- a/electron/resources/speech-helper-windows.ps1
+++ b/electron/resources/speech-helper-windows.ps1
@@ -1,4 +1,6 @@
# Windows dictation through the speech recognizer built into Windows (System.Speech): on this computer, offline, no key.
+# A display language with no desktop recognizer tries speech-helper-windows-onecore.ps1 first: the newer Windows speech,
+# which works only when Windows' online speech recognition setting is on (Windows then sends the audio to Microsoft).
# Same output as speech-helper.swift, one JSON object per line on stdout:
# {"partial":true,"text":"..."} while recognizing
# {"partial":false,"text":"..."} final result, then exit 0
@@ -33,20 +35,33 @@ try {
try {
$installed = @([System.Speech.Recognition.SpeechRecognitionEngine]::InstalledRecognizers())
} catch {
- Send-Line @{ error = 'speech-language-missing' }
- exit 1
-}
-if ($installed.Count -eq 0) {
- Send-Line @{ error = 'speech-language-missing' }
- exit 1
+ $installed = @()
}
-# The person's display language first, then the same language in another region, then any installed recognizer.
+# The person's display language first, then the same language in another region, then the newer Windows speech,
+# then any installed recognizer.
$culture = [System.Globalization.CultureInfo]::CurrentUICulture
$recognizer = $installed | Where-Object { $_.Culture.Name -eq $culture.Name } | Select-Object -First 1
if (-not $recognizer) {
$recognizer = $installed | Where-Object { $_.Culture.TwoLetterISOLanguageName -eq $culture.TwoLetterISOLanguageName } | Select-Object -First 1
}
-if (-not $recognizer) { $recognizer = $installed[0] }
+if (-not $recognizer) {
+ # Exit code 3: the newer speech cannot listen either and wrote nothing.
+ $onecore = Join-Path $PSScriptRoot 'speech-helper-onecore.ps1'
+ if (Test-Path -LiteralPath $onecore) {
+ try {
+ & $onecore -EndpointMs $EndpointMs
+ } catch {
+ Send-Line @{ error = 'helper-exited' }
+ exit 1
+ }
+ if ($LASTEXITCODE -ne 3) { exit $LASTEXITCODE }
+ }
+ if ($installed.Count -eq 0) {
+ Send-Line @{ error = 'speech-language-missing' }
+ exit 1
+ }
+ $recognizer = $installed[0]
+}
try {
$engine = New-Object System.Speech.Recognition.SpeechRecognitionEngine($recognizer)
diff --git a/electron/speech-helper-windows.test.mjs b/electron/speech-helper-windows.test.mjs
new file mode 100644
index 0000000000..bddb669030
--- /dev/null
+++ b/electron/speech-helper-windows.test.mjs
@@ -0,0 +1,45 @@
+// The Windows speech helpers run in Windows PowerShell 5.1 (powershell.exe): on Windows these tests use it, elsewhere
+// PowerShell 7 (pwsh) when it is installed.
+import { execFileSync, spawnSync } from "node:child_process";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const resources = path.join(path.dirname(fileURLToPath(import.meta.url)), "resources");
+const CLASSIC = path.join(resources, "speech-helper-windows.ps1");
+const ONECORE = path.join(resources, "speech-helper-windows-onecore.ps1");
+const shell = process.platform === "win32" ? "powershell.exe" : "pwsh";
+const ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive"];
+const found = spawnSync(shell, [...ARGS, "-Command", "exit 0"], { stdio: "ignore" }).status === 0;
+
+const quoted = (text) => `'${text.replaceAll("'", "''")}'`;
+const run = (command) => execFileSync(shell, [...ARGS, "-Command", command], { encoding: "utf8" }).trim();
+const parse = (file) => `[System.Management.Automation.Language.Parser]::ParseFile(${quoted(file)}, [ref]$null, [ref]$errors)`;
+
+describe.skipIf(!found)("Windows speech helper scripts", () => {
+ it("parse without errors", () => {
+ for (const file of [CLASSIC, ONECORE]) {
+ expect(run(`$errors = $null; $null = ${parse(file)}; $errors.Count`)).toBe("0");
+ }
+ }, 30_000);
+
+ it("the newer speech picks the display language, then the same language in another region, else none", () => {
+ const pick = (tags, name) => run([
+ `$errors = $null; $ast = ${parse(ONECORE)}`,
+ "$fn = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Select-SpeechLanguage' }, $true)",
+ ". ([ScriptBlock]::Create($fn.Extent.Text))",
+ `$picked = Select-SpeechLanguage @(${tags.map(quoted).join(", ")}) ${quoted(name)}`,
+ "if ($null -eq $picked) { '<none>' } else { $picked }",
+ ].join("; "));
+ expect(pick(["en-US", "pt-PT", "pt-BR"], "pt-BR")).toBe("pt-BR");
+ expect(pick(["en-US", "pt-BR"], "pt-PT")).toBe("pt-BR");
+ expect(pick(["en-US", "de-DE"], "pt-BR")).toBe("<none>");
+ expect(pick([], "pt-BR")).toBe("<none>");
+ }, 30_000);
+
+ it.skipIf(process.platform === "win32")("the newer speech exits 3 and writes nothing where Windows speech is missing", () => {
+ const result = spawnSync(shell, [...ARGS, "-File", ONECORE], { encoding: "utf8", input: "" });
+ expect(result.status).toBe(3);
+ expect(result.stdout).toBe("");
+ }, 30_000);
+});
diff --git a/electron/speech.mjs b/electron/speech.mjs
index 266e063da1..1850fe0812 100644
--- a/electron/speech.mjs
+++ b/electron/speech.mjs
@@ -29,6 +29,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(__dirname, "resources", "speech-helper.swift");
const INFO = path.join(__dirname, "resources", "speech-helper-Info.plist");
const WINDOWS_HELPER = path.join(__dirname, "resources", "speech-helper-windows.ps1");
+// Run by WINDOWS_HELPER from the same session folder when the desktop recognizer lacks the display language.
+const WINDOWS_ONECORE_HELPER = path.join(__dirname, "resources", "speech-helper-windows-onecore.ps1");
// A signed app bundle must never be rewritten: lazy compilation would break its seal.
const BUNDLE = app.isPackaged
? path.join(process.resourcesPath, "OpenMausBot Speech.app")
@@ -120,6 +122,7 @@ function startWindowsSpeech(sink, endpointMs) {
sessionDir = mkdtempSync(path.join(app.getPath("temp"), "openmausbot-speech-"));
script = path.join(sessionDir, "speech-helper.ps1");
writeFileSync(script, readFileSync(WINDOWS_HELPER));
+ writeFileSync(path.join(sessionDir, "speech-helper-onecore.ps1"), readFileSync(WINDOWS_ONECORE_HELPER));
} catch {
if (sessionDir) rmSync(sessionDir, { recursive: true, force: true });
sink.end({ code: 1, reason: "helper-start-failed" });
diff --git a/electron/speech.test.mjs b/electron/speech.test.mjs
index 9e39e3a97d..26ed3242e0 100644
--- a/electron/speech.test.mjs
+++ b/electron/speech.test.mjs
@@ -232,6 +232,9 @@ describe("Windows speech helper", () => {
expect(session.args.slice(-2)).toEqual(["-EndpointMs", "0"]);
expect(session.options).toMatchObject({ windowsHide: true, stdio: ["pipe", "pipe", "ignore"] });
expect(session.scriptText).toContain("System.Speech.Recognition.SpeechRecognitionEngine");
+ const onecore = path.join(path.dirname(session.script), "speech-helper-onecore.ps1");
+ expect(session.scriptText).toContain("'speech-helper-onecore.ps1'");
+ expect(readFileSync(onecore, "utf8")).toContain("Windows.Media.SpeechRecognition.SpeechRecognizer");
expect(speechBusy()).toBe(true);
say(session, { partial: true, text: "hello" });
session.proc.stdout.emit("data", `${JSON.stringify({ partial: true, text: "hello there" }).slice(0, 9)}`);
@@ -245,6 +248,7 @@ describe("Windows speech helper", () => {
{ channel: "speech:end", body: { code: 0, reason: "completed" } },
]);
expect(existsSync(session.script)).toBe(false);
+ expect(existsSync(onecore)).toBe(false);
expect(speechBusy()).toBe(false);
});