@mentra/bluetooth-sdk 3.3.0 → 3.4.0-beta.1241
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 +61 -0
- package/README.md +80 -11
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +85 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +154 -110
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
- 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/DeviceManagerOwnerLossTest.kt +146 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -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/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- 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 +201 -1
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +43 -5
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +2 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +3 -0
- package/build/generated/changelogCatalog.d.ts.map +1 -1
- package/build/generated/changelogCatalog.js +4 -0
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +6 -6
- 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 +9 -0
- package/build/index.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +76 -12
- package/ios/MentraBluetoothSDK.podspec +4 -0
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +2 -2
- package/ios/Source/Bridge.swift +11 -3
- package/ios/Source/DeviceManager.swift +131 -18
- package/ios/Source/DeviceStore.swift +27 -0
- package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +40 -5
- 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/errors/BluetoothSdkError.swift +5 -1
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +9 -6
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
- package/ios/Source/sgcs/MentraLive.swift +1270 -189
- package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
- package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
- package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
- package/ios/Source/sgcs/Nimo.swift +10 -3
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
- package/ios/Source/sgcs/SGCManager.swift +13 -0
- package/ios/Source/sgcs/Simulated.swift +2 -0
- package/ios/Source/status/DeviceStatus.swift +35 -0
- 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/types/DeviceModels.swift +8 -1
- package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
- 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/BluetoothAudioRouteTests.swift +82 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
- package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
- package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
- package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
- package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
- package/package.json +3 -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 +201 -1
- package/src/_private/BluetoothSdkModule.ts +47 -5
- package/src/generated/changelogCatalog.ts +4 -0
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +22 -0
- 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/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/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 -288
- /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
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Native keyword spotting, independent of full speech transcription.
|
|
4
|
+
///
|
|
5
|
+
/// The model comes from the Speech-page model directory passed to `configure`. It is loaded
|
|
6
|
+
/// while detection is enabled and released when detection is disabled.
|
|
7
|
+
final class WakeWordDetector {
|
|
8
|
+
static let shared = WakeWordDetector()
|
|
9
|
+
|
|
10
|
+
static let requiredModelFiles = ["encoder.int8.onnx", "decoder.onnx", "joiner.int8.onnx", "tokens.txt", "keywords.txt"]
|
|
11
|
+
private static let phrase = "Hey Mentra"
|
|
12
|
+
|
|
13
|
+
private let lock = NSLock()
|
|
14
|
+
private var modelDir: String?
|
|
15
|
+
// Worker queue only.
|
|
16
|
+
private var lastDetection: TimeInterval = 0
|
|
17
|
+
private lazy var worker: DemandDrivenAudioWorker<SherpaOnnxKeywordSpotterWrapper> = DemandDrivenAudioWorker(
|
|
18
|
+
queue: DispatchQueue(label: "com.mentra.wakeword.processor", qos: .userInitiated),
|
|
19
|
+
makeProcessor: { [weak self] in self?.makeSpotter() },
|
|
20
|
+
process: { [weak self] spotter, data, generation in
|
|
21
|
+
self?.process(spotter, data: data, generation: generation)
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
private init() {
|
|
26
|
+
_ = worker
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// Enable with the model in `modelDir`, or disable and release the model. Enabling returns
|
|
30
|
+
/// once the model is loaded and `ready` has been sent; it throws when the model is missing
|
|
31
|
+
/// or fails to load, and sends no `ready` in that case.
|
|
32
|
+
func configure(enabled: Bool, modelDir requestedDir: String?) async throws {
|
|
33
|
+
guard enabled else {
|
|
34
|
+
setModelDir(nil)
|
|
35
|
+
worker.setActive(false)
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
guard let dir = requestedDir, !dir.isEmpty else {
|
|
39
|
+
throw Self.error("Wake-word model directory is required to enable detection")
|
|
40
|
+
}
|
|
41
|
+
let missing = Self.requiredModelFiles.filter {
|
|
42
|
+
!FileManager.default.fileExists(atPath: (dir as NSString).appendingPathComponent($0))
|
|
43
|
+
}
|
|
44
|
+
guard missing.isEmpty else {
|
|
45
|
+
throw Self.error("Wake-word model files are missing: \(missing.joined(separator: ", "))")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
lock.lock()
|
|
49
|
+
let changed = modelDir != dir
|
|
50
|
+
modelDir = dir
|
|
51
|
+
lock.unlock()
|
|
52
|
+
if changed {
|
|
53
|
+
// Load the new directory even if detection was already on with another one.
|
|
54
|
+
worker.setActive(false)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The engine retries a failed load by enabling the same directory again.
|
|
58
|
+
switch await worker.activateAndAwaitLoad() {
|
|
59
|
+
case .loaded:
|
|
60
|
+
// Send `ready` only for the detector that is still on; disabling in the meantime
|
|
61
|
+
// invalidates the generation captured here.
|
|
62
|
+
let sent = await worker.withCurrentProcessor { _, _ -> Bool in
|
|
63
|
+
Self.emit("ready")
|
|
64
|
+
return true
|
|
65
|
+
}
|
|
66
|
+
if sent != true {
|
|
67
|
+
Bridge.log("WAKE_WORD: disabled before the model finished loading")
|
|
68
|
+
}
|
|
69
|
+
case .failed:
|
|
70
|
+
throw Self.error("Could not load the wake-word model")
|
|
71
|
+
case .noDemand:
|
|
72
|
+
break // Disabled while loading.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func accept(_ pcm: Data) {
|
|
77
|
+
worker.accept(pcm)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private func setModelDir(_ dir: String?) {
|
|
81
|
+
lock.lock()
|
|
82
|
+
modelDir = dir
|
|
83
|
+
lock.unlock()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Worker queue only.
|
|
87
|
+
private func makeSpotter() -> SherpaOnnxKeywordSpotterWrapper? {
|
|
88
|
+
lock.lock()
|
|
89
|
+
let dir = modelDir
|
|
90
|
+
lock.unlock()
|
|
91
|
+
guard let dir else { return nil }
|
|
92
|
+
let path = { (name: String) in (dir as NSString).appendingPathComponent(name) }
|
|
93
|
+
guard Self.requiredModelFiles.allSatisfy({ FileManager.default.fileExists(atPath: path($0)) }) else {
|
|
94
|
+
Bridge.log("WAKE_WORD: model files are missing in \(dir)")
|
|
95
|
+
return nil
|
|
96
|
+
}
|
|
97
|
+
let transducer = sherpaOnnxOnlineTransducerModelConfig(
|
|
98
|
+
encoder: path("encoder.int8.onnx"), decoder: path("decoder.onnx"), joiner: path("joiner.int8.onnx")
|
|
99
|
+
)
|
|
100
|
+
let model = sherpaOnnxOnlineModelConfig(tokens: path("tokens.txt"), transducer: transducer, numThreads: 1)
|
|
101
|
+
var config = sherpaOnnxKeywordSpotterConfig(featConfig: sherpaOnnxFeatureConfig(), modelConfig: model,
|
|
102
|
+
keywordsFile: path("keywords.txt"), maxActivePaths: 8, numTrailingBlanks: 1, keywordsScore: 3.0)
|
|
103
|
+
guard let spotter = SherpaOnnxKeywordSpotterWrapper(config: &config) else {
|
|
104
|
+
Bridge.log("WAKE_WORD: sherpa-onnx rejected the keyword spotter model in \(dir)")
|
|
105
|
+
return nil
|
|
106
|
+
}
|
|
107
|
+
lastDetection = 0
|
|
108
|
+
Bridge.log("WAKE_WORD: keyword spotter loaded from \(dir)")
|
|
109
|
+
return spotter
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Worker queue only.
|
|
113
|
+
private func process(_ spotter: SherpaOnnxKeywordSpotterWrapper, data: Data, generation: UInt64) {
|
|
114
|
+
let samples: [Float] = data.withUnsafeBytes { bytes in
|
|
115
|
+
(0 ..< (bytes.count / 2)).map { i in
|
|
116
|
+
let bits = UInt16(bytes[i * 2]) | UInt16(bytes[i * 2 + 1]) << 8
|
|
117
|
+
return Float(Int16(bitPattern: bits)) / 32768
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
spotter.acceptWaveform(samples: samples)
|
|
121
|
+
while spotter.isReady() {
|
|
122
|
+
spotter.decode()
|
|
123
|
+
if !spotter.getResult().keyword.isEmpty {
|
|
124
|
+
spotter.reset()
|
|
125
|
+
let now = Date().timeIntervalSince1970
|
|
126
|
+
if worker.isCurrent(generation), now - lastDetection >= 0.25 {
|
|
127
|
+
lastDetection = now
|
|
128
|
+
Self.emit("detected")
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private static func error(_ message: String) -> NSError {
|
|
135
|
+
NSError(domain: "WakeWordDetector", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private static func emit(_ kind: String) {
|
|
139
|
+
Bridge.sendTypedMessage("wake_word", body: [
|
|
140
|
+
"kind": kind,
|
|
141
|
+
"phrase": phrase,
|
|
142
|
+
"timestamp": Date().timeIntervalSince1970 * 1000,
|
|
143
|
+
])
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -172,14 +172,21 @@ public struct ConnectOptions {
|
|
|
172
172
|
/// Mentra Live on iOS only. Whether CoreBluetooth should require ANCS
|
|
173
173
|
/// authorization while establishing the connection.
|
|
174
174
|
public let requiresAncs: Bool
|
|
175
|
+
/// Mentra Live on iOS only. Ask CoreBluetooth to bring up the Classic
|
|
176
|
+
/// profiles (A2DP/HFP) after the BLE connection. On by default: iOS derives
|
|
177
|
+
/// the Classic key at the BLE bond but never starts Classic, and the glasses
|
|
178
|
+
/// commit `no_classic`, so pairing waits forever for an audio route without it.
|
|
179
|
+
public let enableTransportBridging: Bool
|
|
175
180
|
|
|
176
181
|
public init(
|
|
177
182
|
saveAsDefault: Bool = true,
|
|
178
183
|
cancelExistingConnectionAttempt: Bool = true,
|
|
179
|
-
requiresAncs: Bool = true
|
|
184
|
+
requiresAncs: Bool = true,
|
|
185
|
+
enableTransportBridging: Bool = true
|
|
180
186
|
) {
|
|
181
187
|
self.saveAsDefault = saveAsDefault
|
|
182
188
|
self.cancelExistingConnectionAttempt = cancelExistingConnectionAttempt
|
|
183
189
|
self.requiresAncs = requiresAncs
|
|
190
|
+
self.enableTransportBridging = enableTransportBridging
|
|
184
191
|
}
|
|
185
192
|
}
|
|
@@ -22,6 +22,14 @@ class AudioSessionMonitor {
|
|
|
22
22
|
static var isMonitoring = false
|
|
23
23
|
static var devicePattern: String?
|
|
24
24
|
static var callback: ((Bool, String?) -> Void)?
|
|
25
|
+
/// Last pair-audio decision line. The check runs on a timer; log only changes.
|
|
26
|
+
private static var lastPairFlow = ""
|
|
27
|
+
/// SoloAmbient hides paired HFP inputs. One short category probe per second is enough.
|
|
28
|
+
private static var lastBluetoothProbe: (at: Date, outputs: [AVAudioSessionPortDescription], inputs: [AVAudioSessionPortDescription]?)?
|
|
29
|
+
/// The glasses sent `classic_link` in the current BLE session. Their report replaces the
|
|
30
|
+
/// category probe, which can see a route that is not the glasses'. Old firmware never sends
|
|
31
|
+
/// it and keeps the probe.
|
|
32
|
+
static var glassesReportClassicLink = false
|
|
25
33
|
|
|
26
34
|
private init() {
|
|
27
35
|
Bridge.log("AudioMonitor: Initialized")
|
|
@@ -93,18 +101,134 @@ class AudioSessionMonitor {
|
|
|
93
101
|
return false
|
|
94
102
|
}
|
|
95
103
|
|
|
104
|
+
private struct BluetoothSessionSnapshot {
|
|
105
|
+
let categoryLabel: String
|
|
106
|
+
let outputs: [AVAudioSessionPortDescription]
|
|
107
|
+
let availableInputs: [AVAudioSessionPortDescription]?
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// The default SoloAmbient session lists only the built-in mic, so glasses that are
|
|
111
|
+
/// already connected in Settings look absent and pairing waits out the auto-audio timer.
|
|
112
|
+
/// Read HFP inputs with a category that can see them, then put the previous category back.
|
|
113
|
+
/// Does not activate the session or select an input.
|
|
114
|
+
private static func bluetoothSessionSnapshot() -> BluetoothSessionSnapshot {
|
|
115
|
+
if !Thread.isMainThread {
|
|
116
|
+
return DispatchQueue.main.sync { bluetoothSessionSnapshot() }
|
|
117
|
+
}
|
|
118
|
+
let session = AVAudioSession.sharedInstance()
|
|
119
|
+
if categoryShowsBluetoothInputs(session.category) {
|
|
120
|
+
return BluetoothSessionSnapshot(
|
|
121
|
+
categoryLabel: session.category.rawValue,
|
|
122
|
+
outputs: session.currentRoute.outputs,
|
|
123
|
+
availableInputs: session.availableInputs
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
if glassesReportClassicLink {
|
|
127
|
+
// Passive route observation only: never switch the category.
|
|
128
|
+
return BluetoothSessionSnapshot(
|
|
129
|
+
categoryLabel: "passive:\(session.category.rawValue)",
|
|
130
|
+
outputs: session.currentRoute.outputs,
|
|
131
|
+
availableInputs: session.availableInputs
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
if let lastBluetoothProbe, Date().timeIntervalSince(lastBluetoothProbe.at) < 1 {
|
|
135
|
+
return BluetoothSessionSnapshot(
|
|
136
|
+
categoryLabel: "probed:\(AVAudioSession.Category.playAndRecord.rawValue)",
|
|
137
|
+
outputs: lastBluetoothProbe.outputs,
|
|
138
|
+
availableInputs: lastBluetoothProbe.inputs
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
let savedCategory = session.category
|
|
142
|
+
let savedMode = session.mode
|
|
143
|
+
let savedOptions = session.categoryOptions
|
|
144
|
+
do {
|
|
145
|
+
try session.setCategory(
|
|
146
|
+
.playAndRecord, mode: .default, options: [.allowBluetooth, .allowBluetoothA2DP]
|
|
147
|
+
)
|
|
148
|
+
} catch {
|
|
149
|
+
return BluetoothSessionSnapshot(
|
|
150
|
+
categoryLabel: session.category.rawValue,
|
|
151
|
+
outputs: session.currentRoute.outputs,
|
|
152
|
+
availableInputs: session.availableInputs
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
let outputs = session.currentRoute.outputs
|
|
156
|
+
let inputs = session.availableInputs
|
|
157
|
+
lastBluetoothProbe = (Date(), outputs, inputs)
|
|
158
|
+
try? session.setCategory(savedCategory, mode: savedMode, options: savedOptions)
|
|
159
|
+
return BluetoothSessionSnapshot(
|
|
160
|
+
categoryLabel: "probed:\(AVAudioSession.Category.playAndRecord.rawValue)",
|
|
161
|
+
outputs: outputs,
|
|
162
|
+
availableInputs: inputs
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private static func categoryShowsBluetoothInputs(_ category: AVAudioSession.Category) -> Bool {
|
|
167
|
+
category == .playAndRecord || category == .record || category == .multiRoute
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// Glasses' Classic audio facts without selecting an input or activating the session.
|
|
171
|
+
/// `profilesConnected` matches `isDevicePaired`; `audioRouted` is the stricter
|
|
172
|
+
/// "audio is flowing to the glasses" signal.
|
|
173
|
+
static func observeProfiles(devicePattern: String) -> BluetoothAudioRoute.ProfileObservation {
|
|
174
|
+
let snapshot = bluetoothSessionSnapshot()
|
|
175
|
+
let profiles = profileObservation(
|
|
176
|
+
devicePattern: devicePattern, outputs: snapshot.outputs, availableInputs: snapshot.availableInputs
|
|
177
|
+
)
|
|
178
|
+
logPairFlow(
|
|
179
|
+
category: snapshot.categoryLabel, devicePattern: devicePattern, outputs: snapshot.outputs,
|
|
180
|
+
availableInputs: snapshot.availableInputs, profiles: profiles
|
|
181
|
+
)
|
|
182
|
+
return profiles
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private static func profileObservation(
|
|
186
|
+
devicePattern: String,
|
|
187
|
+
outputs: [AVAudioSessionPortDescription],
|
|
188
|
+
availableInputs: [AVAudioSessionPortDescription]?
|
|
189
|
+
) -> BluetoothAudioRoute.ProfileObservation {
|
|
190
|
+
BluetoothAudioRoute.observeProfiles(
|
|
191
|
+
outputs: outputs.map { (name: $0.portName, portType: $0.portType.rawValue) },
|
|
192
|
+
inputs: availableInputs?.map { (name: $0.portName, portType: $0.portType.rawValue) },
|
|
193
|
+
target: devicePattern, isIOSAppOnMac: ProcessInfo.processInfo.isiOSAppOnMac
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// One PAIRFLOW line per transition of category, inputs availability, ports, and both facts.
|
|
198
|
+
/// Port names are the glasses' advertised name or other audio devices; no credentials are logged.
|
|
199
|
+
private static func logPairFlow(
|
|
200
|
+
category: String,
|
|
201
|
+
devicePattern: String,
|
|
202
|
+
outputs: [AVAudioSessionPortDescription],
|
|
203
|
+
availableInputs: [AVAudioSessionPortDescription]?,
|
|
204
|
+
profiles: BluetoothAudioRoute.ProfileObservation
|
|
205
|
+
) {
|
|
206
|
+
let decision = profiles.audioRouted
|
|
207
|
+
? "advance_active_output"
|
|
208
|
+
: (profiles.profilesConnected ? "advance_hfp_input" : "wait_no_route")
|
|
209
|
+
let outputNames = outputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")
|
|
210
|
+
let inputNames = (availableInputs ?? []).map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")
|
|
211
|
+
let pairFlow =
|
|
212
|
+
"PAIRFLOW: pair_audio decision=\(decision) pattern=\(devicePattern) category=\(category) inputsNil=\(availableInputs == nil) outputs=[\(outputNames)] inputs=[\(inputNames)] profilesConnected=\(profiles.profilesConnected) audioRouted=\(profiles.audioRouted)"
|
|
213
|
+
if pairFlow != lastPairFlow {
|
|
214
|
+
lastPairFlow = pairFlow
|
|
215
|
+
Bridge.log(pairFlow)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
96
219
|
/// Check if a Bluetooth device matching the pattern is paired (appears in availableInputs)
|
|
97
220
|
/// Returns true if device is found (paired), WITHOUT activating it
|
|
98
221
|
/// This avoids switching A2DP music playback to HFP microphone mode
|
|
99
222
|
static func isDevicePaired(devicePattern: String) -> Bool {
|
|
100
|
-
let
|
|
101
|
-
let outputs =
|
|
223
|
+
let snapshot = bluetoothSessionSnapshot()
|
|
224
|
+
let outputs = snapshot.outputs
|
|
102
225
|
let route = BluetoothAudioRoute.observe(
|
|
103
226
|
outputs: outputs.map { (name: $0.portName, portType: $0.portType.rawValue) },
|
|
104
227
|
target: devicePattern, isIOSAppOnMac: ProcessInfo.processInfo.isiOSAppOnMac
|
|
105
228
|
)
|
|
106
229
|
let activeTarget = route.matchingOutputCount > 0
|
|
107
|
-
let availableInputs =
|
|
230
|
+
let availableInputs = snapshot.availableInputs
|
|
231
|
+
let profiles = profileObservation(devicePattern: devicePattern, outputs: outputs, availableInputs: availableInputs)
|
|
108
232
|
let bluetoothInput = availableInputs?.first { input in
|
|
109
233
|
input.portType == .bluetoothHFP
|
|
110
234
|
&& input.portName.localizedCaseInsensitiveContains(devicePattern)
|
|
@@ -112,8 +236,12 @@ class AudioSessionMonitor {
|
|
|
112
236
|
|
|
113
237
|
// NSLog messages redact the native route checks in retained Mac logs.
|
|
114
238
|
// Keep categorical evidence at notice level without exposing names or
|
|
115
|
-
// selecting an input
|
|
116
|
-
readinessLog.notice("Pair audio: iosOnMac=\(ProcessInfo.processInfo.isiOSAppOnMac, privacy: .public) targetPresent=\(!devicePattern.isEmpty, privacy: .public) category=\(
|
|
239
|
+
// selecting an input or activating the session.
|
|
240
|
+
readinessLog.notice("Pair audio: iosOnMac=\(ProcessInfo.processInfo.isiOSAppOnMac, privacy: .public) targetPresent=\(!devicePattern.isEmpty, privacy: .public) category=\(snapshot.categoryLabel, privacy: .public) outputs=\(outputs.count, privacy: .public) bluetoothOutputs=\(route.bluetoothOutputCount, privacy: .public) targetNameOutputs=\(route.targetNameOutputCount, privacy: .public) inputs=\(availableInputs?.count ?? -1, privacy: .public) activeTarget=\(activeTarget, privacy: .public) hfpTarget=\(bluetoothInput != nil, privacy: .public)")
|
|
241
|
+
logPairFlow(
|
|
242
|
+
category: snapshot.categoryLabel, devicePattern: devicePattern, outputs: outputs,
|
|
243
|
+
availableInputs: availableInputs, profiles: profiles
|
|
244
|
+
)
|
|
117
245
|
|
|
118
246
|
// Check if already active (using A2DP for music or HFP for calls)
|
|
119
247
|
if activeTarget {
|
|
@@ -320,6 +448,31 @@ enum BluetoothAudioRoute {
|
|
|
320
448
|
)
|
|
321
449
|
}
|
|
322
450
|
|
|
451
|
+
/// Separate facts about the glasses' Classic audio link. Neither implies a bond:
|
|
452
|
+
/// a bonded device with no connected audio profile is invisible to AVAudioSession.
|
|
453
|
+
struct ProfileObservation: Equatable {
|
|
454
|
+
/// An HFP input is available, or a matching Bluetooth output is active.
|
|
455
|
+
let profilesConnected: Bool
|
|
456
|
+
/// A matching Bluetooth output is the active route (A2DP or HFP).
|
|
457
|
+
let audioRouted: Bool
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/// `inputs` is nil when `AVAudioSession.availableInputs` is nil (it depends on the session category).
|
|
461
|
+
static func observeProfiles(
|
|
462
|
+
outputs: [(name: String, portType: String)],
|
|
463
|
+
inputs: [(name: String, portType: String)]?,
|
|
464
|
+
target: String,
|
|
465
|
+
isIOSAppOnMac: Bool
|
|
466
|
+
) -> ProfileObservation {
|
|
467
|
+
let audioRouted = outputs.contains {
|
|
468
|
+
matches(name: $0.name, portType: $0.portType, target: target, isIOSAppOnMac: isIOSAppOnMac)
|
|
469
|
+
}
|
|
470
|
+
let hfpInput = inputs?.contains {
|
|
471
|
+
$0.portType == "BluetoothHFP" && matchesName($0.name, target: target)
|
|
472
|
+
} ?? false
|
|
473
|
+
return ProfileObservation(profilesConnected: audioRouted || hfpInput, audioRouted: audioRouted)
|
|
474
|
+
}
|
|
475
|
+
|
|
323
476
|
static func matches(name: String, portType: String, target: String, isIOSAppOnMac: Bool) -> Bool {
|
|
324
477
|
matchesName(name, target: target) && isBluetoothTransport(portType, isIOSAppOnMac: isIOSAppOnMac)
|
|
325
478
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Settles a bounded wait exactly once, from whichever comes first: the work or the timeout.
|
|
4
|
+
final class BoundedWaitResolver<T>: @unchecked Sendable {
|
|
5
|
+
private let lock = NSLock()
|
|
6
|
+
private var continuation: CheckedContinuation<T, Never>?
|
|
7
|
+
|
|
8
|
+
fileprivate init(_ continuation: CheckedContinuation<T, Never>) {
|
|
9
|
+
self.continuation = continuation
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/// True once the wait has settled. Work that finds it settled should skip its side effects.
|
|
13
|
+
var isSettled: Bool {
|
|
14
|
+
lock.lock()
|
|
15
|
+
defer { lock.unlock() }
|
|
16
|
+
return continuation == nil
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// Settle with `value`. Later calls are ignored.
|
|
20
|
+
func resolve(_ value: T) {
|
|
21
|
+
lock.lock()
|
|
22
|
+
let pending = continuation
|
|
23
|
+
continuation = nil
|
|
24
|
+
lock.unlock()
|
|
25
|
+
pending?.resume(returning: value)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// Run `start`, which must eventually call `resolve` on the resolver it receives, and settle with
|
|
30
|
+
/// `timeoutValue` if it has not done so within `timeout` seconds. Never throws.
|
|
31
|
+
func withBoundedWait<T>(
|
|
32
|
+
timeout: TimeInterval,
|
|
33
|
+
timeoutValue: T,
|
|
34
|
+
timerQueue: DispatchQueue = .global(qos: .userInitiated),
|
|
35
|
+
_ start: (BoundedWaitResolver<T>) -> Void
|
|
36
|
+
) async -> T {
|
|
37
|
+
await withCheckedContinuation { continuation in
|
|
38
|
+
let resolver = BoundedWaitResolver(continuation)
|
|
39
|
+
timerQueue.asyncAfter(deadline: .now() + timeout) {
|
|
40
|
+
resolver.resolve(timeoutValue)
|
|
41
|
+
}
|
|
42
|
+
start(resolver)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -31,6 +31,8 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
31
31
|
private var processor: Processor?
|
|
32
32
|
private var processorGeneration: UInt64?
|
|
33
33
|
private var attemptedInitialization = false
|
|
34
|
+
/// Control operations queued behind audio; while any wait, `drain` yields after each buffer.
|
|
35
|
+
private var pendingControlOperations = 0
|
|
34
36
|
|
|
35
37
|
init(capacity: Int = 100,
|
|
36
38
|
queue: DispatchQueue = DispatchQueue(label: "com.mentra.speech.processor", qos: .userInitiated),
|
|
@@ -86,6 +88,76 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
86
88
|
return active && generation == token
|
|
87
89
|
}
|
|
88
90
|
|
|
91
|
+
/// Outcome of the processor load for the current demand.
|
|
92
|
+
enum LoadState: Equatable {
|
|
93
|
+
/// No demand, so nothing is loaded and nothing needs to be.
|
|
94
|
+
case noDemand
|
|
95
|
+
case loaded
|
|
96
|
+
case failed
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Serialize control operations with inference without enabling audio demand.
|
|
100
|
+
func perform<T>(_ operation: @escaping () -> T) async -> T {
|
|
101
|
+
await withCheckedContinuation { continuation in
|
|
102
|
+
lock.lock()
|
|
103
|
+
pendingControlOperations += 1
|
|
104
|
+
lock.unlock()
|
|
105
|
+
queue.async {
|
|
106
|
+
self.lock.lock()
|
|
107
|
+
self.pendingControlOperations -= 1
|
|
108
|
+
self.lock.unlock()
|
|
109
|
+
continuation.resume(returning: operation())
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Run `operation` on the worker queue, after audio already queued, with the processor of the
|
|
115
|
+
/// current demand. Returns nil without running it when there is no demand or no processor.
|
|
116
|
+
func withCurrentProcessor<T>(_ operation: @escaping (Processor, UInt64) -> T) async -> T? {
|
|
117
|
+
await perform {
|
|
118
|
+
self.lock.lock()
|
|
119
|
+
let token = self.generation
|
|
120
|
+
let current = self.active && self.processorGeneration == token
|
|
121
|
+
self.lock.unlock()
|
|
122
|
+
guard current, let processor = self.processor else { return nil }
|
|
123
|
+
return operation(processor, token)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// Wait until the processor for the current demand has been created (or failed to be).
|
|
128
|
+
/// Returns immediately when there is no demand.
|
|
129
|
+
func awaitLoad() async -> LoadState {
|
|
130
|
+
while true {
|
|
131
|
+
guard snapshot().active else { return .noDemand }
|
|
132
|
+
// A drain is already scheduled ahead of this block whenever demand changed, so
|
|
133
|
+
// the state seen here is settled unless demand changed again in the meantime.
|
|
134
|
+
let state: LoadState? = await perform {
|
|
135
|
+
self.lock.lock()
|
|
136
|
+
defer { self.lock.unlock() }
|
|
137
|
+
guard self.active else { return .noDemand }
|
|
138
|
+
guard self.processorGeneration == self.generation, self.attemptedInitialization else { return nil }
|
|
139
|
+
return self.processor == nil ? .failed : .loaded
|
|
140
|
+
}
|
|
141
|
+
if let state { return state }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// Reload the processor if there is demand, and wait for the result.
|
|
146
|
+
func restartAndAwaitLoad() async -> LoadState {
|
|
147
|
+
restart()
|
|
148
|
+
return await awaitLoad()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Turn demand on and wait for the load. Enabling again while a failed load is cached is a
|
|
152
|
+
/// retry, so it loads once more; enabling a loaded or loading processor changes nothing.
|
|
153
|
+
func activateAndAwaitLoad() async -> LoadState {
|
|
154
|
+
let wasActive = snapshot().active
|
|
155
|
+
setActive(true)
|
|
156
|
+
let state = await awaitLoad()
|
|
157
|
+
guard state == .failed, wasActive else { return state }
|
|
158
|
+
return await restartAndAwaitLoad()
|
|
159
|
+
}
|
|
160
|
+
|
|
89
161
|
func snapshot() -> Snapshot {
|
|
90
162
|
lock.lock()
|
|
91
163
|
defer { lock.unlock() }
|
|
@@ -144,6 +216,13 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
144
216
|
lock.lock()
|
|
145
217
|
processedBuffers &+= 1
|
|
146
218
|
processing = false
|
|
219
|
+
// When inference can't keep up, audio never runs out. Yield to a waiting control
|
|
220
|
+
// operation (a load wait, a flush) instead of starving it.
|
|
221
|
+
if pendingControlOperations > 0, !buffers.isEmpty {
|
|
222
|
+
lock.unlock()
|
|
223
|
+
queue.async { self.drain() }
|
|
224
|
+
return
|
|
225
|
+
}
|
|
147
226
|
lock.unlock()
|
|
148
227
|
}
|
|
149
228
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What a loaded on-device speech model can do, decided from its files, never its folder name.
|
|
4
|
+
struct SttModelTraits: Equatable {
|
|
5
|
+
enum Kind: String {
|
|
6
|
+
/// Streaming transducer (encoder/decoder/joiner), e.g. Zipformer or Kroko.
|
|
7
|
+
case transducer
|
|
8
|
+
/// Streaming CTC (single model file).
|
|
9
|
+
case ctc
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let kind: Kind
|
|
13
|
+
/// The vocabulary has no lowercase letters, so the model writes ALL CAPS.
|
|
14
|
+
let uppercaseOnlyVocabulary: Bool
|
|
15
|
+
|
|
16
|
+
init(kind: Kind, uppercaseOnlyVocabulary: Bool) {
|
|
17
|
+
self.kind = kind
|
|
18
|
+
self.uppercaseOnlyVocabulary = uppercaseOnlyVocabulary
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
init(kind: Kind, tokensFileContents: String) {
|
|
22
|
+
self.init(kind: kind, uppercaseOnlyVocabulary: Self.isUppercaseOnly(tokensFileContents: tokensFileContents))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Any streaming transducer can end its utterance early by flushing its stream.
|
|
26
|
+
var canFinalizeEarly: Bool {
|
|
27
|
+
kind == .transducer
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Same rule as Android: streaming transducers get four CPU threads, other models one.
|
|
31
|
+
var numThreads: Int {
|
|
32
|
+
kind == .transducer ? 4 : 1
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Lowercase output from a model that can only write capitals; keep everything else as the
|
|
36
|
+
/// model wrote it, including its punctuation and capitalization.
|
|
37
|
+
func format(_ text: String) -> String {
|
|
38
|
+
uppercaseOnlyVocabulary ? text.lowercased() : text
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// `tokens.txt` holds one `<token> <id>` per line. Special tokens such as `<blk>` or `<0x41>`
|
|
42
|
+
/// are ignored. A vocabulary with capital letters and no lowercase letters is uppercase-only.
|
|
43
|
+
static func isUppercaseOnly(tokensFileContents: String) -> Bool {
|
|
44
|
+
var sawUppercase = false
|
|
45
|
+
for rawLine in tokensFileContents.split(whereSeparator: \.isNewline) {
|
|
46
|
+
let line = rawLine.trimmingCharacters(in: .whitespaces)
|
|
47
|
+
guard !line.isEmpty else { continue }
|
|
48
|
+
let token: Substring
|
|
49
|
+
if let separator = line.lastIndex(where: { $0 == " " || $0 == "\t" }) {
|
|
50
|
+
token = line[..<separator]
|
|
51
|
+
} else {
|
|
52
|
+
token = Substring(line)
|
|
53
|
+
}
|
|
54
|
+
if token.hasPrefix("<"), token.hasSuffix(">") { continue }
|
|
55
|
+
for character in token where character.isLetter {
|
|
56
|
+
if character.isLowercase { return false }
|
|
57
|
+
if character.isUppercase { sawUppercase = true }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return sawUppercase
|
|
61
|
+
}
|
|
62
|
+
}
|