mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
feat(speech): run GGUF models on transcribe-cpp, falling back to the CPU
The speech host child can now load a second engine. A model whose files are GGUF runs on transcribe-cpp (Metal on Apple silicon, Vulkan on Windows and Linux, CPU otherwise); everything else stays on sherpa-onnx, which remains the only engine on Intel Macs. A GPU that fails to load, errors, stalls for 25 s or crashes the process moves the dictation to a CPU-only process (TRANSCRIBE_BACKENDS=cpu) that replays the audio the GPU had not decoded yet, so no words are lost or repeated. A GPU that crashed or would not load is remembered per transcribe-cpp version and OS release, and voice.speechGpu = 'off' keeps it on the CPU. Packaging copies transcribe-cpp, koffi and the target's native package into resources/node_modules outside asar, fails when a target's package is missing, and ships the MSVC runtime beside transcribe.dll on Windows. No catalog model is GGUF yet, so nothing runs on transcribe-cpp until the catalog change that follows.
This commit is contained in:
@@ -20,9 +20,12 @@ const {
|
||||
assertPackagedNativeVariantsInstalled,
|
||||
assertProcessHostOutputBuilt,
|
||||
createPackagedRuntimeNodeModuleResources,
|
||||
normalizeElectronArchitecture,
|
||||
prunePackagedRuntimeNodeModules,
|
||||
readPackage,
|
||||
verifyPackagedMainRuntimeDeps
|
||||
} = require('./packaged-runtime-node-modules.cjs')
|
||||
const { copyPackagedTranscribeCpp } = require('./packaged-transcribe-cpp.cjs')
|
||||
const {
|
||||
assertNoWindowsExecutablesInRuntimeNodeModules
|
||||
} = require('./packaged-windows-only-runtime-files.cjs')
|
||||
@@ -330,7 +333,7 @@ module.exports = {
|
||||
// extraResources already ships plugin bytes; exclude source duplicates.
|
||||
'!resources/plugins/launch/**',
|
||||
// Platform extraResources selects speech natives; asar would duplicate it and ship other variants.
|
||||
'!node_modules/sherpa-onnx*{,/**/*}',
|
||||
'!node_modules/{sherpa-onnx*,transcribe-cpp,@transcribe-cpp,koffi,@koromix}{,/**/*}',
|
||||
// CLI shim belongs beside resources/bin/orca.exe; unpacking source creates a second .cmd without its executable (#7351).
|
||||
'!resources/win32{,/**/*}'
|
||||
],
|
||||
@@ -448,6 +451,13 @@ module.exports = {
|
||||
writeMacBuildCompatibility(resourcesDir, { version, commit, architecture })
|
||||
}
|
||||
stampPackagedCliVersion(resourcesDir, context.packager.appInfo.version)
|
||||
// Before the prune, which drops the copied packages' type declarations too.
|
||||
copyPackagedTranscribeCpp(
|
||||
readPackage,
|
||||
resourcesDir,
|
||||
context.electronPlatformName,
|
||||
normalizeElectronArchitecture(context.arch)
|
||||
)
|
||||
prunePackagedRuntimeNodeModules(resourcesDir, context.electronPlatformName, context.arch)
|
||||
assertNoWindowsExecutablesInRuntimeNodeModules(resourcesDir, context.electronPlatformName)
|
||||
// Gate native glibc floor after pruning foreign CPU variants; GLIBC_2.34 once broke Ubuntu 20.04 startup (#9902).
|
||||
|
||||
@@ -15,6 +15,7 @@ const {
|
||||
} = require('./scripts/native-build/windows/windows-pe-machine.cjs')
|
||||
const { adoptPackagedNativeBuildEntries } = require('./packaged-native-build-entries.cjs')
|
||||
const { runtimePackageExcludeFilter } = require('./packaged-windows-only-runtime-files.cjs')
|
||||
const { missingTranscribeCppPackages } = require('./packaged-transcribe-cpp.cjs')
|
||||
const {
|
||||
NATIVE_BUILD_PACKAGES,
|
||||
TRANSIENT_NATIVE_BUILD_ENTRY_FILTER
|
||||
@@ -567,6 +568,7 @@ function assertPackagedNativeVariantsInstalled(electronPlatformName, electronArc
|
||||
if (sherpaName in rootOptionalDependencies && !isInstalled(sherpaName)) {
|
||||
missing.push(sherpaName)
|
||||
}
|
||||
missing.push(...missingTranscribeCppPackages(readPackage, electronPlatformName, architecture))
|
||||
|
||||
// Why prefix, not equality: linux variants carry a libc suffix (watcher-linux-x64-glibc),
|
||||
// mirroring what prunePackagedParcelWatcher keeps.
|
||||
@@ -656,6 +658,7 @@ module.exports = {
|
||||
createPackagedRuntimeNodeModuleResources,
|
||||
findAsarEntry,
|
||||
isPackagedExternalSpecifier,
|
||||
normalizeElectronArchitecture,
|
||||
normalizeNodePtyWindowsArch,
|
||||
packageNameFromSpecifier,
|
||||
prunePackagedNodePty,
|
||||
@@ -664,5 +667,6 @@ module.exports = {
|
||||
prunePackagedRuntimeTypeAndSourceMapArtifacts,
|
||||
prunePackagedSherpaOnnx,
|
||||
prunePackagedZodSources,
|
||||
readPackage,
|
||||
verifyPackagedMainRuntimeDeps
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
const { cpSync, existsSync } = require('node:fs')
|
||||
const { execFileSync } = require('node:child_process')
|
||||
const { join } = require('node:path')
|
||||
|
||||
const TRANSCRIBE_CPP_PACKAGES = require('../src/shared/transcribe-cpp-packages.json')
|
||||
// transcribe.dll needs MSVC runtime >= 14.40 (older ones crash in std::mutex); the system copy may be older.
|
||||
const WINDOWS_CRT_DLLS = ['msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll']
|
||||
const MIN_WINDOWS_CRT_VERSION = [14, 40]
|
||||
|
||||
/**
|
||||
* The packages the speech host loads transcribe-cpp from, in load order: the ESM binding, koffi
|
||||
* (its FFI), koffi's prebuilt addon, and the target's native libraries. Each resolves from the
|
||||
* previous one's directory, as Node does at runtime. Null where the target ships no transcribe-cpp.
|
||||
*/
|
||||
function transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture) {
|
||||
const native = TRANSCRIBE_CPP_PACKAGES[`${electronPlatformName}-${architecture}`]
|
||||
if (!native) {
|
||||
return null
|
||||
}
|
||||
const binding = readPackage('transcribe-cpp')
|
||||
const koffi = readPackage('koffi', binding.packageDir)
|
||||
const koffiAddon = readPackage(
|
||||
`@koromix/koffi-${electronPlatformName}-${architecture}`,
|
||||
koffi.packageDir
|
||||
)
|
||||
const nativeLibraries = readPackage(native, binding.packageDir)
|
||||
return [binding, koffi, koffiAddon, nativeLibraries]
|
||||
}
|
||||
|
||||
function readFileVersion(dll) {
|
||||
const version = execFileSync(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-Command', `(Get-Item -LiteralPath '${dll}').VersionInfo.FileVersion`],
|
||||
{ encoding: 'utf8' }
|
||||
).trim()
|
||||
return version.split(/[.,\s]+/).map((part) => Number.parseInt(part, 10))
|
||||
}
|
||||
|
||||
function copyWindowsCrt(nativeDir) {
|
||||
const systemDir = join(process.env.SystemRoot || 'C:\\Windows', 'System32')
|
||||
for (const name of WINDOWS_CRT_DLLS) {
|
||||
const source = join(systemDir, name)
|
||||
if (!existsSync(source)) {
|
||||
throw new Error(
|
||||
`Packaging transcribe-cpp needs ${source} (Visual C++ 2015-2022 x64 runtime).`
|
||||
)
|
||||
}
|
||||
const [major, minor] = readFileVersion(source)
|
||||
const [minMajor, minMinor] = MIN_WINDOWS_CRT_VERSION
|
||||
if (major < minMajor || (major === minMajor && minor < minMinor)) {
|
||||
throw new Error(
|
||||
`${source} is ${major}.${minor}; transcribe-cpp needs ${MIN_WINDOWS_CRT_VERSION.join('.')}+. ` +
|
||||
'Install the latest Visual C++ 2015-2022 x64 redistributable on the build host.'
|
||||
)
|
||||
}
|
||||
// App-local beside transcribe.dll, which loads its dependencies from its own directory.
|
||||
cpSync(source, join(nativeDir, name))
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy transcribe-cpp into the slice's resources/node_modules, outside asar where koffi can dlopen it. */
|
||||
function copyPackagedTranscribeCpp(readPackage, resourcesDir, electronPlatformName, architecture) {
|
||||
// beforePack's assertPackagedNativeVariantsInstalled already failed any real build missing these;
|
||||
// only an afterPack driven without it (packaging tests) gets here without them.
|
||||
if (missingTranscribeCppPackages(readPackage, electronPlatformName, architecture).length > 0) {
|
||||
return
|
||||
}
|
||||
const packages = transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture)
|
||||
if (!packages) {
|
||||
return
|
||||
}
|
||||
for (const { name, packageDir } of packages) {
|
||||
const target = join(resourcesDir, 'node_modules', ...name.split('/'))
|
||||
cpSync(packageDir, target, { recursive: true, dereference: true })
|
||||
}
|
||||
if (electronPlatformName === 'win32') {
|
||||
copyWindowsCrt(join(resourcesDir, 'node_modules', ...packages[3].name.split('/')))
|
||||
}
|
||||
}
|
||||
|
||||
/** The transcribe-cpp packages a target needs that this install lacks (install:release adds other CPUs). */
|
||||
function missingTranscribeCppPackages(readPackage, electronPlatformName, architecture) {
|
||||
try {
|
||||
transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture)
|
||||
return []
|
||||
} catch (error) {
|
||||
return [String(error.message ?? error)]
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
copyPackagedTranscribeCpp,
|
||||
missingTranscribeCppPackages
|
||||
}
|
||||
+6
-1
@@ -393,12 +393,17 @@
|
||||
"optionalDependencies": {
|
||||
"@orca/windows-registry": "workspace:*",
|
||||
"@orca/windows-security": "workspace:*",
|
||||
"@transcribe-cpp/darwin-arm64-metal": "0.4.1",
|
||||
"@transcribe-cpp/linux-arm64-cpu-vulkan": "0.4.1",
|
||||
"@transcribe-cpp/linux-x64-cpu-vulkan": "0.4.1",
|
||||
"@transcribe-cpp/win32-x64-cpu-vulkan": "0.4.1",
|
||||
"@vscode/windows-process-tree": "0.8.0",
|
||||
"sherpa-onnx-darwin-arm64": "1.12.37",
|
||||
"sherpa-onnx-darwin-x64": "1.12.37",
|
||||
"sherpa-onnx-linux-arm64": "1.12.37",
|
||||
"sherpa-onnx-linux-x64": "1.12.37",
|
||||
"sherpa-onnx-win-x64": "1.12.37"
|
||||
"sherpa-onnx-win-x64": "1.12.37",
|
||||
"transcribe-cpp": "0.4.1"
|
||||
},
|
||||
"lint-staged": {
|
||||
"{*.{ts,tsx,js,jsx,mjs,mts,cts},!(cloud)/**/*.{ts,tsx,js,jsx,mjs,mts,cts}}": [
|
||||
|
||||
Generated
+259
@@ -702,6 +702,18 @@ importers:
|
||||
'@orca/windows-security':
|
||||
specifier: workspace:*
|
||||
version: link:native/windows-security
|
||||
'@transcribe-cpp/darwin-arm64-metal':
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan':
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1
|
||||
'@transcribe-cpp/linux-x64-cpu-vulkan':
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1
|
||||
'@transcribe-cpp/win32-x64-cpu-vulkan':
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1
|
||||
'@vscode/windows-process-tree':
|
||||
specifier: 0.8.0
|
||||
version: 0.8.0(patch_hash=a09f2e8b2b4e73ef20c317af91f9e06c09abf62fa2c891d99b16f53047f596fd)
|
||||
@@ -720,6 +732,9 @@ importers:
|
||||
sherpa-onnx-win-x64:
|
||||
specifier: 1.12.37
|
||||
version: 1.12.37
|
||||
transcribe-cpp:
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1
|
||||
|
||||
native/windows-registry:
|
||||
dependencies:
|
||||
@@ -1475,6 +1490,106 @@ packages:
|
||||
'@keyv/serialize@1.1.1':
|
||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
||||
|
||||
'@koromix/koffi-android-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-wxsPuEMDrqOR5RUdABYFNDTabhh/xwDetCUDI+/CN93QF1T7Yeq218kvDWmYT/g1wV2kU1aYdRO4D7cH9PDskw==}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@koromix/koffi-android-x64@3.3.6':
|
||||
resolution: {integrity: sha512-fHZE6ejYLmAEe2eou2uoG61HUtolY45RhQEsTKAKNI5eKSW7Z2Jh8eP5EE+3CVQSbzbaMeHXRTcgEQGk5uEF5Q==}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@koromix/koffi-darwin-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-++V4qscXff/Ya5cE6vOPOomcxk3T5JQu81Uc0fvoso3VVELcoHt2/dz9E0FY0EPyQNIRcWOVg7CgvsPCKId9lg==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@koromix/koffi-darwin-x64@3.3.6':
|
||||
resolution: {integrity: sha512-eOyit0eyfkmdXCNlOkG8cNtpQUx+dikr1QsozJdwm7/zH1u7KP5dRtmsaGUMLSUY7cVYSRTUStkwHBrHjBtuzw==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@koromix/koffi-freebsd-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-7teGsq2BukkLZ60xxq4KyPxeJct51nV1G/MfNj8IoMTqlpd35w4aiIIoFWVwLL3j3DdT95Ye/FpVY4C7ZEuMHg==}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
|
||||
'@koromix/koffi-freebsd-ia32@3.3.6':
|
||||
resolution: {integrity: sha512-WA7qEAMxTWS2WSFDceETVJTFrZgRwNvfG+FJpCC2XkJXftHwOhv8/X6d5HUEXh361sd7HwCHoT1wypL0nvI7Mw==}
|
||||
cpu: [ia32]
|
||||
os: [freebsd]
|
||||
|
||||
'@koromix/koffi-freebsd-x64@3.3.6':
|
||||
resolution: {integrity: sha512-OQ/eBhGefbtxcPs5VDkK9mwxoIeSwrIriOT1/JHHA/tbNAXdC0GiAYsBw82T4L4r2u0TuJ0CbgN3HrulzdPPig==}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@koromix/koffi-linux-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-8LuJcdH74wTg7JcZjnRnb3z+qWPKcEDSv8HRPkWTVD56TFm0CXZXgl/WJ4maDbWem6ZoXxc87a8nQEA+wABzNA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-arm@3.3.6':
|
||||
resolution: {integrity: sha512-0uo15z9L7GsAEGvPCVKcXzCtRJCyghCYDrWO2L3vXk4G5lgk+OBvWS7RmlDZ99X/A0oDiL3vLCplGaBCEZZ8Eg==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-ia32@3.3.6':
|
||||
resolution: {integrity: sha512-aTOjTMdy2Q6JqNA9KkT2OaCs77d0TzEG5KipfinzDyiV9DkYyUCvFykIY5GDHCUKXyJi+xy1IfuUxeL64wzzBQ==}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-loong64@3.3.6':
|
||||
resolution: {integrity: sha512-m33Zjrhj2Atpkcr0We61V2Zjm8wFb79QOtaOfzttmNFQMtryYpWZ4CBxx4gLKvcrR7NcK3GV/D9Qi2M0ppWK7A==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-ppc64@3.3.6':
|
||||
resolution: {integrity: sha512-L1+1cjH5GtNtv7TYWy469jsDberOOwCfE96h0AWFKrVHycDn8hTKH5fEA/er42R04lZiNWbiC0+sMb50enYRGw==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-riscv64@3.3.6':
|
||||
resolution: {integrity: sha512-VnzoNRg3MfTdGXLDtUrBj4wJnZD3buX6LajGrvYm5Mf1U132bzQwxP1ryZhs8Q0Cl1pTsN2fIovjNwpwE7Hs3A==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-linux-x64@3.3.6':
|
||||
resolution: {integrity: sha512-RTRbVTZ1rf1GFowSsbuU2acYoRq66ZwJGh+rTgau1Cat3muv2884p0FRH6UKfwlgWkpjIHJ7N8N0liM7Oe2eAQ==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@koromix/koffi-openbsd-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-eXHyRZw/BACrBIuntkqlNTa8p8i9KobtREJjhxldsVoEPRQTREnhBq5IbqbvXesY89MwFGn4lHmzG1x5ueV63A==}
|
||||
cpu: [arm64]
|
||||
os: [openbsd]
|
||||
|
||||
'@koromix/koffi-openbsd-ia32@3.3.6':
|
||||
resolution: {integrity: sha512-xbJYOFY0IAIx3nyNdYad5g2f8cNAOY8OBcjPDYRlc7gkqQiPNER9ZA9g+M2LuVf48i65ZCn11XaWDSQymDJJBg==}
|
||||
cpu: [ia32]
|
||||
os: [openbsd]
|
||||
|
||||
'@koromix/koffi-openbsd-x64@3.3.6':
|
||||
resolution: {integrity: sha512-bNL4uIxUBhA93naaL3dWwXdLgQGAss6krDbwljO1uS3iJ+8K7KSo8EGbJfRYUf1L+ctaHTJuDwgZ1XTSEC9FQQ==}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
|
||||
'@koromix/koffi-win32-arm64@3.3.6':
|
||||
resolution: {integrity: sha512-WDVsrvWAaHbA7xiCMXX3PBmfDf4+VnfY67ryRAW86QNW8109W9WPS3YVGGD2YoPswDmSZsMBVzzZCEFUrLdJuA==}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@koromix/koffi-win32-ia32@3.3.6':
|
||||
resolution: {integrity: sha512-6hwsUGC7FCICiLdmEQwTK0+MOLmuraqWuVsUCBkdSCL6k62LQLScuTn2dzONFvN/H5EXq0zzX4ddgtq2abL/xQ==}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@koromix/koffi-win32-x64@3.3.6':
|
||||
resolution: {integrity: sha512-g9KC6VKQLe88Tjgeubk3yhu0CjtqSeRq4XjWFWxUq4rsP0/wfLUBoeISvG60HoPmhYQp+U7hVd8Ms+amOMHDvA==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@linear/sdk@97.0.0':
|
||||
resolution: {integrity: sha512-ntgZI06I37DTp/XULYTPbOg1t7vJRo72JRSkMjdgG+GbUEHdSkYsUjN0dR42go/2LvLRKWJD3jVehm0wE5haEg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -4056,6 +4171,33 @@ packages:
|
||||
'@tiptap/starter-kit@3.31.3':
|
||||
resolution: {integrity: sha512-WKof9RewdmGHvWJ1wn0/HVNG2mV+HOgVRyJkKekuM9fgr6BZAAH/xZsWE1eon+94JnQ+KtK2ThydXQM/qc6b2A==}
|
||||
|
||||
'@transcribe-cpp/darwin-arm64-metal@0.4.1':
|
||||
resolution: {integrity: sha512-Sg8obJiDeBxSWQvFcHxlVJoY5X+BzMFMNH+5LU5oVfj8iHJ0dj0uVlBUrNIN6D2xCBksoLVOEMCbasqUXv/DLw==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@transcribe-cpp/darwin-x64-cpu@0.4.1':
|
||||
resolution: {integrity: sha512-lRP/Mr8msBMUHXkLPtGZoVhNXgxdTV3tzEmpLki0VeBP3LraPC73m9PjfhzoYNEwXEnpqdLwNaTnuCHOwJRugw==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan@0.4.1':
|
||||
resolution: {integrity: sha512-b010Fhfnqe4jGJLMhvx6LucvysxK638qY2eww1oaaErzkAKutdN0uRx84vsfXVxVr3lKlzdL5vq6Zv/QfAArTA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@transcribe-cpp/linux-x64-cpu-vulkan@0.4.1':
|
||||
resolution: {integrity: sha512-AuiE8PSFbDndLJDpt8lilZIyg2syQSRBmZQWklx0rd9vF1M/Wfn4StKUXTGC4rouQOTJPy3ViioGLpyYr6unaw==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@transcribe-cpp/win32-x64-cpu-vulkan@0.4.1':
|
||||
resolution: {integrity: sha512-0W8yQ6SgmPKgVaLHVGkj5gr2uzMS9mAVHMCJKZCFdhvQxeQlUbrvN/8ooyYD7S5qmLsLNEHt0ecMMVgsoWUu9A==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tsrs/darwin-arm64@0.18.0-ts7.1.0-dev.20260929':
|
||||
resolution: {integrity: sha512-sAirMpaGA9uRQm2W+t4zC7PjnijNuFa4PCSIfLKKo0JyAUCRfnMeev0UGBQ9F3g+9Nz187tvikUs5Irh5+eajA==}
|
||||
engines: {node: '>=16.20.0'}
|
||||
@@ -6147,6 +6289,9 @@ packages:
|
||||
resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
koffi@3.3.6:
|
||||
resolution: {integrity: sha512-pPqCZg8o4laLvzxySGEju/T1Fd+eCJTVnJmcH6h1u98HFRoBQ9EokNuBSj3NxIQdzkEPRxPnHKjhBVkLeB+X0g==}
|
||||
|
||||
layout-base@1.0.2:
|
||||
resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==}
|
||||
|
||||
@@ -7806,6 +7951,10 @@ packages:
|
||||
resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==}
|
||||
engines: {node: '>=16'}
|
||||
|
||||
transcribe-cpp@0.4.1:
|
||||
resolution: {integrity: sha512-6+cemagaGsOC8X3XWPCn7Ek+jjwyH2/NdTyBcEH7FtFjC3Ciyih2Xx6/GSRirZolxmxENtbvfwu1WV5RzutgCw==}
|
||||
engines: {node: '>=22'}
|
||||
|
||||
trim-lines@3.0.1:
|
||||
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
|
||||
|
||||
@@ -9025,6 +9174,66 @@ snapshots:
|
||||
'@keyv/serialize@1.1.1':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-android-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-android-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-darwin-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-darwin-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-freebsd-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-freebsd-ia32@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-freebsd-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-arm@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-ia32@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-loong64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-ppc64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-riscv64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-linux-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-openbsd-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-openbsd-ia32@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-openbsd-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-win32-arm64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-win32-ia32@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@koromix/koffi-win32-x64@3.3.6':
|
||||
optional: true
|
||||
|
||||
'@linear/sdk@97.0.0(graphql@16.14.2)':
|
||||
dependencies:
|
||||
'@graphql-typed-document-node/core': 3.2.0(graphql@16.14.2)
|
||||
@@ -10987,6 +11196,21 @@ snapshots:
|
||||
- '@types/tiptap__extensions'
|
||||
- '@types/tiptap__pm'
|
||||
|
||||
'@transcribe-cpp/darwin-arm64-metal@0.4.1':
|
||||
optional: true
|
||||
|
||||
'@transcribe-cpp/darwin-x64-cpu@0.4.1':
|
||||
optional: true
|
||||
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan@0.4.1':
|
||||
optional: true
|
||||
|
||||
'@transcribe-cpp/linux-x64-cpu-vulkan@0.4.1':
|
||||
optional: true
|
||||
|
||||
'@transcribe-cpp/win32-x64-cpu-vulkan@0.4.1':
|
||||
optional: true
|
||||
|
||||
'@tsrs/darwin-arm64@0.18.0-ts7.1.0-dev.20260929':
|
||||
optional: true
|
||||
|
||||
@@ -13196,6 +13420,30 @@ snapshots:
|
||||
|
||||
kleur@3.0.3: {}
|
||||
|
||||
koffi@3.3.6:
|
||||
optionalDependencies:
|
||||
'@koromix/koffi-android-arm64': 3.3.6
|
||||
'@koromix/koffi-android-x64': 3.3.6
|
||||
'@koromix/koffi-darwin-arm64': 3.3.6
|
||||
'@koromix/koffi-darwin-x64': 3.3.6
|
||||
'@koromix/koffi-freebsd-arm64': 3.3.6
|
||||
'@koromix/koffi-freebsd-ia32': 3.3.6
|
||||
'@koromix/koffi-freebsd-x64': 3.3.6
|
||||
'@koromix/koffi-linux-arm': 3.3.6
|
||||
'@koromix/koffi-linux-arm64': 3.3.6
|
||||
'@koromix/koffi-linux-ia32': 3.3.6
|
||||
'@koromix/koffi-linux-loong64': 3.3.6
|
||||
'@koromix/koffi-linux-ppc64': 3.3.6
|
||||
'@koromix/koffi-linux-riscv64': 3.3.6
|
||||
'@koromix/koffi-linux-x64': 3.3.6
|
||||
'@koromix/koffi-openbsd-arm64': 3.3.6
|
||||
'@koromix/koffi-openbsd-ia32': 3.3.6
|
||||
'@koromix/koffi-openbsd-x64': 3.3.6
|
||||
'@koromix/koffi-win32-arm64': 3.3.6
|
||||
'@koromix/koffi-win32-ia32': 3.3.6
|
||||
'@koromix/koffi-win32-x64': 3.3.6
|
||||
optional: true
|
||||
|
||||
layout-base@1.0.2: {}
|
||||
|
||||
layout-base@2.0.1: {}
|
||||
@@ -15288,6 +15536,17 @@ snapshots:
|
||||
tldts: 7.4.18
|
||||
optional: true
|
||||
|
||||
transcribe-cpp@0.4.1:
|
||||
dependencies:
|
||||
koffi: 3.3.6
|
||||
optionalDependencies:
|
||||
'@transcribe-cpp/darwin-arm64-metal': 0.4.1
|
||||
'@transcribe-cpp/darwin-x64-cpu': 0.4.1
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan': 0.4.1
|
||||
'@transcribe-cpp/linux-x64-cpu-vulkan': 0.4.1
|
||||
'@transcribe-cpp/win32-x64-cpu-vulkan': 0.4.1
|
||||
optional: true
|
||||
|
||||
trim-lines@3.0.1: {}
|
||||
|
||||
trough@2.2.0: {}
|
||||
|
||||
@@ -61,6 +61,8 @@ allowBuilds:
|
||||
cpu-features: true
|
||||
electron-winstaller: false
|
||||
esbuild: true
|
||||
# Its install script only rebuilds when no @koromix/koffi-<platform> prebuilt is installed.
|
||||
koffi: false
|
||||
msw: false
|
||||
node-pty: true
|
||||
ssh2: false
|
||||
|
||||
@@ -11,33 +11,49 @@ afterEach(() => {
|
||||
}
|
||||
})
|
||||
|
||||
function resourcesWith(packageName: string): string {
|
||||
function resourcesWith(files: string[]): string {
|
||||
const resources = mkdtempSync(join(tmpdir(), 'orca-serve-speech-'))
|
||||
roots.push(resources)
|
||||
const dir = join(resources, 'node_modules', packageName)
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(join(dir, 'sherpa-onnx.node'), '')
|
||||
for (const file of files) {
|
||||
const path = join(resources, 'node_modules', file)
|
||||
mkdirSync(join(path, '..'), { recursive: true })
|
||||
writeFileSync(path, '')
|
||||
}
|
||||
return resources
|
||||
}
|
||||
|
||||
describe("finding the app's speech recognizer (#31174)", () => {
|
||||
it('finds the copy a packaged app ships in its resources', () => {
|
||||
const resources = resourcesWith('sherpa-onnx-linux-x64')
|
||||
expect(findAppSpeechRecognizerDir(join(resources, 'app.asar.unpacked'), 'linux', 'x64')).toBe(
|
||||
join(resources, 'node_modules', 'sherpa-onnx-linux-x64')
|
||||
describe("finding the app's speech engines (#31174)", () => {
|
||||
it('hands orcad the node_modules a packaged app ships its sherpa recognizer in', () => {
|
||||
const resources = resourcesWith(['sherpa-onnx-darwin-x64/sherpa-onnx.node'])
|
||||
expect(findAppSpeechRecognizerDir(join(resources, 'app.asar.unpacked'), 'darwin', 'x64')).toBe(
|
||||
join(resources, 'node_modules')
|
||||
)
|
||||
})
|
||||
|
||||
it('answers nothing when the app ships no recognizer for this platform', () => {
|
||||
const resources = resourcesWith('sherpa-onnx-linux-arm64')
|
||||
it('hands orcad the node_modules holding transcribe-cpp and its native package', () => {
|
||||
const resources = resourcesWith([
|
||||
'transcribe-cpp/package.json',
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan/contract.json'
|
||||
])
|
||||
expect(findAppSpeechRecognizerDir(join(resources, 'app.asar.unpacked'), 'linux', 'arm64')).toBe(
|
||||
join(resources, 'node_modules')
|
||||
)
|
||||
})
|
||||
|
||||
it('answers nothing when the app ships no engine for this platform', () => {
|
||||
const resources = resourcesWith([
|
||||
'transcribe-cpp/package.json',
|
||||
'@transcribe-cpp/linux-arm64-cpu-vulkan/contract.json',
|
||||
'sherpa-onnx-linux-arm64/sherpa-onnx.node'
|
||||
])
|
||||
expect(
|
||||
findAppSpeechRecognizerDir(join(resources, 'app.asar.unpacked'), 'linux', 'x64')
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
// A loaded addon is locked on Windows; orcad holding the app's copy would block app updates.
|
||||
it('never hands orcad the recognizer on Windows', () => {
|
||||
const resources = resourcesWith('sherpa-onnx-win-x64')
|
||||
it('never hands orcad the engines on Windows', () => {
|
||||
const resources = resourcesWith(['sherpa-onnx-win-x64/sherpa-onnx.node'])
|
||||
expect(
|
||||
findAppSpeechRecognizerDir(join(resources, 'app.asar.unpacked'), 'win32', 'x64')
|
||||
).toBeUndefined()
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { speechRecognizerPackageName } from '../../shared/speech-recognizer-package'
|
||||
import { hasSpeechEnginePackage } from '../../shared/speech-recognizer-package'
|
||||
|
||||
/**
|
||||
* The installed app's on-device recognizer, for orcad's dictation (#31174). electron-builder puts
|
||||
* it in `resources/node_modules`, beside the app root; a dev checkout keeps it in node_modules.
|
||||
* The installed app's node_modules holding its on-device speech engines, for orcad's dictation
|
||||
* (#31174). electron-builder puts them in `resources/node_modules`, beside the app root; a dev
|
||||
* checkout keeps them in node_modules.
|
||||
*
|
||||
* Not on Windows: a loaded addon locks its files for the server's life, which would make the next
|
||||
* app update fail to replace them. Windows orcad keeps cloud dictation only.
|
||||
@@ -17,8 +17,9 @@ export function findAppSpeechRecognizerDir(
|
||||
if (platform === 'win32') {
|
||||
return undefined
|
||||
}
|
||||
const name = speechRecognizerPackageName(platform, arch)
|
||||
return [join(dirname(appRoot), 'node_modules', name), join(appRoot, 'node_modules', name)].find(
|
||||
(dir) => existsSync(join(dir, 'sherpa-onnx.node'))
|
||||
return [join(dirname(appRoot), 'node_modules'), join(appRoot, 'node_modules')].find(
|
||||
(dir) =>
|
||||
hasSpeechEnginePackage(dir, 'transcribe-cpp', platform, arch) ||
|
||||
hasSpeechEnginePackage(dir, 'sherpa', platform, arch)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { net } from 'electron'
|
||||
import { ModelManager } from '../speech/model-manager'
|
||||
import { SttService } from '../speech/stt-service'
|
||||
import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker'
|
||||
import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback'
|
||||
import { spawnSttUtilityProcess } from '../speech/stt-worker-utility-process'
|
||||
import type { SpeechServiceFactories } from '../speech/speech-runtime-service'
|
||||
import type {
|
||||
@@ -41,5 +43,8 @@ export const openElectronSpeechDownloadRequest: OpenSpeechDownloadRequest = (url
|
||||
export const electronSpeechServiceFactories: SpeechServiceFactories = {
|
||||
createModelManager: (customModelsDir) =>
|
||||
new ModelManager(customModelsDir, openElectronSpeechDownloadRequest),
|
||||
createSttService: (models) => new SttService(models, spawnSttUtilityProcess)
|
||||
createSttService: (models, gpuEnabled) => {
|
||||
const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled)
|
||||
return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttUtilityProcess, gpu))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { openNodeSpeechDownloadRequest } from '../speech/node-speech-download-re
|
||||
import { canReadOpenAiSpeechApiKey } from '../speech/openai-api-key-store'
|
||||
import type { SpeechServiceFactories } from '../speech/speech-runtime-service'
|
||||
import { SttService } from '../speech/stt-service'
|
||||
import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker'
|
||||
import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback'
|
||||
import { spawnSttForkedProcess } from '../speech/stt-worker-forked-process'
|
||||
|
||||
// Local speech needs the installed app recognizer supplied by orca serve.
|
||||
@@ -10,5 +12,8 @@ export const orcadSpeechServiceFactories: SpeechServiceFactories = {
|
||||
createModelManager: (customModelsDir) =>
|
||||
// Headless key reads cannot open keychain prompts, so readiness may verify decryption.
|
||||
new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadOpenAiSpeechApiKey),
|
||||
createSttService: (models) => new SttService(models, spawnSttForkedProcess)
|
||||
createSttService: (models, gpuEnabled) => {
|
||||
const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled)
|
||||
return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ export class RuntimeMobileDictationController {
|
||||
throw new Error('voice_model_not_selected')
|
||||
}
|
||||
const manifest = getCatalogModel(modelId)
|
||||
if (manifest && isLocalSpeechModel(manifest) && !hasLocalSpeechRecognizer()) {
|
||||
if (manifest && isLocalSpeechModel(manifest) && !hasLocalSpeechRecognizer(manifest)) {
|
||||
throw new Error(LOCAL_SPEECH_UNAVAILABLE_ERROR)
|
||||
}
|
||||
const modelState = await getSpeechModelManager(store).getModelState(modelId)
|
||||
|
||||
@@ -39,10 +39,10 @@ export class RuntimeMobileSpeechCatalog {
|
||||
const states = await getSpeechModelManager(store).getModelStates()
|
||||
const stateById = new Map(states.map((state) => [state.id, state]))
|
||||
// Omit unsupported status variants; older phones could treat them as pickable models.
|
||||
const localRunnable = hasLocalSpeechRecognizer()
|
||||
const runnable = SPEECH_MODEL_CATALOG.filter(
|
||||
(manifest) =>
|
||||
isOfferedSpeechModel(manifest) && (localRunnable || !isLocalSpeechModel(manifest))
|
||||
isOfferedSpeechModel(manifest) &&
|
||||
(!isLocalSpeechModel(manifest) || hasLocalSpeechRecognizer(manifest))
|
||||
)
|
||||
const models: RuntimeSpeechModelSummary[] = runnable.map((manifest) => {
|
||||
const state = stateById.get(manifest.id)
|
||||
@@ -67,7 +67,7 @@ export class RuntimeMobileSpeechCatalog {
|
||||
async download(modelId: string): Promise<{ started: true }> {
|
||||
const store = this.requireStore()
|
||||
const manifest = getCatalogModel(modelId)
|
||||
if (!manifest || !isLocalSpeechModel(manifest) || !hasLocalSpeechRecognizer()) {
|
||||
if (!manifest || !isLocalSpeechModel(manifest) || !hasLocalSpeechRecognizer(manifest)) {
|
||||
throw new Error('voice_model_not_downloadable')
|
||||
}
|
||||
void getSpeechModelManager(store)
|
||||
|
||||
@@ -12,7 +12,8 @@ type SpeechSettingsStore = {
|
||||
|
||||
export type SpeechServiceFactories = {
|
||||
createModelManager(customModelsDir: string | undefined): ModelManager
|
||||
createSttService(models: ModelManager): SttService
|
||||
/** `gpuEnabled` reads the user's Voice setting at each recognizer start. */
|
||||
createSttService(models: ModelManager, gpuEnabled: () => boolean): SttService
|
||||
}
|
||||
|
||||
let factories: SpeechServiceFactories | null = null
|
||||
@@ -43,7 +44,10 @@ export function getSpeechModelManager(store: SpeechSettingsStore): ModelManager
|
||||
|
||||
export function getSpeechSttService(store: SpeechSettingsStore): SttService {
|
||||
if (!sttService) {
|
||||
sttService = requireFactories().createSttService(getSpeechModelManager(store))
|
||||
sttService = requireFactories().createSttService(
|
||||
getSpeechModelManager(store),
|
||||
() => store.getSettings().voice?.speechGpu !== 'off'
|
||||
)
|
||||
}
|
||||
return sttService
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { release } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { SttGpuPolicy } from './stt-worker-cpu-fallback'
|
||||
import { getSpeechEngineModulesDir } from './stt-worker-paths'
|
||||
|
||||
const GPU_FAILURE_MARKER_FILE = 'speech-gpu-failed.json'
|
||||
|
||||
let cachedGpuFailureKey: string | null = null
|
||||
|
||||
// The GPU is retried once transcribe-cpp or the OS (on macOS, also the GPU driver) changes.
|
||||
function gpuFailureKey(): string {
|
||||
if (cachedGpuFailureKey) {
|
||||
return cachedGpuFailureKey
|
||||
}
|
||||
let version = 'unknown'
|
||||
const modulesDir = getSpeechEngineModulesDir('transcribe-cpp')
|
||||
if (modulesDir) {
|
||||
try {
|
||||
version = JSON.parse(
|
||||
readFileSync(join(modulesDir, 'transcribe-cpp', 'package.json'), 'utf8')
|
||||
).version
|
||||
} catch {
|
||||
// An unreadable version keys the marker as 'unknown'; the next good read retries the GPU.
|
||||
}
|
||||
}
|
||||
cachedGpuFailureKey = `${version}|${process.platform}|${process.arch}|${release()}`
|
||||
return cachedGpuFailureKey
|
||||
}
|
||||
|
||||
function readMarkerKey(file: string): string | null {
|
||||
try {
|
||||
return JSON.parse(readFileSync(file, 'utf8')).key ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** `gpuEnabled` is the user's Voice setting; the marker records a GPU that failed on this machine. */
|
||||
export function createSttGpuPolicy(modelsDir: string, gpuEnabled: () => boolean): SttGpuPolicy {
|
||||
const file = join(modelsDir, GPU_FAILURE_MARKER_FILE)
|
||||
return {
|
||||
allowGpu: () => {
|
||||
if (!gpuEnabled()) {
|
||||
return false
|
||||
}
|
||||
const marker = readMarkerKey(file)
|
||||
return marker === null || marker !== gpuFailureKey()
|
||||
},
|
||||
markGpuFailed: () => {
|
||||
try {
|
||||
writeFileSync(file, JSON.stringify({ key: gpuFailureKey() }))
|
||||
} catch (error) {
|
||||
console.warn('[speech] Could not record the GPU failure:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { RecognizerConfigInput } from './stt-worker-model-config'
|
||||
|
||||
export type SttRecognizerInit = RecognizerConfigInput & {
|
||||
/** The node_modules directory holding this model's engine package. */
|
||||
speechModulesDir: string
|
||||
}
|
||||
|
||||
export type SttRecognizerEvent =
|
||||
| { type: 'partial'; streamId: string; text: string }
|
||||
| { type: 'final'; streamId: string; text: string }
|
||||
/** One decoded offline chunk; `samples` counts the stream's input-rate samples decoded so far. */
|
||||
| { type: 'chunk'; streamId: string; text: string; samples: number }
|
||||
|
||||
export type SttRecognizerPost = (event: SttRecognizerEvent) => void
|
||||
|
||||
/** One loaded model in the speech host child, shared by every dictation stream; calls never overlap. */
|
||||
export type SttRecognizer = {
|
||||
feed(streamId: string, samples: Float32Array, sampleRate: number): void | Promise<void>
|
||||
/** Decode the stream's buffered audio, post its text and drop the stream; may throw after posting. */
|
||||
finish(streamId: string): void | Promise<void>
|
||||
/** Drop the stream's audio undecoded. */
|
||||
discard(streamId: string): void
|
||||
}
|
||||
@@ -43,8 +43,9 @@ export async function prewarmSttModel(
|
||||
return
|
||||
}
|
||||
const ready =
|
||||
manifest !== undefined &&
|
||||
config !== null &&
|
||||
hasLocalSpeechRecognizer() &&
|
||||
hasLocalSpeechRecognizer(manifest) &&
|
||||
(await state.modelManager.getModelState(modelId)).status === 'ready'
|
||||
for (;;) {
|
||||
// Never disturb a dictation; whatever it loaded is what the user is using.
|
||||
|
||||
@@ -19,7 +19,8 @@ import {
|
||||
teardownIdleSttEngine,
|
||||
teardownSttEngine
|
||||
} from './stt-session-stop'
|
||||
import { getSherpaModulePath, LOCAL_SPEECH_UNAVAILABLE_ERROR } from './stt-worker-paths'
|
||||
import { speechEngineForModelFiles } from '../../shared/speech-model-engine'
|
||||
import { getSpeechEngineModulesDir, LOCAL_SPEECH_UNAVAILABLE_ERROR } from './stt-worker-paths'
|
||||
import {
|
||||
attachSttWorkerLifecycle,
|
||||
initializeSttWorker,
|
||||
@@ -166,8 +167,9 @@ export function spawnSttEngine(
|
||||
config: SttRecognizerConfig,
|
||||
manifest: SpeechModelManifest
|
||||
): SttEngine {
|
||||
const sherpaModulePath = getSherpaModulePath()
|
||||
if (!sherpaModulePath) {
|
||||
const files = manifest.files ?? []
|
||||
const speechModulesDir = getSpeechEngineModulesDir(speechEngineForModelFiles(files))
|
||||
if (!speechModulesDir) {
|
||||
throw new Error(LOCAL_SPEECH_UNAVAILABLE_ERROR)
|
||||
}
|
||||
clearSttIdleTeardownTimer(state)
|
||||
@@ -200,12 +202,12 @@ export function spawnSttEngine(
|
||||
engine.ready.catch(() => undefined)
|
||||
state.engine = engine
|
||||
initializeSttWorker(worker, {
|
||||
sherpaModulePath,
|
||||
speechModulesDir,
|
||||
modelDir: state.modelManager.getModelDir(config.modelId),
|
||||
modelType: manifest.type,
|
||||
streaming: manifest.streaming,
|
||||
sampleRate: manifest.sampleRate,
|
||||
files: manifest.files ?? [],
|
||||
files,
|
||||
hotwordsFilePath: config.hotwordsFilePath,
|
||||
modelingUnit: manifest.modelingUnit,
|
||||
language: config.language
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/* oxlint-disable typescript-eslint/no-explicit-any -- sherpa-onnx native addon has no type definitions */
|
||||
import { join } from 'node:path'
|
||||
import { speechRecognizerPackageName } from '../../shared/speech-recognizer-package'
|
||||
import { resampleToRate } from './stt-audio-resample'
|
||||
import { OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
import { buildRecognizerConfig } from './stt-worker-model-config'
|
||||
import { createStopTailPadding } from './stt-stop-tail-padding'
|
||||
import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer'
|
||||
|
||||
// One per dictation session; every session shares the one loaded recognizer.
|
||||
type SessionStream = {
|
||||
// Online streams live for the session; offline ones are made per decode.
|
||||
online: any
|
||||
offlineChunker: OfflineAudioChunker | null
|
||||
// Primed on the session's first feed so stop never waits on another session's stream.
|
||||
primed: boolean
|
||||
// Streaming models report the same hypothesis on most 100 ms feeds; only changes are posted.
|
||||
lastPartialText: string
|
||||
}
|
||||
|
||||
export function createSherpaRecognizer(
|
||||
init: SttRecognizerInit,
|
||||
post: SttRecognizerPost
|
||||
): SttRecognizer {
|
||||
// Use the platform native addon: the main sherpa-onnx WASM package cannot load host model files.
|
||||
const sherpa: any = require(
|
||||
join(init.speechModulesDir, speechRecognizerPackageName(process.platform, process.arch))
|
||||
)
|
||||
const { streaming: isStreaming, sampleRate: modelSampleRate } = init
|
||||
const { online, config } = buildRecognizerConfig(init)
|
||||
const recognizer = online
|
||||
? sherpa.createOnlineRecognizer(config)
|
||||
: sherpa.createOfflineRecognizer(config)
|
||||
const streams = new Map<string, SessionStream>()
|
||||
|
||||
const openStream = (streamId: string): SessionStream => {
|
||||
const existing = streams.get(streamId)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const stream: SessionStream = {
|
||||
online: isStreaming ? sherpa.createOnlineStream(recognizer) : null,
|
||||
offlineChunker: isStreaming ? null : new OfflineAudioChunker(modelSampleRate),
|
||||
primed: false,
|
||||
lastPartialText: ''
|
||||
}
|
||||
streams.set(streamId, stream)
|
||||
return stream
|
||||
}
|
||||
|
||||
const decodeOfflineChunk = (samples: Float32Array): string => {
|
||||
const stream = sherpa.createOfflineStream(recognizer)
|
||||
sherpa.acceptWaveformOffline(stream, { sampleRate: modelSampleRate, samples })
|
||||
sherpa.decodeOfflineStream(recognizer, stream)
|
||||
const result = JSON.parse(sherpa.getOfflineStreamResultAsJson(stream))
|
||||
return result?.text?.trim() ?? ''
|
||||
}
|
||||
|
||||
const feedOnline = (streamId: string, stream: SessionStream, samples: Float32Array): void => {
|
||||
if (!stream.primed) {
|
||||
// New streams start with empty encoder caches; zipformer en-20M dropped most of the first second
|
||||
// (first word wrong on 71 of 73 LibriSpeech clips). A second of silence fills them first.
|
||||
sherpa.acceptWaveformOnline(stream.online, {
|
||||
sampleRate: modelSampleRate,
|
||||
samples: new Float32Array(modelSampleRate)
|
||||
})
|
||||
stream.primed = true
|
||||
}
|
||||
sherpa.acceptWaveformOnline(stream.online, { sampleRate: modelSampleRate, samples })
|
||||
while (sherpa.isOnlineStreamReady(recognizer, stream.online)) {
|
||||
sherpa.decodeOnlineStream(recognizer, stream.online)
|
||||
}
|
||||
const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online))
|
||||
const text = result?.text?.trim()
|
||||
if (text && text !== stream.lastPartialText) {
|
||||
stream.lastPartialText = text
|
||||
post({ type: 'partial', streamId, text })
|
||||
}
|
||||
if (sherpa.isEndpoint(recognizer, stream.online)) {
|
||||
if (text) {
|
||||
post({ type: 'final', streamId, text })
|
||||
}
|
||||
sherpa.reset(recognizer, stream.online)
|
||||
stream.lastPartialText = ''
|
||||
}
|
||||
}
|
||||
|
||||
const feedOffline = (streamId: string, stream: SessionStream, samples: Float32Array): void => {
|
||||
// Bound ONNX allocations below Chromium's >=2GiB crash threshold (#7925); consumers append final segments.
|
||||
const readyChunks = stream.offlineChunker?.push(new Float32Array(samples)) ?? []
|
||||
// push() already consumed these windows; keep decoding later ones after a failure.
|
||||
let firstError: unknown = null
|
||||
for (const chunk of readyChunks) {
|
||||
try {
|
||||
const text = decodeOfflineChunk(chunk)
|
||||
if (text) {
|
||||
post({ type: 'final', streamId, text })
|
||||
}
|
||||
} catch (err) {
|
||||
firstError ??= err
|
||||
}
|
||||
}
|
||||
if (firstError) {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
|
||||
const finishStream = (stream: SessionStream): string => {
|
||||
if (stream.online) {
|
||||
sherpa.acceptWaveformOnline(stream.online, {
|
||||
sampleRate: modelSampleRate,
|
||||
samples: createStopTailPadding(modelSampleRate)
|
||||
})
|
||||
sherpa.inputFinished(stream.online)
|
||||
while (sherpa.isOnlineStreamReady(recognizer, stream.online)) {
|
||||
sherpa.decodeOnlineStream(recognizer, stream.online)
|
||||
}
|
||||
const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online))
|
||||
return result?.text?.trim() ?? ''
|
||||
}
|
||||
// flush() leaves less than one bounded chunk.
|
||||
const remaining = stream.offlineChunker?.flush()
|
||||
return remaining && remaining.length > 0 ? decodeOfflineChunk(remaining) : ''
|
||||
}
|
||||
|
||||
return {
|
||||
feed(streamId, samples, sampleRate) {
|
||||
const stream = openStream(streamId)
|
||||
// Normalize rates before native decode: mixed rates on one recognizer abort the process.
|
||||
const resampled = resampleToRate(samples, sampleRate || modelSampleRate, modelSampleRate)
|
||||
if (isStreaming) {
|
||||
feedOnline(streamId, stream, resampled)
|
||||
} else {
|
||||
feedOffline(streamId, stream, resampled)
|
||||
}
|
||||
},
|
||||
finish(streamId) {
|
||||
const stream = streams.get(streamId)
|
||||
streams.delete(streamId)
|
||||
const text = stream ? finishStream(stream) : ''
|
||||
if (text) {
|
||||
post({ type: 'final', streamId, text })
|
||||
}
|
||||
},
|
||||
discard(streamId) {
|
||||
streams.delete(streamId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { availableParallelism } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import type * as TranscribeCpp from 'transcribe-cpp'
|
||||
import { resampleToRate } from './stt-audio-resample'
|
||||
import { OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
import { resolveFile } from './stt-worker-model-config'
|
||||
import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer'
|
||||
|
||||
// Past ~8 threads decode slowed 2-4x under load in the 2026-11 benchmark; E-cores and SMT siblings
|
||||
// don't help. Half the logical CPUs is close to the performance cores on Apple silicon and SMT x86.
|
||||
function performanceCoreThreads(): number {
|
||||
const logical = availableParallelism()
|
||||
return Math.min(logical, 8, Math.max(4, Math.floor(logical / 2)))
|
||||
}
|
||||
|
||||
// The hotwords file is written in sherpa's format, one `term :score` per line. The host deletes it
|
||||
// once dictation starts, so a CPU fallback's reload finds it gone and runs without.
|
||||
function readVocabulary(path: string | undefined): string[] {
|
||||
if (!path || !existsSync(path)) {
|
||||
return []
|
||||
}
|
||||
return readFileSync(path, 'utf8')
|
||||
.split('\n')
|
||||
.map((line) => line.replace(/\s+:[\d.]+\s*$/, '').trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
// Totals, not the nominal rate ratio: per-feed resampling rounds, and the drift would replay decoded audio.
|
||||
type StreamCoverage = {
|
||||
chunker: OfflineAudioChunker
|
||||
inputSamples: number
|
||||
resampledSamples: number
|
||||
decodedSamples: number
|
||||
}
|
||||
|
||||
export async function createTranscribeCppRecognizer(
|
||||
init: SttRecognizerInit,
|
||||
post: SttRecognizerPost
|
||||
): Promise<SttRecognizer> {
|
||||
const entry = join(init.speechModulesDir, 'transcribe-cpp', 'dist', 'index.js')
|
||||
const transcribe: typeof TranscribeCpp = await import(pathToFileURL(entry).href)
|
||||
const model = await transcribe.TranscribeModel.load(
|
||||
resolveFile(init.files, '.gguf', init.modelDir, '.gguf')
|
||||
)
|
||||
// The child runs one call at a time, so every stream can share one session.
|
||||
const session = model.createSession({ nThreads: performanceCoreThreads() })
|
||||
const vocabulary = readVocabulary(init.hotwordsFilePath)
|
||||
const options: TranscribeCpp.TranscribeOptions = {
|
||||
timestamps: 'none',
|
||||
...(init.language && model.capabilities.languages.includes(init.language)
|
||||
? { language: init.language }
|
||||
: {}),
|
||||
...(vocabulary.length > 0 && model.supports('vocabulary') ? { vocabulary } : {})
|
||||
}
|
||||
const modelRate = model.capabilities.nativeSampleRate || init.sampleRate
|
||||
const streams = new Map<string, StreamCoverage>()
|
||||
|
||||
const transcribeChunk = async (chunk: Float32Array): Promise<string> => {
|
||||
try {
|
||||
return (await session.run(chunk, options)).text
|
||||
} catch (error) {
|
||||
// Repetition loops (Whisper on noise) and length caps are about this audio, not the GPU; keep what decoded.
|
||||
if (error instanceof transcribe.OutputTruncated) {
|
||||
return error.partialResult?.text ?? ''
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// The first run compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop.
|
||||
await transcribeChunk(new Float32Array(Math.round(modelRate / 2)))
|
||||
|
||||
// Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay.
|
||||
const decode = async (streamId: string, stream: StreamCoverage, chunk: Float32Array) => {
|
||||
const text = await transcribeChunk(chunk)
|
||||
stream.decodedSamples += chunk.length
|
||||
post({
|
||||
type: 'chunk',
|
||||
streamId,
|
||||
text: text.trim(),
|
||||
samples: Math.round((stream.decodedSamples * stream.inputSamples) / stream.resampledSamples)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
async feed(streamId, samples, sampleRate) {
|
||||
let stream = streams.get(streamId)
|
||||
if (!stream) {
|
||||
stream = {
|
||||
chunker: new OfflineAudioChunker(modelRate),
|
||||
inputSamples: 0,
|
||||
resampledSamples: 0,
|
||||
decodedSamples: 0
|
||||
}
|
||||
streams.set(streamId, stream)
|
||||
}
|
||||
// The binding borrows PCM until the run settles; resampleToRate may return the caller's buffer.
|
||||
const resampled = new Float32Array(
|
||||
resampleToRate(samples, sampleRate || modelRate, modelRate)
|
||||
)
|
||||
stream.inputSamples += samples.length
|
||||
stream.resampledSamples += resampled.length
|
||||
for (const chunk of stream.chunker.push(resampled)) {
|
||||
await decode(streamId, stream, chunk)
|
||||
}
|
||||
},
|
||||
async finish(streamId) {
|
||||
const stream = streams.get(streamId)
|
||||
streams.delete(streamId)
|
||||
const remaining = stream?.chunker.flush()
|
||||
if (stream && remaining) {
|
||||
await decode(streamId, stream, remaining)
|
||||
}
|
||||
},
|
||||
discard(streamId) {
|
||||
streams.delete(streamId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { spawnSttWorkerWithCpuFallback } from './stt-worker-cpu-fallback'
|
||||
|
||||
class FakeChild extends EventEmitter {
|
||||
readonly posted: { type: string; samples?: Float32Array }[] = []
|
||||
constructor(readonly cpuOnly: boolean) {
|
||||
super()
|
||||
}
|
||||
postMessage(message: { type: string; samples?: Float32Array }): void {
|
||||
this.posted.push(message)
|
||||
}
|
||||
terminate(): Promise<number> {
|
||||
return Promise.resolve(0)
|
||||
}
|
||||
attachAudioPort(): boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
function setup(): {
|
||||
worker: ReturnType<typeof spawnSttWorkerWithCpuFallback>
|
||||
children: FakeChild[]
|
||||
events: unknown[]
|
||||
marks: () => number
|
||||
} {
|
||||
const children: FakeChild[] = []
|
||||
let marks = 0
|
||||
const worker = spawnSttWorkerWithCpuFallback(
|
||||
({ cpuOnly }) => {
|
||||
const child = new FakeChild(cpuOnly)
|
||||
children.push(child)
|
||||
return child
|
||||
},
|
||||
{ allowGpu: () => true, markGpuFailed: () => void (marks += 1) }
|
||||
)
|
||||
const events: unknown[] = []
|
||||
worker.on('message', (event: unknown) => events.push(event))
|
||||
worker.postMessage({
|
||||
type: 'init',
|
||||
speechModulesDir: '/app/node_modules',
|
||||
modelDir: '/models/parakeet',
|
||||
modelType: 'transducer',
|
||||
streaming: false,
|
||||
sampleRate: 16000,
|
||||
files: ['model-Q8_0.gguf']
|
||||
})
|
||||
return { worker, children, events, marks: () => marks }
|
||||
}
|
||||
|
||||
const feed = (
|
||||
n: number
|
||||
): { type: 'feed'; streamId: string; samples: Float32Array; sampleRate: number } => ({
|
||||
type: 'feed',
|
||||
streamId: '1',
|
||||
samples: new Float32Array(n),
|
||||
sampleRate: 16000
|
||||
})
|
||||
|
||||
describe('GPU speech process falling back to the CPU', () => {
|
||||
it('replays only the audio the GPU had not decoded when it crashes mid-stop', () => {
|
||||
const { worker, children, events, marks } = setup()
|
||||
const [gpu] = children
|
||||
gpu.emit('message', { type: 'ready' })
|
||||
worker.postMessage(feed(300))
|
||||
worker.postMessage(feed(300))
|
||||
gpu.emit('message', { type: 'chunk', streamId: '1', text: 'first', samples: 400 })
|
||||
worker.postMessage(feed(300))
|
||||
worker.postMessage({ type: 'stop', streamId: '1' })
|
||||
gpu.emit('exit', 1)
|
||||
// The dead process's late messages must not settle the stop or duplicate text.
|
||||
gpu.emit('message', { type: 'chunk', streamId: '1', text: 'late', samples: 900 })
|
||||
gpu.emit('message', { type: 'stopped', streamId: '1' })
|
||||
|
||||
const cpu = children[1]
|
||||
expect(cpu.cpuOnly).toBe(true)
|
||||
expect(cpu.posted.map((m) => [m.type, m.samples?.length])).toEqual([
|
||||
['init', undefined],
|
||||
['feed', 200],
|
||||
['feed', 300],
|
||||
['stop', undefined]
|
||||
])
|
||||
expect(marks()).toBe(0)
|
||||
cpu.emit('message', { type: 'ready' })
|
||||
expect(marks()).toBe(1)
|
||||
cpu.emit('message', { type: 'chunk', streamId: '1', text: 'second', samples: 500 })
|
||||
cpu.emit('message', { type: 'stopped', streamId: '1' })
|
||||
expect(events).toEqual([
|
||||
{ type: 'ready' },
|
||||
{ type: 'final', streamId: '1', text: 'first' },
|
||||
{ type: 'final', streamId: '1', text: 'second' },
|
||||
{ type: 'stopped', streamId: '1' }
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the GPU for later sessions when only this audio failed', () => {
|
||||
const { worker, children, marks } = setup()
|
||||
const [gpu] = children
|
||||
gpu.emit('message', { type: 'ready' })
|
||||
worker.postMessage(feed(100))
|
||||
gpu.emit('message', { type: 'error', streamId: '1', error: 'bad input' })
|
||||
children[1].emit('message', { type: 'ready' })
|
||||
expect(marks()).toBe(0)
|
||||
})
|
||||
|
||||
it('does not replay a canceled dictation', () => {
|
||||
const { worker, children } = setup()
|
||||
const [gpu] = children
|
||||
gpu.emit('message', { type: 'ready' })
|
||||
worker.postMessage(feed(100))
|
||||
worker.postMessage({ type: 'discard', streamId: '1' })
|
||||
gpu.emit('exit', 1)
|
||||
expect(children[1].posted.map((m) => m.type)).toEqual(['init', 'discard'])
|
||||
})
|
||||
|
||||
it('reports an idle GPU process killed between dictations instead of moving it to the CPU', () => {
|
||||
const { worker, children, marks } = setup()
|
||||
const [gpu] = children
|
||||
const exits: number[] = []
|
||||
worker.on('exit', (code: number) => exits.push(code))
|
||||
gpu.emit('message', { type: 'ready' })
|
||||
worker.postMessage({ type: 'stop', streamId: '1' })
|
||||
gpu.emit('message', { type: 'stopped', streamId: '1' })
|
||||
gpu.emit('exit', 137)
|
||||
expect(children).toHaveLength(1)
|
||||
expect(exits).toEqual([137])
|
||||
expect(marks()).toBe(0)
|
||||
})
|
||||
|
||||
it('fails the worker when the CPU replacement cannot load the model mid-dictation', () => {
|
||||
const { worker, children } = setup()
|
||||
const exits: number[] = []
|
||||
worker.on('exit', (code: number) => exits.push(code))
|
||||
children[0].emit('message', { type: 'ready' })
|
||||
worker.postMessage(feed(100))
|
||||
children[0].emit('exit', 1)
|
||||
children[1].emit('message', { type: 'error', error: 'model load failed' })
|
||||
expect(exits).toEqual([1])
|
||||
})
|
||||
|
||||
it('keeps a GPU process on IPC audio, which it can replay, and hands a CPU process the port', () => {
|
||||
const { worker, children } = setup()
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fakes never touch the port.
|
||||
const port = {} as never
|
||||
expect(worker.attachAudioPort('1', port)).toBe(false)
|
||||
children[0].emit('message', { type: 'ready' })
|
||||
worker.postMessage(feed(100))
|
||||
children[0].emit('exit', 1)
|
||||
expect(worker.attachAudioPort('2', port)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,243 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import type { MessagePortMain } from 'electron'
|
||||
import { speechEngineForModelFiles } from '../../shared/speech-model-engine'
|
||||
import { OFFLINE_DECODE_CHUNK_SECONDS } from './stt-offline-audio-chunker'
|
||||
import type { SttWorkerProcess, SttWorkerRequest } from './stt-worker-process'
|
||||
|
||||
export type SpawnSttChild = (options: { cpuOnly: boolean }) => SttWorkerProcess
|
||||
|
||||
export type SttGpuPolicy = {
|
||||
/** False when the user turned the GPU off or this machine's GPU already failed. */
|
||||
allowGpu(): boolean
|
||||
markGpuFailed(): void
|
||||
}
|
||||
|
||||
type Feed = Extract<SttWorkerRequest, { type: 'feed' }>
|
||||
type ChildMessage =
|
||||
| { type: 'chunk'; streamId: string; text: string; samples: number }
|
||||
| {
|
||||
type: 'ready' | 'stopped' | 'error' | 'partial' | 'final'
|
||||
streamId?: string
|
||||
text?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** A dictation's audio the GPU has not decoded yet, kept for a CPU replay. */
|
||||
type StreamBacklog = {
|
||||
feeds: Feed[]
|
||||
/** Input samples before feeds[0], in the stream's own count. */
|
||||
start: number
|
||||
seconds: number
|
||||
pending: 'stop' | 'discard' | null
|
||||
}
|
||||
|
||||
// Well under the session's 60 s start and stop timeouts, so a CPU replay still fits; covers first-run shader compiles.
|
||||
const GPU_STALL_TIMEOUT_MS = 25_000
|
||||
|
||||
/**
|
||||
* Runs transcribe-cpp on the GPU and, when the GPU fails to load, errors, stalls or crashes the
|
||||
* process, moves every dictation to a CPU-only process and replays the audio not yet decoded.
|
||||
* Session code sees one worker throughout.
|
||||
*/
|
||||
class SttCpuFallbackWorker extends EventEmitter implements SttWorkerProcess {
|
||||
private child!: SttWorkerProcess
|
||||
private detachChild: () => void = () => undefined
|
||||
private cpuOnly: boolean
|
||||
private init: Extract<SttWorkerRequest, { type: 'init' }> | null = null
|
||||
private transcribeCpp = false
|
||||
private ready = false
|
||||
private exitRequested = false
|
||||
private markOnCpuReady = false
|
||||
private readonly streams = new Map<string, StreamBacklog>()
|
||||
private stallTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
constructor(
|
||||
private readonly spawn: SpawnSttChild,
|
||||
private readonly gpu: SttGpuPolicy
|
||||
) {
|
||||
super()
|
||||
this.cpuOnly = !gpu.allowGpu()
|
||||
this.attach(spawn({ cpuOnly: this.cpuOnly }))
|
||||
}
|
||||
|
||||
postMessage(msg: SttWorkerRequest): void {
|
||||
if (msg.type === 'init') {
|
||||
this.init = msg
|
||||
this.transcribeCpp = speechEngineForModelFiles(msg.files) === 'transcribe-cpp'
|
||||
} else if (msg.type === 'feed' && this.canFallBack()) {
|
||||
const stream = this.backlog(msg.streamId)
|
||||
stream.feeds.push(msg)
|
||||
stream.seconds += msg.samples.length / msg.sampleRate
|
||||
} else if ((msg.type === 'stop' || msg.type === 'discard') && this.canFallBack()) {
|
||||
this.backlog(msg.streamId).pending = msg.type
|
||||
}
|
||||
this.watchForStall(false)
|
||||
this.child.postMessage(msg)
|
||||
}
|
||||
|
||||
/** A GPU process keeps audio on IPC, where this wrapper can hold it for a CPU replay. */
|
||||
attachAudioPort(streamId: string, port: MessagePortMain): boolean {
|
||||
return !this.canFallBack() && this.child.attachAudioPort(streamId, port)
|
||||
}
|
||||
|
||||
terminate(): Promise<number> {
|
||||
this.exitRequested = true
|
||||
this.clearStallTimer()
|
||||
return this.child.terminate()
|
||||
}
|
||||
|
||||
private canFallBack(): boolean {
|
||||
return this.transcribeCpp && !this.cpuOnly && !this.exitRequested
|
||||
}
|
||||
|
||||
private backlog(streamId: string): StreamBacklog {
|
||||
let stream = this.streams.get(streamId)
|
||||
if (!stream) {
|
||||
stream = { feeds: [], start: 0, seconds: 0, pending: null }
|
||||
this.streams.set(streamId, stream)
|
||||
}
|
||||
return stream
|
||||
}
|
||||
|
||||
private attach(child: SttWorkerProcess): void {
|
||||
const onMessage = (message: ChildMessage): void => this.receive(message)
|
||||
const onExit = (code: number): void => {
|
||||
// An idle process killed from outside (OOM, Activity Monitor) is not a GPU failure.
|
||||
if (this.canFallBack() && (!this.ready || this.streams.size > 0)) {
|
||||
this.fallBack(true)
|
||||
} else {
|
||||
this.emit('exit', code)
|
||||
}
|
||||
}
|
||||
child.on('message', onMessage)
|
||||
child.on('exit', onExit)
|
||||
this.child = child
|
||||
this.detachChild = () => {
|
||||
child.off('message', onMessage)
|
||||
child.off('exit', onExit)
|
||||
}
|
||||
}
|
||||
|
||||
private receive(message: ChildMessage): void {
|
||||
if (message.type === 'error' && this.canFallBack()) {
|
||||
this.fallBack(!this.ready)
|
||||
return
|
||||
}
|
||||
if (message.type === 'error' && !message.streamId && this.ready) {
|
||||
// The CPU replacement could not load: fail every dictation now rather than answer them empty.
|
||||
this.detachChild()
|
||||
void this.child.terminate().catch(() => undefined)
|
||||
this.emit('exit', 1)
|
||||
return
|
||||
}
|
||||
if (message.type === 'chunk') {
|
||||
const { streamId, text, samples } = message
|
||||
const stream = this.streams.get(streamId)
|
||||
if (stream) {
|
||||
this.trimBacklog(stream, samples)
|
||||
}
|
||||
this.watchForStall(true)
|
||||
if (text) {
|
||||
this.emit('message', { type: 'final', streamId, text })
|
||||
}
|
||||
return
|
||||
}
|
||||
if (message.type === 'ready') {
|
||||
if (this.markOnCpuReady) {
|
||||
this.markOnCpuReady = false
|
||||
this.gpu.markGpuFailed()
|
||||
}
|
||||
if (this.ready) {
|
||||
return
|
||||
}
|
||||
this.ready = true
|
||||
this.watchForStall(true)
|
||||
} else if (message.type === 'stopped' && message.streamId) {
|
||||
this.streams.delete(message.streamId)
|
||||
this.watchForStall(true)
|
||||
}
|
||||
this.emit('message', message)
|
||||
}
|
||||
|
||||
/** `persist`: the GPU itself failed (crash or load error), not just this audio. */
|
||||
private fallBack(persist: boolean): void {
|
||||
this.clearStallTimer()
|
||||
this.detachChild()
|
||||
void this.child.terminate().catch(() => undefined)
|
||||
// Persist only once CPU loads the model: a broken model must not turn the GPU off.
|
||||
this.markOnCpuReady = persist
|
||||
this.cpuOnly = true
|
||||
this.attach(this.spawn({ cpuOnly: true }))
|
||||
if (this.init) {
|
||||
this.child.postMessage(this.init)
|
||||
}
|
||||
for (const [streamId, stream] of this.streams) {
|
||||
// A canceled dictation wants no text, so its audio is not replayed.
|
||||
if (stream.pending !== 'discard') {
|
||||
for (const feed of stream.feeds) {
|
||||
this.child.postMessage(feed)
|
||||
}
|
||||
}
|
||||
if (stream.pending) {
|
||||
this.child.postMessage({ type: stream.pending, streamId })
|
||||
}
|
||||
}
|
||||
this.streams.clear()
|
||||
}
|
||||
|
||||
private trimBacklog(stream: StreamBacklog, decodedSamples: number): void {
|
||||
while (stream.feeds.length > 0) {
|
||||
const first = stream.feeds[0]
|
||||
const end = stream.start + first.samples.length
|
||||
const dropped = Math.min(first.samples.length, decodedSamples - stream.start)
|
||||
stream.seconds -= dropped / first.sampleRate
|
||||
if (end > decodedSamples) {
|
||||
stream.feeds[0] = { ...first, samples: first.samples.subarray(dropped) }
|
||||
stream.start = decodedSamples
|
||||
return
|
||||
}
|
||||
stream.feeds.shift()
|
||||
stream.start = end
|
||||
}
|
||||
}
|
||||
|
||||
/** The GPU owes progress while loading, finishing a stop, or once a full chunk waits undecoded. */
|
||||
private owesProgress(): boolean {
|
||||
if (!this.ready) {
|
||||
return this.init !== null
|
||||
}
|
||||
for (const stream of this.streams.values()) {
|
||||
if (stream.pending === 'stop' || stream.seconds > OFFLINE_DECODE_CHUNK_SECONDS) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** `progressed`: the GPU just answered, so a running timer restarts. */
|
||||
private watchForStall(progressed: boolean): void {
|
||||
if (progressed || !this.canFallBack() || !this.owesProgress()) {
|
||||
this.clearStallTimer()
|
||||
}
|
||||
if (this.stallTimer || !this.canFallBack() || !this.owesProgress()) {
|
||||
return
|
||||
}
|
||||
// Not persisted: a first-run shader compile or cold model read can be slow once and fine after.
|
||||
this.stallTimer = setTimeout(() => this.fallBack(false), GPU_STALL_TIMEOUT_MS)
|
||||
this.stallTimer.unref?.()
|
||||
}
|
||||
|
||||
private clearStallTimer(): void {
|
||||
if (this.stallTimer) {
|
||||
clearTimeout(this.stallTimer)
|
||||
this.stallTimer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function spawnSttWorkerWithCpuFallback(
|
||||
spawn: SpawnSttChild,
|
||||
gpu: SttGpuPolicy
|
||||
): SttWorkerProcess {
|
||||
return new SttCpuFallbackWorker(spawn, gpu)
|
||||
}
|
||||
@@ -2,19 +2,20 @@ import { forkProcess } from '@orca/process-host/fork-process'
|
||||
import { getSttWorkerPath } from './stt-worker-paths'
|
||||
import {
|
||||
logSttWorkerStderr,
|
||||
sttWorkerEnv,
|
||||
SttWorkerChildProcess,
|
||||
type SttWorkerProcess
|
||||
} from './stt-worker-process'
|
||||
|
||||
/** For orcad, which has no Electron utility processes. */
|
||||
export function spawnSttForkedProcess(): SttWorkerProcess {
|
||||
export function spawnSttForkedProcess(options: { cpuOnly: boolean }): SttWorkerProcess {
|
||||
const child = forkProcess({
|
||||
modulePath: getSttWorkerPath(),
|
||||
// Structured clone keeps feed audio a Float32Array.
|
||||
serialization: 'advanced',
|
||||
execArgv: [],
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
|
||||
env: { ...sttWorkerEnv(options), ELECTRON_RUN_AS_NODE: '1' }
|
||||
})
|
||||
const kill = (): void => {
|
||||
child.kill('SIGKILL')
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { getAppEnvironment } from '../../shared/app-environment'
|
||||
import { speechEngineForModelFiles, type SpeechEngine } from '../../shared/speech-model-engine'
|
||||
import {
|
||||
SPEECH_RECOGNIZER_DIR_ENV,
|
||||
speechRecognizerPackageName
|
||||
hasSpeechEnginePackage,
|
||||
SPEECH_RECOGNIZER_DIR_ENV
|
||||
} from '../../shared/speech-recognizer-package'
|
||||
import {
|
||||
currentWorkerEntryLayout,
|
||||
@@ -17,34 +17,31 @@ export function getSttWorkerPath(): string {
|
||||
return resolveWorkerThreadEntryPath(currentWorkerEntryLayout(__dirname), 'stt-worker.js')
|
||||
}
|
||||
|
||||
/** Recognizer directory, or null on hosts without one. */
|
||||
export function getSherpaModulePath(): string | null {
|
||||
const nativePackage = speechRecognizerPackageName(process.platform, process.arch)
|
||||
function speechNodeModulesDirCandidates(): string[] {
|
||||
const resourcesPath =
|
||||
'resourcesPath' in process && typeof process.resourcesPath === 'string'
|
||||
? process.resourcesPath
|
||||
: undefined
|
||||
|
||||
if (getAppEnvironment().isPackaged() && resourcesPath) {
|
||||
const resourcesNodeModule = join(resourcesPath, 'node_modules', nativePackage)
|
||||
if (existsSync(resourcesNodeModule)) {
|
||||
return resourcesNodeModule
|
||||
}
|
||||
return join(resourcesPath, 'app.asar.unpacked', 'node_modules', nativePackage)
|
||||
return [
|
||||
join(resourcesPath, 'node_modules'),
|
||||
join(resourcesPath, 'app.asar.unpacked', 'node_modules')
|
||||
]
|
||||
}
|
||||
if (getAppEnvironment().isPackaged()) {
|
||||
// orcad: only the installed app's copy, which `orca serve` names.
|
||||
const handed = process.env[SPEECH_RECOGNIZER_DIR_ENV]
|
||||
return handed && existsSync(join(handed, 'sherpa-onnx.node')) ? handed : null
|
||||
}
|
||||
|
||||
try {
|
||||
return join(require.resolve(nativePackage), '..')
|
||||
} catch {
|
||||
return null
|
||||
return handed ? [handed] : []
|
||||
}
|
||||
return require.resolve.paths('transcribe-cpp') ?? []
|
||||
}
|
||||
|
||||
export function hasLocalSpeechRecognizer(): boolean {
|
||||
return getSherpaModulePath() !== null
|
||||
/** The node_modules directory holding `engine`, or null on hosts without it. */
|
||||
export function getSpeechEngineModulesDir(engine: SpeechEngine): string | null {
|
||||
return speechNodeModulesDirCandidates().find((dir) => hasSpeechEnginePackage(dir, engine)) ?? null
|
||||
}
|
||||
|
||||
/** Whether this host ships the engine `model` runs on. */
|
||||
export function hasLocalSpeechRecognizer(model: { files?: readonly string[] }): boolean {
|
||||
return getSpeechEngineModulesDir(speechEngineForModelFiles(model.files ?? [])) !== null
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import type { MessagePortMain } from 'electron'
|
||||
import type { WorkerRequestTransport } from '../worker-threads/worker-thread-transport'
|
||||
import type { RecognizerConfigInput } from './stt-worker-model-config'
|
||||
import type { SttRecognizerInit } from './stt-recognizer'
|
||||
|
||||
/** Electron reports it as the utility process's name when it exits. */
|
||||
export const STT_UTILITY_PROCESS_NAME = 'Orca Speech'
|
||||
@@ -10,7 +10,7 @@ export const STT_WORKER_EXITED_ERROR = 'The speech engine stopped unexpectedly.
|
||||
export const STT_WORKER_HUNG_ERROR = 'The speech engine stopped responding. Try again.'
|
||||
|
||||
export type SttWorkerRequest =
|
||||
| ({ type: 'init'; sherpaModulePath: string } & RecognizerConfigInput)
|
||||
| ({ type: 'init' } & SttRecognizerInit)
|
||||
| { type: 'feed'; streamId: string; samples: Float32Array; sampleRate: number }
|
||||
| { type: 'stop'; streamId: string }
|
||||
| { type: 'discard'; streamId: string }
|
||||
@@ -73,6 +73,16 @@ export class SttWorkerChildProcess extends EventEmitter implements SttWorkerProc
|
||||
}
|
||||
}
|
||||
|
||||
/** Env for a speech child: CPU-only skips GPU backend registration, which can itself crash a driver. */
|
||||
export function sttWorkerEnv(options: { cpuOnly: boolean }): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
...(options.cpuOnly ? { TRANSCRIBE_BACKENDS: 'cpu' } : {}),
|
||||
// Implicit Vulkan layers (overlays, capture tools) crash some drivers' compute (Handy #2049).
|
||||
...(process.platform === 'win32' ? { VK_LOADER_LAYERS_DISABLE: '~implicit~' } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export function logSttWorkerStderr(stderr: NodeJS.ReadableStream | null | undefined): void {
|
||||
stderr?.on('data', (chunk: Buffer) => {
|
||||
console.error('[speech-worker]', String(chunk).trimEnd())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { SttEvent } from './stt-service'
|
||||
import type { SttRecognizerInit } from './stt-recognizer'
|
||||
import type { SttWorkerProcess } from './stt-worker-process'
|
||||
|
||||
/** Session events carry the stream they belong to. */
|
||||
@@ -84,19 +85,6 @@ export function attachSttWorkerLifecycle(args: {
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeSttWorker(
|
||||
worker: SttWorkerProcess,
|
||||
input: {
|
||||
sherpaModulePath: string
|
||||
modelDir: string
|
||||
modelType: string
|
||||
streaming: boolean
|
||||
sampleRate: number
|
||||
files: readonly string[]
|
||||
hotwordsFilePath?: string
|
||||
modelingUnit?: string
|
||||
language?: string
|
||||
}
|
||||
): void {
|
||||
export function initializeSttWorker(worker: SttWorkerProcess, input: SttRecognizerInit): void {
|
||||
worker.postMessage({ type: 'init', ...input })
|
||||
}
|
||||
|
||||
@@ -3,15 +3,17 @@ import { getSttWorkerPath } from './stt-worker-paths'
|
||||
import {
|
||||
logSttWorkerStderr,
|
||||
STT_UTILITY_PROCESS_NAME,
|
||||
sttWorkerEnv,
|
||||
SttWorkerChildProcess,
|
||||
type SttWorkerProcess
|
||||
} from './stt-worker-process'
|
||||
|
||||
/** A native crash or hang in the recognizer stays out of the app's main process. */
|
||||
export function spawnSttUtilityProcess(): SttWorkerProcess {
|
||||
export function spawnSttUtilityProcess(options: { cpuOnly: boolean }): SttWorkerProcess {
|
||||
const child = utilityProcess.fork(getSttWorkerPath(), [], {
|
||||
serviceName: STT_UTILITY_PROCESS_NAME,
|
||||
stdio: ['ignore', 'ignore', 'pipe']
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
env: sttWorkerEnv(options)
|
||||
})
|
||||
const worker = new SttWorkerChildProcess({
|
||||
send: (message) => child.postMessage(message),
|
||||
|
||||
+42
-165
@@ -1,23 +1,11 @@
|
||||
/* oxlint-disable typescript-eslint/no-explicit-any -- sherpa-onnx native addon has no type definitions */
|
||||
import type { MessagePortMain } from 'electron'
|
||||
import { speechEngineForModelFiles } from '../../shared/speech-model-engine'
|
||||
import type { SpeechAudioPortMessage } from '../../shared/speech-types'
|
||||
import { resampleToRate } from './stt-audio-resample'
|
||||
import { OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
import { buildRecognizerConfig } from './stt-worker-model-config'
|
||||
import { createStopTailPadding } from './stt-stop-tail-padding'
|
||||
import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer'
|
||||
import { createSherpaRecognizer } from './stt-sherpa-recognizer'
|
||||
import { createTranscribeCppRecognizer } from './stt-transcribe-cpp-recognizer'
|
||||
import { connectSttWorkerParentPort } from './stt-worker-parent-port'
|
||||
import type { SttWorkerRequest as WorkerMessage } from './stt-worker-process'
|
||||
|
||||
// One per dictation session; every session shares the one loaded recognizer.
|
||||
type SessionStream = {
|
||||
// Online streams live for the session; offline ones are made per decode.
|
||||
online: any
|
||||
offlineChunker: OfflineAudioChunker | null
|
||||
// Primed on the session's first feed so stop never waits on another session's stream.
|
||||
primed: boolean
|
||||
// Streaming models report the same hypothesis on most 100 ms feeds; only changes are posted.
|
||||
lastPartialText: string
|
||||
}
|
||||
import type { SttWorkerRequest } from './stt-worker-process'
|
||||
|
||||
// A desktop renderer's audio for one stream, posted straight here instead of through main.
|
||||
type AudioPortInput = {
|
||||
@@ -26,144 +14,36 @@ type AudioPortInput = {
|
||||
}
|
||||
|
||||
const parentPort = connectSttWorkerParentPort()
|
||||
// Use the platform native addon: the main sherpa-onnx WASM package cannot load host model files. Main supplies its resolved path.
|
||||
let sherpa: any = null
|
||||
let recognizer: any = null
|
||||
let isStreaming = false
|
||||
let modelSampleRate = 16000
|
||||
const streams = new Map<string, SessionStream>()
|
||||
let recognizer: SttRecognizer | null = null
|
||||
const audioPorts = new Map<string, AudioPortInput>()
|
||||
|
||||
function loadSherpa(modulePath: string | undefined): any {
|
||||
if (!modulePath) {
|
||||
throw new Error('init.sherpaModulePath is required')
|
||||
}
|
||||
return require(modulePath)
|
||||
// transcribe-cpp decodes off the event loop; one queue keeps feeds behind init and stop behind feeds.
|
||||
let queue: Promise<void> = Promise.resolve()
|
||||
function enqueue(task: () => void | Promise<void>): void {
|
||||
queue = queue.then(task)
|
||||
}
|
||||
|
||||
function handleInit(msg: Extract<WorkerMessage, { type: 'init' }>): void {
|
||||
async function handleInit(init: SttRecognizerInit): Promise<void> {
|
||||
try {
|
||||
sherpa = loadSherpa(msg.sherpaModulePath)
|
||||
isStreaming = msg.streaming
|
||||
modelSampleRate = msg.sampleRate
|
||||
const { online, config } = buildRecognizerConfig(msg)
|
||||
recognizer = online
|
||||
? sherpa.createOnlineRecognizer(config)
|
||||
: sherpa.createOfflineRecognizer(config)
|
||||
const post: SttRecognizerPost = (event) => parentPort.post(event)
|
||||
recognizer =
|
||||
speechEngineForModelFiles(init.files) === 'transcribe-cpp'
|
||||
? await createTranscribeCppRecognizer(init, post)
|
||||
: createSherpaRecognizer(init, post)
|
||||
parentPort.post({ type: 'ready' })
|
||||
} catch (err) {
|
||||
parentPort.post({ type: 'error', error: String(err) })
|
||||
}
|
||||
}
|
||||
|
||||
function openStream(streamId: string): SessionStream {
|
||||
const existing = streams.get(streamId)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const stream: SessionStream = {
|
||||
online: isStreaming ? sherpa.createOnlineStream(recognizer) : null,
|
||||
offlineChunker: isStreaming ? null : new OfflineAudioChunker(modelSampleRate),
|
||||
primed: false,
|
||||
lastPartialText: ''
|
||||
}
|
||||
streams.set(streamId, stream)
|
||||
return stream
|
||||
}
|
||||
|
||||
function decodeOfflineChunk(samples: Float32Array): string {
|
||||
const stream = sherpa.createOfflineStream(recognizer)
|
||||
sherpa.acceptWaveformOffline(stream, { sampleRate: modelSampleRate, samples })
|
||||
sherpa.decodeOfflineStream(recognizer, stream)
|
||||
const result = JSON.parse(sherpa.getOfflineStreamResultAsJson(stream))
|
||||
return result?.text?.trim() ?? ''
|
||||
}
|
||||
|
||||
function feedOnline(streamId: string, stream: SessionStream, samples: Float32Array): void {
|
||||
if (!stream.primed) {
|
||||
// New streams start with empty encoder caches; zipformer en-20M dropped most of the first second
|
||||
// (first word wrong on 71 of 73 LibriSpeech clips). A second of silence fills them first.
|
||||
sherpa.acceptWaveformOnline(stream.online, {
|
||||
sampleRate: modelSampleRate,
|
||||
samples: new Float32Array(modelSampleRate)
|
||||
})
|
||||
stream.primed = true
|
||||
}
|
||||
sherpa.acceptWaveformOnline(stream.online, { sampleRate: modelSampleRate, samples })
|
||||
while (sherpa.isOnlineStreamReady(recognizer, stream.online)) {
|
||||
sherpa.decodeOnlineStream(recognizer, stream.online)
|
||||
}
|
||||
const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online))
|
||||
const text = result?.text?.trim()
|
||||
if (text && text !== stream.lastPartialText) {
|
||||
stream.lastPartialText = text
|
||||
parentPort.post({ type: 'partial', streamId, text })
|
||||
}
|
||||
if (sherpa.isEndpoint(recognizer, stream.online)) {
|
||||
if (text) {
|
||||
parentPort.post({ type: 'final', streamId, text })
|
||||
}
|
||||
sherpa.reset(recognizer, stream.online)
|
||||
stream.lastPartialText = ''
|
||||
}
|
||||
}
|
||||
|
||||
function feedOffline(streamId: string, stream: SessionStream, samples: Float32Array): void {
|
||||
// Bound ONNX allocations below Chromium's >=2GiB crash threshold (#7925); consumers append final segments.
|
||||
const readyChunks = stream.offlineChunker?.push(new Float32Array(samples)) ?? []
|
||||
// push() already consumed these windows; keep decoding later ones after a failure.
|
||||
let firstError: unknown = null
|
||||
for (const chunk of readyChunks) {
|
||||
try {
|
||||
const text = decodeOfflineChunk(chunk)
|
||||
if (text) {
|
||||
parentPort.post({ type: 'final', streamId, text })
|
||||
}
|
||||
} catch (err) {
|
||||
firstError ??= err
|
||||
}
|
||||
}
|
||||
if (firstError) {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
|
||||
function handleFeed(msg: Extract<WorkerMessage, { type: 'feed' }>): void {
|
||||
if (!recognizer) {
|
||||
return
|
||||
}
|
||||
async function handleFeed(msg: Extract<SttWorkerRequest, { type: 'feed' }>): Promise<void> {
|
||||
try {
|
||||
const stream = openStream(msg.streamId)
|
||||
// Normalize rates before native decode: mixed rates on one recognizer abort the process.
|
||||
const samples = resampleToRate(msg.samples, msg.sampleRate || modelSampleRate, modelSampleRate)
|
||||
if (isStreaming) {
|
||||
feedOnline(msg.streamId, stream, samples)
|
||||
} else {
|
||||
feedOffline(msg.streamId, stream, samples)
|
||||
}
|
||||
await recognizer?.feed(msg.streamId, msg.samples, msg.sampleRate)
|
||||
} catch (err) {
|
||||
parentPort.post({ type: 'error', streamId: msg.streamId, error: String(err) })
|
||||
}
|
||||
}
|
||||
|
||||
function finishStream(stream: SessionStream): string {
|
||||
if (stream.online) {
|
||||
sherpa.acceptWaveformOnline(stream.online, {
|
||||
sampleRate: modelSampleRate,
|
||||
samples: createStopTailPadding(modelSampleRate)
|
||||
})
|
||||
sherpa.inputFinished(stream.online)
|
||||
while (sherpa.isOnlineStreamReady(recognizer, stream.online)) {
|
||||
sherpa.decodeOnlineStream(recognizer, stream.online)
|
||||
}
|
||||
const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online))
|
||||
return result?.text?.trim() ?? ''
|
||||
}
|
||||
// flush() leaves less than one bounded chunk.
|
||||
const remaining = stream.offlineChunker?.flush()
|
||||
return remaining && remaining.length > 0 ? decodeOfflineChunk(remaining) : ''
|
||||
}
|
||||
|
||||
function attachAudioPort(streamId: string, port: MessagePortMain | undefined): void {
|
||||
if (!port) {
|
||||
return
|
||||
@@ -181,31 +61,26 @@ function attachAudioPort(streamId: string, port: MessagePortMain | undefined): v
|
||||
port.on('message', ({ data }) => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the desktop preload holds the other end, and it sends SpeechAudioPortMessage.
|
||||
const msg = data as SpeechAudioPortMessage
|
||||
if (msg.type === 'end') {
|
||||
end()
|
||||
} else {
|
||||
handleFeed({ type: 'feed', streamId, samples: msg.samples, sampleRate: msg.sampleRate })
|
||||
}
|
||||
enqueue(() =>
|
||||
msg.type === 'end'
|
||||
? end()
|
||||
: handleFeed({ type: 'feed', streamId, samples: msg.samples, sampleRate: msg.sampleRate })
|
||||
)
|
||||
})
|
||||
port.on('close', end)
|
||||
audioPorts.set(streamId, input)
|
||||
port.start()
|
||||
}
|
||||
|
||||
function handleStop(streamId: string): void {
|
||||
async function handleStop(streamId: string): Promise<void> {
|
||||
const input = audioPorts.get(streamId)
|
||||
// Main's stop can overtake the renderer's last frames on the port; finish only after them.
|
||||
if (input) {
|
||||
input.onEnded = () => handleStop(streamId)
|
||||
input.onEnded = () => enqueue(() => handleStop(streamId))
|
||||
return
|
||||
}
|
||||
const stream = streams.get(streamId)
|
||||
streams.delete(streamId)
|
||||
try {
|
||||
const text = stream && recognizer ? finishStream(stream) : ''
|
||||
if (text) {
|
||||
parentPort.post({ type: 'final', streamId, text })
|
||||
}
|
||||
await recognizer?.finish(streamId)
|
||||
} catch (err) {
|
||||
parentPort.post({ type: 'error', streamId, error: String(err) })
|
||||
} finally {
|
||||
@@ -218,28 +93,30 @@ function handleDiscard(streamId: string): void {
|
||||
const input = audioPorts.get(streamId)
|
||||
audioPorts.delete(streamId)
|
||||
input?.port.close()
|
||||
streams.delete(streamId)
|
||||
recognizer?.discard(streamId)
|
||||
parentPort.post({ type: 'stopped', streamId })
|
||||
}
|
||||
|
||||
parentPort.onMessage((message, ports) => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the session host posts here, and it sends WorkerMessage.
|
||||
const msg = message as WorkerMessage
|
||||
function handleMessage(
|
||||
msg: SttWorkerRequest,
|
||||
ports: readonly MessagePortMain[]
|
||||
): void | Promise<void> {
|
||||
switch (msg.type) {
|
||||
case 'init':
|
||||
handleInit(msg)
|
||||
break
|
||||
return handleInit(msg)
|
||||
case 'feed':
|
||||
handleFeed(msg)
|
||||
break
|
||||
return handleFeed(msg)
|
||||
case 'stop':
|
||||
handleStop(msg.streamId)
|
||||
break
|
||||
return handleStop(msg.streamId)
|
||||
case 'discard':
|
||||
handleDiscard(msg.streamId)
|
||||
break
|
||||
return handleDiscard(msg.streamId)
|
||||
case 'attach-audio':
|
||||
attachAudioPort(msg.streamId, ports[0])
|
||||
break
|
||||
return attachAudioPort(msg.streamId, ports[0])
|
||||
}
|
||||
}
|
||||
|
||||
parentPort.onMessage((message, ports) => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the session host posts here, and it sends SttWorkerRequest.
|
||||
const msg = message as SttWorkerRequest
|
||||
enqueue(() => handleMessage(msg, ports))
|
||||
})
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export type SpeechEngine = 'sherpa' | 'transcribe-cpp'
|
||||
|
||||
/** GGUF models run on transcribe-cpp; everything else on sherpa-onnx. */
|
||||
export function speechEngineForModelFiles(files: readonly string[]): SpeechEngine {
|
||||
return files.some((file) => file.endsWith('.gguf')) ? 'transcribe-cpp' : 'sherpa'
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
/** Desktop and orca serve share the app’s platform recognizer addon; orcad slots omit the ~70 MB package. */
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import type { SpeechEngine } from './speech-model-engine'
|
||||
import transcribeCppPackages from './transcribe-cpp-packages.json'
|
||||
|
||||
/** Set by `orca serve` for orcad: the directory of the app's recognizer package. */
|
||||
/** Desktop and orca serve share the app’s speech engine packages; orcad slots omit them. */
|
||||
|
||||
/** Set by `orca serve` for orcad: the app's node_modules directory holding the speech engine packages. */
|
||||
export const SPEECH_RECOGNIZER_DIR_ENV = 'ORCA_SPEECH_RECOGNIZER_DIR'
|
||||
|
||||
export function speechRecognizerPackageName(platform: string, arch: string): string {
|
||||
@@ -8,3 +13,25 @@ export function speechRecognizerPackageName(platform: string, arch: string): str
|
||||
? 'sherpa-onnx-win-x64'
|
||||
: `sherpa-onnx-${platform}-${arch}`
|
||||
}
|
||||
|
||||
// Intel Macs stay on sherpa: transcribe-cpp's darwin-x64 build is SSE-only with no GPU. Packaging reads the same table.
|
||||
const TRANSCRIBE_CPP_PACKAGES: Record<string, string> = transcribeCppPackages
|
||||
|
||||
/** Whether `nodeModulesDir` holds a loadable copy of `engine` for this host. */
|
||||
export function hasSpeechEnginePackage(
|
||||
nodeModulesDir: string,
|
||||
engine: SpeechEngine,
|
||||
platform: string = process.platform,
|
||||
arch: string = process.arch
|
||||
): boolean {
|
||||
if (engine === 'sherpa') {
|
||||
const sherpa = speechRecognizerPackageName(platform, arch)
|
||||
return existsSync(join(nodeModulesDir, sherpa, 'sherpa-onnx.node'))
|
||||
}
|
||||
const native = TRANSCRIBE_CPP_PACKAGES[`${platform}-${arch}`]
|
||||
return (
|
||||
native !== undefined &&
|
||||
existsSync(join(nodeModulesDir, 'transcribe-cpp', 'package.json')) &&
|
||||
existsSync(join(nodeModulesDir, ...native.split('/'), 'contract.json'))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -75,6 +75,8 @@ export type UserModelConfig = {
|
||||
|
||||
export type DictationMode = 'toggle' | 'hold'
|
||||
|
||||
export type SpeechGpuMode = 'auto' | 'off'
|
||||
|
||||
export type VoiceSettings = {
|
||||
enabled: boolean
|
||||
sttModel: string
|
||||
@@ -93,4 +95,6 @@ export type VoiceSettings = {
|
||||
microphoneDeviceLabel: string | null
|
||||
/** Minutes an idle on-device model stays loaded; 0 unloads after each dictation, null never unloads. */
|
||||
unloadModelAfterMinutes: number | null
|
||||
/** 'off' keeps on-device recognition on the CPU, for machines whose GPU driver hard-crashes. Absent = 'auto'. */
|
||||
speechGpu?: SpeechGpuMode
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"darwin-arm64": "@transcribe-cpp/darwin-arm64-metal",
|
||||
"linux-x64": "@transcribe-cpp/linux-x64-cpu-vulkan",
|
||||
"linux-arm64": "@transcribe-cpp/linux-arm64-cpu-vulkan",
|
||||
"win32-x64": "@transcribe-cpp/win32-x64-cpu-vulkan"
|
||||
}
|
||||
Reference in New Issue
Block a user