@mentra/bluetooth-sdk 3.4.0-dev.998 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +16 -7
- package/README.md +40 -13
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +114 -122
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
- package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +274 -56
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +3 -3
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +103 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +42 -8
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +1 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +2 -2
- package/build/generated/changelogCatalog.js +2 -2
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -1
- package/build/index.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
- package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.js +0 -3
- package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
- package/build/ota-transport/index.d.ts +3 -3
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +4 -4
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useGlassesConnection.d.ts +1 -1
- package/build/react/useGlassesConnection.d.ts.map +1 -1
- package/build/react/useGlassesConnection.js +3 -3
- package/build/react/useGlassesConnection.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -1
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +1 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +73 -22
- package/ios/LocalIPv4.swift +0 -61
- package/ios/MentraBluetoothSDK.podspec +7 -1
- package/ios/MentraOtaServerModule.swift +0 -16
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +4 -4
- package/ios/Source/Bridge.swift +14 -0
- package/ios/Source/DeviceManager.swift +43 -22
- package/ios/Source/GeneratedChangelogCatalog.swift +2 -2
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- package/ios/Source/MentraBluetoothSDK.swift +35 -16
- package/ios/Source/OtaManifest.swift +1 -17
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +14 -1
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
- package/ios/Source/sgcs/MentraLive.swift +195 -66
- package/ios/Source/sgcs/Nimo.swift +249 -276
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
- package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
- package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
- package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
- package/ios/Source/sgcs/SGCManager.swift +6 -0
- package/ios/Source/streaming/StreamModels.swift +15 -6
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/BesCrashReportTests.swift +142 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
- package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
- package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
- package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/StreamRequestTests.swift +18 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +9 -11
- package/plugin/build/withKotlinVersion.d.ts +2 -0
- package/plugin/build/withKotlinVersion.js +46 -0
- package/src/BluetoothSdk.types.ts +107 -5
- package/src/_private/BluetoothSdkModule.ts +45 -8
- package/src/_private/MentraLocalNetworkModule.ts +5 -1
- package/src/generated/changelogCatalog.ts +2 -2
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/index.ts +13 -1
- package/src/ota-server/MentraOtaServerModule.ts +0 -2
- package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
- package/src/ota-transport/index.ts +4 -5
- package/src/react/useGlassesConnection.ts +4 -4
- package/src/react/useMentraBluetooth.ts +2 -2
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
- package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
- package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
- package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
- package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
- package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
- package/ios/Tests/NimoResourceSessionTests.swift +0 -476
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -3,46 +3,28 @@ import Foundation
|
|
|
3
3
|
class STTTools {
|
|
4
4
|
// MARK: - SherpaOnnxTranscriber / STT Model Management
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
/// Send a transcript the loaded model produced. `text` is already formatted for that model,
|
|
7
|
+
/// and `language` is the language it was loaded for.
|
|
8
|
+
static func sendTranscription(_ text: String, isFinal: Bool, language: String) {
|
|
9
|
+
guard !text.isEmpty else { return }
|
|
10
|
+
if isFinal {
|
|
11
|
+
Bridge.log("Mentra: Sending final transcription: \(text), \(language)")
|
|
12
|
+
}
|
|
13
|
+
let now = Int(Date().timeIntervalSince1970 * 1000)
|
|
11
14
|
let transcription: [String: Any] = [
|
|
12
15
|
"type": "local_transcription",
|
|
13
|
-
"text":
|
|
14
|
-
"isFinal":
|
|
15
|
-
"startTime":
|
|
16
|
-
"endTime":
|
|
16
|
+
"text": text,
|
|
17
|
+
"isFinal": isFinal,
|
|
18
|
+
"startTime": now - (isFinal ? 2000 : 1000),
|
|
19
|
+
"endTime": now,
|
|
17
20
|
"speakerId": 0,
|
|
18
|
-
"transcribeLanguage":
|
|
21
|
+
"transcribeLanguage": language,
|
|
19
22
|
"provider": "sherpa-onnx",
|
|
20
23
|
]
|
|
21
24
|
|
|
22
25
|
Bridge.sendLocalTranscription(transcription: transcription)
|
|
23
26
|
}
|
|
24
27
|
|
|
25
|
-
static func didReceiveFinalTranscription(_ text: String) {
|
|
26
|
-
// Send final result to server with proper formatting
|
|
27
|
-
let transcriptionLanguage =
|
|
28
|
-
UserDefaults.standard.string(forKey: "STTModelLanguageCode") ?? "en-US"
|
|
29
|
-
Bridge.log("Mentra: Sending final transcription: \(text), \(transcriptionLanguage)")
|
|
30
|
-
if !text.isEmpty {
|
|
31
|
-
let transcription: [String: Any] = [
|
|
32
|
-
"type": "local_transcription",
|
|
33
|
-
"text": transcriptionLanguage == "en-US" ? text.lowercased() : text,
|
|
34
|
-
"isFinal": true,
|
|
35
|
-
"startTime": Int(Date().timeIntervalSince1970 * 1000) - 2000, // 2 seconds ago
|
|
36
|
-
"endTime": Int(Date().timeIntervalSince1970 * 1000),
|
|
37
|
-
"speakerId": 0,
|
|
38
|
-
"transcribeLanguage": transcriptionLanguage,
|
|
39
|
-
"provider": "sherpa-onnx",
|
|
40
|
-
]
|
|
41
|
-
|
|
42
|
-
Bridge.sendLocalTranscription(transcription: transcription)
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
28
|
static func setSttModelDetails(_ path: String, _ languageCode: String) {
|
|
47
29
|
UserDefaults.standard.set(path, forKey: "STTModelPath")
|
|
48
30
|
UserDefaults.standard.set(languageCode, forKey: "STTModelLanguageCode")
|
|
@@ -4,23 +4,38 @@ import Foundation
|
|
|
4
4
|
* SherpaOnnxTranscriber handles real-time audio transcription using Sherpa-ONNX.
|
|
5
5
|
*
|
|
6
6
|
* It works fully offline and processes PCM audio in real-time to provide partial and final ASR results.
|
|
7
|
-
*
|
|
7
|
+
* The recognizer exists only while on-device transcription is in demand: the demand-driven worker
|
|
8
|
+
* loads the model Speech settings selected when demand starts and releases it when demand ends.
|
|
8
9
|
*/
|
|
9
10
|
class SherpaOnnxTranscriber {
|
|
10
11
|
private static let TAG = "SherpaOnnxTranscriber"
|
|
11
12
|
|
|
12
13
|
private static let SAMPLE_RATE = 16000 // Sherpa-ONNX model's required sample rate
|
|
14
|
+
/// Bounded wait for `finishUtterance`, matching Android.
|
|
15
|
+
private static let FINISH_TIMEOUT_SECONDS: TimeInterval = 3
|
|
16
|
+
|
|
13
17
|
private final class Session {
|
|
14
18
|
let recognizer: SherpaOnnxRecognizer
|
|
19
|
+
let modelPath: String
|
|
20
|
+
let language: String
|
|
21
|
+
let traits: SttModelTraits
|
|
15
22
|
var lastPartialResult = ""
|
|
16
23
|
|
|
17
|
-
init(_ recognizer: SherpaOnnxRecognizer) {
|
|
24
|
+
init(_ recognizer: SherpaOnnxRecognizer, modelPath: String, language: String, traits: SttModelTraits) {
|
|
18
25
|
self.recognizer = recognizer
|
|
26
|
+
self.modelPath = modelPath
|
|
27
|
+
self.language = language
|
|
28
|
+
self.traits = traits
|
|
19
29
|
}
|
|
20
30
|
}
|
|
21
31
|
|
|
32
|
+
// Path of the most recent successful load. Combined with the worker's `initialized` flag it
|
|
33
|
+
// answers `isModelLoaded` without waiting on the worker queue, which may be mid-load.
|
|
34
|
+
private let loadedLock = NSLock()
|
|
35
|
+
private var loadedModelPath: String?
|
|
36
|
+
|
|
22
37
|
private lazy var worker = DemandDrivenAudioWorker<Session>(
|
|
23
|
-
makeProcessor: {
|
|
38
|
+
makeProcessor: { [weak self] in self?.makeSession() },
|
|
24
39
|
process: { [weak self] session, data, generation in
|
|
25
40
|
self?.process(session, data: data, generation: generation)
|
|
26
41
|
}
|
|
@@ -35,28 +50,24 @@ class SherpaOnnxTranscriber {
|
|
|
35
50
|
worker.setActive(active)
|
|
36
51
|
}
|
|
37
52
|
|
|
38
|
-
///
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
53
|
+
/// The application container changes between development builds, so a stored absolute path
|
|
54
|
+
/// is re-rooted under the current Documents directory.
|
|
55
|
+
private static func resolveModelPath(_ storedPath: String) -> String {
|
|
56
|
+
guard let range = storedPath.range(of: "/Documents/"),
|
|
57
|
+
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
|
|
58
|
+
else {
|
|
59
|
+
return storedPath
|
|
42
60
|
}
|
|
61
|
+
let relativePath = String(storedPath[range.upperBound...]) // e.g. "stt_models/..."
|
|
62
|
+
return documentsURL.appendingPathComponent(relativePath).path
|
|
63
|
+
}
|
|
43
64
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
// NOTE: Doing this because the application id changes between the development builds and files can't be found.
|
|
49
|
-
if let range = storedPath.range(of: "/Documents/") {
|
|
50
|
-
let relativePath = String(storedPath[range.upperBound...]) // e.g. "stt_models/..."
|
|
51
|
-
let fixedPath = documentsURL.appendingPathComponent(relativePath).path
|
|
52
|
-
|
|
53
|
-
Bridge.log("Reconstructed STTModelPath: \(fixedPath)")
|
|
54
|
-
return fixedPath
|
|
65
|
+
/// Model selected in Speech settings, if any.
|
|
66
|
+
private static var selectedModelPath: String? {
|
|
67
|
+
guard let storedPath = UserDefaults.standard.string(forKey: "STTModelPath"), !storedPath.isEmpty else {
|
|
68
|
+
return nil
|
|
55
69
|
}
|
|
56
|
-
|
|
57
|
-
// If nothing matched, just return as-is
|
|
58
|
-
Bridge.log("STTModelPath (raw): \(storedPath)")
|
|
59
|
-
return storedPath
|
|
70
|
+
return resolveModelPath(storedPath)
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
private static func firstExistingFile(in directory: String, candidates: [String]) -> String? {
|
|
@@ -71,152 +82,195 @@ class SherpaOnnxTranscriber {
|
|
|
71
82
|
}
|
|
72
83
|
|
|
73
84
|
/// Runs exclusively on the worker queue, never on the main/audio delivery thread.
|
|
74
|
-
private static func makeRecognizer() -> SherpaOnnxRecognizer? {
|
|
75
|
-
var recognizer: SherpaOnnxRecognizer?
|
|
85
|
+
private static func makeRecognizer(modelPath customPath: String) -> (SherpaOnnxRecognizer, SttModelTraits)? {
|
|
76
86
|
do {
|
|
77
|
-
var tokensPath: String
|
|
78
|
-
var modelType = "unknown"
|
|
79
87
|
let fileManager = FileManager.default
|
|
88
|
+
// Detect model type based on available files
|
|
89
|
+
let ctcModelPath = Self.firstExistingFile(
|
|
90
|
+
in: customPath,
|
|
91
|
+
candidates: ["model.int8.onnx", "model.onnx"]
|
|
92
|
+
)
|
|
93
|
+
let transducerEncoderPath = Self.firstExistingFile(
|
|
94
|
+
in: customPath,
|
|
95
|
+
candidates: ["encoder.int8.onnx", "encoder.onnx"]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
let tokensPath = (customPath as NSString).appendingPathComponent("tokens.txt")
|
|
99
|
+
|
|
100
|
+
// Verify tokens file exists
|
|
101
|
+
guard fileManager.fileExists(atPath: tokensPath) else {
|
|
102
|
+
throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
|
|
103
|
+
NSLocalizedDescriptionKey: "tokens.txt not found at path: \(customPath)",
|
|
104
|
+
])
|
|
105
|
+
}
|
|
106
|
+
let tokens = (try? String(contentsOfFile: tokensPath, encoding: .utf8)) ?? ""
|
|
80
107
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
108
|
+
let traits: SttModelTraits
|
|
109
|
+
var modelConfig: SherpaOnnxOnlineModelConfig
|
|
110
|
+
if let ctcModelPath {
|
|
111
|
+
traits = SttModelTraits(kind: .ctc, tokensFileContents: tokens)
|
|
112
|
+
Bridge.log("Detected CTC model at \(customPath)")
|
|
113
|
+
|
|
114
|
+
let nemoCtc = sherpaOnnxOnlineNemoCtcModelConfig(
|
|
115
|
+
model: ctcModelPath
|
|
116
|
+
)
|
|
117
|
+
modelConfig = sherpaOnnxOnlineModelConfig(
|
|
118
|
+
tokens: tokensPath,
|
|
119
|
+
numThreads: traits.numThreads,
|
|
120
|
+
nemoCtc: nemoCtc
|
|
121
|
+
)
|
|
122
|
+
} else if let transducerEncoderPath {
|
|
123
|
+
traits = SttModelTraits(kind: .transducer, tokensFileContents: tokens)
|
|
124
|
+
Bridge.log("Detected transducer model at \(customPath)")
|
|
125
|
+
|
|
126
|
+
let decoderPath = Self.firstExistingFile(
|
|
85
127
|
in: customPath,
|
|
86
|
-
candidates: ["
|
|
128
|
+
candidates: ["decoder.int8.onnx", "decoder.onnx"]
|
|
87
129
|
)
|
|
88
|
-
let
|
|
130
|
+
let joinerPath = Self.firstExistingFile(
|
|
89
131
|
in: customPath,
|
|
90
|
-
candidates: ["
|
|
132
|
+
candidates: ["joiner.int8.onnx", "joiner.onnx"]
|
|
91
133
|
)
|
|
92
134
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
135
|
+
// Verify all transducer files exist
|
|
136
|
+
guard let decoderPath,
|
|
137
|
+
let joinerPath
|
|
138
|
+
else {
|
|
97
139
|
throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
|
|
98
|
-
NSLocalizedDescriptionKey: "
|
|
140
|
+
NSLocalizedDescriptionKey: "Transducer model files incomplete at path: \(customPath)",
|
|
99
141
|
])
|
|
100
142
|
}
|
|
101
143
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
// Create model config with CTC
|
|
113
|
-
var modelConfig = sherpaOnnxOnlineModelConfig(
|
|
114
|
-
tokens: tokensPath,
|
|
115
|
-
numThreads: 1,
|
|
116
|
-
nemoCtc: nemoCtc
|
|
117
|
-
)
|
|
118
|
-
|
|
119
|
-
// Configure recognizer
|
|
120
|
-
var featureConfig = sherpaOnnxFeatureConfig()
|
|
121
|
-
|
|
122
|
-
var config = sherpaOnnxOnlineRecognizerConfig(
|
|
123
|
-
featConfig: featureConfig,
|
|
124
|
-
modelConfig: modelConfig,
|
|
125
|
-
enableEndpoint: true,
|
|
126
|
-
rule1MinTrailingSilence: 1.2,
|
|
127
|
-
rule2MinTrailingSilence: 0.8,
|
|
128
|
-
rule3MinUtteranceLength: 10.0
|
|
129
|
-
)
|
|
130
|
-
|
|
131
|
-
// Create recognizer with the wrapper
|
|
132
|
-
recognizer = SherpaOnnxRecognizer(config: &config)
|
|
133
|
-
|
|
134
|
-
} else if let transducerEncoderPath {
|
|
135
|
-
// Transducer model detected
|
|
136
|
-
modelType = "transducer"
|
|
137
|
-
Bridge.log("Detected transducer model at \(customPath)")
|
|
138
|
-
|
|
139
|
-
let decoderPath = Self.firstExistingFile(
|
|
140
|
-
in: customPath,
|
|
141
|
-
candidates: ["decoder.int8.onnx", "decoder.onnx"]
|
|
142
|
-
)
|
|
143
|
-
let joinerPath = Self.firstExistingFile(
|
|
144
|
-
in: customPath,
|
|
145
|
-
candidates: ["joiner.int8.onnx", "joiner.onnx"]
|
|
146
|
-
)
|
|
147
|
-
|
|
148
|
-
// Verify all transducer files exist
|
|
149
|
-
guard let decoderPath,
|
|
150
|
-
let joinerPath
|
|
151
|
-
else {
|
|
152
|
-
throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
|
|
153
|
-
NSLocalizedDescriptionKey: "Transducer model files incomplete at path: \(customPath)",
|
|
154
|
-
])
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Create Sherpa-ONNX transducer model config
|
|
158
|
-
var transducer = sherpaOnnxOnlineTransducerModelConfig(
|
|
159
|
-
encoder: transducerEncoderPath,
|
|
160
|
-
decoder: decoderPath,
|
|
161
|
-
joiner: joinerPath
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
// Create model config
|
|
165
|
-
var modelConfig = sherpaOnnxOnlineModelConfig(
|
|
166
|
-
tokens: tokensPath,
|
|
167
|
-
transducer: transducer,
|
|
168
|
-
numThreads: 1
|
|
169
|
-
)
|
|
170
|
-
|
|
171
|
-
// Configure recognizer
|
|
172
|
-
var featureConfig = sherpaOnnxFeatureConfig()
|
|
173
|
-
|
|
174
|
-
var config = sherpaOnnxOnlineRecognizerConfig(
|
|
175
|
-
featConfig: featureConfig,
|
|
176
|
-
modelConfig: modelConfig,
|
|
177
|
-
enableEndpoint: true,
|
|
178
|
-
rule1MinTrailingSilence: 1.2,
|
|
179
|
-
rule2MinTrailingSilence: 0.8,
|
|
180
|
-
rule3MinUtteranceLength: 10.0
|
|
181
|
-
)
|
|
182
|
-
|
|
183
|
-
// Create recognizer with the wrapper
|
|
184
|
-
recognizer = SherpaOnnxRecognizer(config: &config)
|
|
185
|
-
|
|
186
|
-
} else {
|
|
187
|
-
throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
|
|
188
|
-
NSLocalizedDescriptionKey: "No valid model files found at path: \(customPath)",
|
|
189
|
-
])
|
|
190
|
-
}
|
|
144
|
+
let transducer = sherpaOnnxOnlineTransducerModelConfig(
|
|
145
|
+
encoder: transducerEncoderPath,
|
|
146
|
+
decoder: decoderPath,
|
|
147
|
+
joiner: joinerPath
|
|
148
|
+
)
|
|
149
|
+
modelConfig = sherpaOnnxOnlineModelConfig(
|
|
150
|
+
tokens: tokensPath,
|
|
151
|
+
transducer: transducer,
|
|
152
|
+
numThreads: traits.numThreads
|
|
153
|
+
)
|
|
191
154
|
} else {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
return nil
|
|
155
|
+
throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
|
|
156
|
+
NSLocalizedDescriptionKey: "No valid model files found at path: \(customPath)",
|
|
157
|
+
])
|
|
196
158
|
}
|
|
197
159
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
160
|
+
let featureConfig = sherpaOnnxFeatureConfig()
|
|
161
|
+
var config = sherpaOnnxOnlineRecognizerConfig(
|
|
162
|
+
featConfig: featureConfig,
|
|
163
|
+
modelConfig: modelConfig,
|
|
164
|
+
enableEndpoint: true,
|
|
165
|
+
rule1MinTrailingSilence: 1.2,
|
|
166
|
+
rule2MinTrailingSilence: 0.8,
|
|
167
|
+
rule3MinUtteranceLength: 10.0
|
|
168
|
+
)
|
|
169
|
+
let recognizer = SherpaOnnxRecognizer(config: &config)
|
|
170
|
+
|
|
171
|
+
Bridge.log(
|
|
172
|
+
"Sherpa-ONNX ASR initialized with \(traits.kind.rawValue) model, threads=\(traits.numThreads), " +
|
|
173
|
+
"finalizeEarly=\(traits.canFinalizeEarly), lowercase=\(traits.uppercaseOnlyVocabulary)"
|
|
174
|
+
)
|
|
175
|
+
return (recognizer, traits)
|
|
205
176
|
} catch {
|
|
206
177
|
Bridge.log("Failed to initialize Sherpa-ONNX: \(error.localizedDescription)")
|
|
207
178
|
return nil
|
|
208
179
|
}
|
|
209
180
|
}
|
|
210
181
|
|
|
211
|
-
|
|
182
|
+
/// Worker queue only. Loads the model Speech settings selects right now.
|
|
183
|
+
private func makeSession() -> Session? {
|
|
184
|
+
setLoadedModelPath(nil)
|
|
185
|
+
guard let path = Self.selectedModelPath else {
|
|
186
|
+
Bridge.log("No Sherpa ONNX model available. Transcription will be disabled.")
|
|
187
|
+
Bridge.log("Please download a model using the model downloader in settings.")
|
|
188
|
+
return nil
|
|
189
|
+
}
|
|
190
|
+
Bridge.log("Loading STT model: \(path)")
|
|
191
|
+
let language = UserDefaults.standard.string(forKey: "STTModelLanguageCode") ?? "en-US"
|
|
192
|
+
guard let loaded = Self.makeRecognizer(modelPath: path) else { return nil }
|
|
193
|
+
setLoadedModelPath(path)
|
|
194
|
+
return Session(loaded.0, modelPath: path, language: language, traits: loaded.1)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private func setLoadedModelPath(_ path: String?) {
|
|
198
|
+
loadedLock.lock()
|
|
199
|
+
loadedModelPath = path
|
|
200
|
+
loadedLock.unlock()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// Whether on-device demand currently has `path` loaded. Never waits for a load.
|
|
204
|
+
func isModelLoaded(_ path: String) -> Bool {
|
|
205
|
+
guard worker.snapshot().initialized else { return false }
|
|
206
|
+
loadedLock.lock()
|
|
207
|
+
defer { loadedLock.unlock() }
|
|
208
|
+
return loadedModelPath == Self.resolveModelPath(path)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/// Reload the selected model when on-device transcription is in demand. Returns false only
|
|
212
|
+
/// when the reload failed; true once it loaded or when there is no demand.
|
|
213
|
+
func restart() async -> Bool {
|
|
214
|
+
let state = await worker.restartAndAwaitLoad()
|
|
215
|
+
return state != .failed
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* End the active recognizer's current utterance now, after all audio queued before the call.
|
|
220
|
+
* Returns the final text once its `local_transcription` event has been sent ("" if nothing was
|
|
221
|
+
* pending), or nil when there is no active streaming model, the model can't finalize early, or
|
|
222
|
+
* the bounded wait expires.
|
|
223
|
+
*/
|
|
224
|
+
func finishUtterance() async -> String? {
|
|
225
|
+
await withBoundedWait(timeout: Self.FINISH_TIMEOUT_SECONDS, timeoutValue: nil) { resolver in
|
|
226
|
+
Task {
|
|
227
|
+
let started = await self.worker.withCurrentProcessor { session, generation -> Bool in
|
|
228
|
+
// A late run after the caller gave up must not cut the utterance.
|
|
229
|
+
guard !resolver.isSettled, session.traits.canFinalizeEarly else { return false }
|
|
230
|
+
let text = self.flush(session)
|
|
231
|
+
DispatchQueue.main.async {
|
|
232
|
+
guard self.worker.isCurrent(generation) else {
|
|
233
|
+
resolver.resolve(nil)
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
if !text.isEmpty {
|
|
237
|
+
STTTools.sendTranscription(text, isFinal: true, language: session.language)
|
|
238
|
+
}
|
|
239
|
+
resolver.resolve(text)
|
|
240
|
+
}
|
|
241
|
+
return true
|
|
242
|
+
}
|
|
243
|
+
if started != true { resolver.resolve(nil) }
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/// Worker queue only. Decodes everything the stream holds and replaces the ended stream.
|
|
249
|
+
private func flush(_ session: Session) -> String {
|
|
250
|
+
let startedAt = Date()
|
|
251
|
+
let recognizer = session.recognizer
|
|
252
|
+
// Sherpa's streaming file decoder uses 660 ms of padding before inputFinished.
|
|
253
|
+
// This is synthetic context, decoded immediately; it is not a wall-clock wait.
|
|
254
|
+
recognizer.acceptWaveform(samples: [Float](repeating: 0, count: Self.SAMPLE_RATE * 66 / 100), sampleRate: Self.SAMPLE_RATE)
|
|
255
|
+
recognizer.inputFinished()
|
|
256
|
+
while recognizer.isReady() {
|
|
257
|
+
recognizer.decode()
|
|
258
|
+
}
|
|
259
|
+
let text = session.traits.format(recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines))
|
|
260
|
+
// An ended stream cannot accept new samples. Keep the model and replace only its stream.
|
|
261
|
+
if !recognizer.recreateStream() {
|
|
262
|
+
recognizer.reset()
|
|
263
|
+
}
|
|
264
|
+
session.lastPartialResult = ""
|
|
265
|
+
Bridge.log("STT_FINISH elapsedMs=\(Int(Date().timeIntervalSince(startedAt) * 1000)) characters=\(text.count)")
|
|
266
|
+
return text
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private func handleTranscriptionResult(text: String, isFinal: Bool, language: String, generation: UInt64) {
|
|
212
270
|
DispatchQueue.main.async { [weak self] in
|
|
213
271
|
// A decode or main-queue delivery may finish after stop/model replacement.
|
|
214
272
|
guard let self, self.worker.isCurrent(generation) else { return }
|
|
215
|
-
|
|
216
|
-
STTTools.didReceiveFinalTranscription(text)
|
|
217
|
-
} else {
|
|
218
|
-
STTTools.didReceivePartialTranscription(text)
|
|
219
|
-
}
|
|
273
|
+
STTTools.sendTranscription(text, isFinal: isFinal, language: language)
|
|
220
274
|
}
|
|
221
275
|
}
|
|
222
276
|
|
|
@@ -233,15 +287,15 @@ class SherpaOnnxTranscriber {
|
|
|
233
287
|
recognizer.decode()
|
|
234
288
|
}
|
|
235
289
|
guard worker.isCurrent(generation) else { return }
|
|
236
|
-
let text = recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
290
|
+
let text = session.traits.format(recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines))
|
|
237
291
|
if recognizer.isEndpoint() {
|
|
238
292
|
if !text.isEmpty {
|
|
239
|
-
handleTranscriptionResult(text: text, isFinal: true, generation: generation)
|
|
293
|
+
handleTranscriptionResult(text: text, isFinal: true, language: session.language, generation: generation)
|
|
240
294
|
}
|
|
241
295
|
recognizer.reset()
|
|
242
296
|
session.lastPartialResult = ""
|
|
243
297
|
} else if !text.isEmpty, text != session.lastPartialResult {
|
|
244
|
-
handleTranscriptionResult(text: text, isFinal: false, generation: generation)
|
|
298
|
+
handleTranscriptionResult(text: text, isFinal: false, language: session.language, generation: generation)
|
|
245
299
|
session.lastPartialResult = text
|
|
246
300
|
}
|
|
247
301
|
}
|
|
@@ -254,17 +308,9 @@ class SherpaOnnxTranscriber {
|
|
|
254
308
|
var samples = [Float](repeating: 0, count: count)
|
|
255
309
|
|
|
256
310
|
pcmData.withUnsafeBytes { (bufferPointer: UnsafeRawBufferPointer) in
|
|
257
|
-
|
|
258
|
-
let
|
|
259
|
-
|
|
260
|
-
for i in 0 ..< count {
|
|
261
|
-
// Convert from little-endian if needed
|
|
262
|
-
var sample = int16Pointer[i]
|
|
263
|
-
if CFByteOrderGetCurrent() == CFByteOrder(CFByteOrderBigEndian.rawValue) {
|
|
264
|
-
sample = Int16(littleEndian: sample)
|
|
265
|
-
}
|
|
266
|
-
samples[i] = Float(sample) / 32768.0
|
|
267
|
-
}
|
|
311
|
+
for i in 0 ..< count {
|
|
312
|
+
let bits = UInt16(bufferPointer[i * 2]) | (UInt16(bufferPointer[i * 2 + 1]) << 8)
|
|
313
|
+
samples[i] = Float(Int16(bitPattern: bits)) / 32768.0
|
|
268
314
|
}
|
|
269
315
|
}
|
|
270
316
|
|
|
@@ -274,8 +320,4 @@ class SherpaOnnxTranscriber {
|
|
|
274
320
|
func shutdown() {
|
|
275
321
|
worker.setActive(false)
|
|
276
322
|
}
|
|
277
|
-
|
|
278
|
-
func restart() {
|
|
279
|
-
worker.restart()
|
|
280
|
-
}
|
|
281
323
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Silero voice activity detection through sherpa-onnx, one 512-sample frame at a time.
|
|
4
|
+
final class SileroSpeechActivityClassifier: SpeechActivityClassifier {
|
|
5
|
+
/// Resource bundle declared in MentraBluetoothSDK.podspec.
|
|
6
|
+
private static let bundleName = "MentraSileroVad"
|
|
7
|
+
/// Long enough that real speech is never split. sherpa-onnx raises its threshold past this
|
|
8
|
+
/// to force a split, which bounds the speech it buffers during continuous noise.
|
|
9
|
+
private static let maxSpeechSeconds: Float = 30
|
|
10
|
+
private static let minSpeechSeconds: Float = 0.25
|
|
11
|
+
private static let threshold: Float = 0.5
|
|
12
|
+
|
|
13
|
+
private let vad: SherpaOnnxVoiceActivityDetectorWrapper
|
|
14
|
+
|
|
15
|
+
init?(modelPath: String, minSilenceMs: Int) {
|
|
16
|
+
guard FileManager.default.fileExists(atPath: modelPath) else {
|
|
17
|
+
Bridge.log("SPEECH_ACTIVITY: Silero model missing at \(modelPath)")
|
|
18
|
+
return nil
|
|
19
|
+
}
|
|
20
|
+
let silero = sherpaOnnxSileroVadModelConfig(
|
|
21
|
+
model: modelPath,
|
|
22
|
+
threshold: Self.threshold,
|
|
23
|
+
minSilenceDuration: Float(minSilenceMs) / 1000,
|
|
24
|
+
minSpeechDuration: Self.minSpeechSeconds,
|
|
25
|
+
windowSize: SpeechActivityTracker.frameSamples,
|
|
26
|
+
maxSpeechDuration: Self.maxSpeechSeconds
|
|
27
|
+
)
|
|
28
|
+
var config = sherpaOnnxVadModelConfig(
|
|
29
|
+
sileroVad: silero,
|
|
30
|
+
sampleRate: Int32(SpeechActivityTracker.sampleRate),
|
|
31
|
+
numThreads: 1
|
|
32
|
+
)
|
|
33
|
+
guard let vad = SherpaOnnxVoiceActivityDetectorWrapper(
|
|
34
|
+
config: &config,
|
|
35
|
+
buffer_size_in_seconds: Self.maxSpeechSeconds + 2
|
|
36
|
+
) else {
|
|
37
|
+
Bridge.log("SPEECH_ACTIVITY: sherpa-onnx rejected the Silero model")
|
|
38
|
+
return nil
|
|
39
|
+
}
|
|
40
|
+
self.vad = vad
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
func isSpeech(afterAccepting frame: [Float]) -> Bool {
|
|
44
|
+
vad.acceptWaveform(samples: frame)
|
|
45
|
+
// Only the live state matters; drop finished segments so they don't accumulate.
|
|
46
|
+
while !vad.isEmpty() {
|
|
47
|
+
vad.pop()
|
|
48
|
+
}
|
|
49
|
+
return vad.isSpeechDetected()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static var bundledModelPath: String? {
|
|
53
|
+
let candidates = [Bundle(for: SileroSpeechActivityClassifier.self), Bundle.main]
|
|
54
|
+
for bundle in candidates {
|
|
55
|
+
if let url = bundle.url(forResource: bundleName, withExtension: "bundle"),
|
|
56
|
+
let resources = Bundle(url: url),
|
|
57
|
+
let path = resources.path(forResource: "silero_vad", ofType: "onnx")
|
|
58
|
+
{
|
|
59
|
+
return path
|
|
60
|
+
}
|
|
61
|
+
if let path = bundle.path(forResource: "silero_vad", ofType: "onnx") {
|
|
62
|
+
return path
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return nil
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
extension SpeechActivityMonitor {
|
|
70
|
+
/// Phone-side speech activity on the microphone PCM the wake word and STT also see.
|
|
71
|
+
static let shared = SpeechActivityMonitor(
|
|
72
|
+
makeClassifier: { minSilenceMs in
|
|
73
|
+
guard let path = SileroSpeechActivityClassifier.bundledModelPath else {
|
|
74
|
+
Bridge.log("SPEECH_ACTIVITY: silero_vad.onnx is not bundled")
|
|
75
|
+
return nil
|
|
76
|
+
}
|
|
77
|
+
return SileroSpeechActivityClassifier(modelPath: path, minSilenceMs: minSilenceMs)
|
|
78
|
+
},
|
|
79
|
+
emit: { event in
|
|
80
|
+
Bridge.sendTypedMessage("speech_activity", body: [
|
|
81
|
+
"speaking": event.speaking,
|
|
82
|
+
"silentForMs": event.silentForMs,
|
|
83
|
+
"timestamp": event.timestamp,
|
|
84
|
+
])
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
}
|