This repository was archived by the owner on Apr 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathspeech_bridge.swift
More file actions
2056 lines (1777 loc) · 56.7 KB
/
Copy pathspeech_bridge.swift
File metadata and controls
2056 lines (1777 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AudioCommon
import AVFoundation
import Foundation
import OmnilingualASR
import ParakeetASR
import ParakeetStreamingASR
import Qwen3ASR
import SpeechVAD
import SwiftRs
private enum SpeechBridgeError: LocalizedError {
case message(String)
var errorDescription: String? {
switch self {
case .message(let message):
return message
}
}
}
private enum ProcessingMode: String {
case realtime
case batch
}
private enum SpeechModelKind: String, CaseIterable {
case parakeetStreaming
case parakeetBatch
case omnilingual
case qwen3Small
case qwen3Large
static func resolve(_ identifier: String) -> Self? {
Self(rawValue: identifier) ?? Self.allCases.first(where: { $0.repo == identifier })
}
var label: String {
switch self {
case .parakeetStreaming:
return "Parakeet Streaming"
case .parakeetBatch:
return "Parakeet Batch"
case .omnilingual:
return "Omnilingual"
case .qwen3Small:
return "Qwen3 0.6B"
case .qwen3Large:
return "Qwen3 1.7B"
}
}
var repo: String {
switch self {
case .parakeetStreaming:
return "aufklarer/Parakeet-EOU-120M-CoreML-INT8"
case .parakeetBatch:
return "aufklarer/Parakeet-TDT-v3-CoreML-INT8"
case .omnilingual:
return "aufklarer/Omnilingual-ASR-CTC-300M-CoreML-INT8-10s"
case .qwen3Small:
return "aufklarer/Qwen3-ASR-0.6B-MLX-4bit"
case .qwen3Large:
return "aufklarer/Qwen3-ASR-1.7B-MLX-8bit"
}
}
var isStreamingCapable: Bool {
self == .parakeetStreaming
}
func cacheDirectoryURL() throws -> URL {
try HuggingFaceDownloader.getCacheDirectory(for: repo)
}
func cacheDirectoryPath() -> String {
(try? cacheDirectoryURL().path) ?? ""
}
func filesReady() -> Bool {
guard let directory = try? cacheDirectoryURL() else {
return false
}
switch self {
case .parakeetStreaming, .parakeetBatch:
return Self.regularFileExists(at: directory.appendingPathComponent("config.json"))
&& Self.regularFileExists(at: directory.appendingPathComponent("vocab.json"))
&& Self.compiledCoreMLModelReady(at: directory.appendingPathComponent("encoder.mlmodelc"))
&& Self.compiledCoreMLModelReady(at: directory.appendingPathComponent("decoder.mlmodelc"))
&& Self.compiledCoreMLModelReady(at: directory.appendingPathComponent("joint.mlmodelc"))
case .omnilingual:
return Self.regularFileExists(at: directory.appendingPathComponent("config.json"))
&& Self.regularFileExists(at: directory.appendingPathComponent("tokenizer.model"))
&& Self.directoryContainsRegularFile(
at: directory.appendingPathComponent("omnilingual-ctc-300m-int8.mlpackage")
)
case .qwen3Small, .qwen3Large:
return Self.regularFileExists(at: directory.appendingPathComponent("vocab.json"))
&& Self.regularFileExists(at: directory.appendingPathComponent("merges.txt"))
&& Self.regularFileExists(at: directory.appendingPathComponent("tokenizer_config.json"))
&& Self.directoryContainsFile(withExtension: "safetensors", in: directory)
}
}
func load(progressHandler: ((Double, String) -> Void)?) async throws -> LoadedSpeechModel {
let offlineMode = filesReady()
switch self {
case .parakeetStreaming:
return .streaming(
try await ParakeetStreamingASRModel.fromPretrained(
modelId: repo,
progressHandler: progressHandler
)
)
case .parakeetBatch:
return .parakeetBatch(
try await ParakeetASRModel.fromPretrained(
modelId: repo,
offlineMode: offlineMode,
progressHandler: progressHandler
)
)
case .omnilingual:
return .omnilingual(
try await OmnilingualASRModel.fromPretrained(
modelId: repo,
offlineMode: offlineMode,
progressHandler: progressHandler
)
)
case .qwen3Small, .qwen3Large:
return .qwen3(
try await Qwen3ASRModel.fromPretrained(
modelId: repo,
offlineMode: offlineMode,
progressHandler: progressHandler
)
)
}
}
private static func regularFileExists(at url: URL) -> Bool {
var isDirectory = ObjCBool(false)
return FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)
&& !isDirectory.boolValue
}
private static func compiledCoreMLModelReady(at directory: URL) -> Bool {
var isDirectory = ObjCBool(false)
guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory),
isDirectory.boolValue
else {
return false
}
return regularFileExists(at: directory.appendingPathComponent("model.mil"))
&& directoryContainsRegularFile(at: directory.appendingPathComponent("weights"))
}
private static func directoryContainsFile(withExtension pathExtension: String, in directory: URL)
-> Bool
{
guard
let contents = try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: [.isRegularFileKey]
)
else {
return false
}
return contents.contains { candidate in
guard
candidate.pathExtension == pathExtension,
let values = try? candidate.resourceValues(forKeys: [.isRegularFileKey])
else {
return false
}
return values.isRegularFile == true
}
}
private static func directoryContainsRegularFile(at directory: URL) -> Bool {
guard
let enumerator = FileManager.default.enumerator(
at: directory,
includingPropertiesForKeys: [.isRegularFileKey],
options: [.skipsHiddenFiles]
)
else {
return false
}
for case let candidate as URL in enumerator {
guard let values = try? candidate.resourceValues(forKeys: [.isRegularFileKey]) else {
continue
}
if values.isRegularFile == true {
return true
}
}
return false
}
}
private enum LoadedSpeechModel {
case streaming(ParakeetStreamingASRModel)
case parakeetBatch(ParakeetASRModel)
case omnilingual(OmnilingualASRModel)
case qwen3(Qwen3ASRModel)
func asStreamingModel() throws -> ParakeetStreamingASRModel {
guard case .streaming(let model) = self else {
throw SpeechBridgeError.message("The selected model does not support realtime transcription.")
}
return model
}
func transcribe(audio: [Float], sampleRate: Int, language: String?) throws -> String {
let normalizedLanguage = language?.trimmingCharacters(in: .whitespacesAndNewlines)
let languageHint = (normalizedLanguage?.isEmpty == false) ? normalizedLanguage : nil
switch self {
case .streaming(let model):
return try model.transcribeAudio(audio, sampleRate: sampleRate)
case .parakeetBatch(let model):
return try model.transcribeAudio(audio, sampleRate: sampleRate, language: languageHint)
case .omnilingual(let model):
return try model.transcribeAudio(audio, sampleRate: sampleRate)
case .qwen3(let model):
return model.transcribe(audio: audio, sampleRate: sampleRate, language: languageHint)
}
}
}
private struct ModelDownloadPayload: Codable {
var status: String
var currentFile: String?
var progressPercent: Int?
var localPath: String
var error: String?
}
private enum TranscriptSource: String, CaseIterable, Codable {
case microphone
case system
case mixed
}
private struct TranscriptEntryPayload: Codable {
var source: String
var text: String
}
private struct TranscriptionPayload: Codable {
var running: Bool
var text: String
var error: String?
var entries: [TranscriptEntryPayload]
var audioPath: String
var mode: String?
static let empty = TranscriptionPayload(
running: false,
text: "",
error: nil,
entries: [],
audioPath: "",
mode: nil
)
}
private struct FileTranscriptionPayload: Codable {
var text: String
var error: String?
}
private struct DiarizationSegmentPayload: Codable, Sendable {
var speaker: String
var startSeconds: Double
var endSeconds: Double
}
private struct FileDiarizationPayload: Codable, Sendable {
var segments: [DiarizationSegmentPayload]
var speakerCount: Int
var pipelineSource: String
var error: String?
}
private struct SpeakerEmbeddingRequestPayload: Codable, Sendable {
var speaker: String
var segments: [DiarizationSegmentPayload]
}
private struct SpeakerEmbeddingSamplePayload: Codable, Sendable {
var startSeconds: Double
var endSeconds: Double
var durationSeconds: Double
var embedding: [Float]
}
private struct SpeakerEmbeddingPayload: Codable, Sendable {
var speaker: String
var embedding: [Float]
var samples: [SpeakerEmbeddingSamplePayload]
}
private struct FileSpeakerEmbeddingPayload: Codable, Sendable {
var speakers: [SpeakerEmbeddingPayload]
var error: String?
}
private let diarizationPipelineSource = "speech-swift / sortformer"
private func diarizationSegmentDuration(_ segment: DiarizationSegmentPayload) -> Double {
max(0, segment.endSeconds - segment.startSeconds)
}
private func trimmedSpeakerEmbeddingSegment(
_ segment: DiarizationSegmentPayload,
minimumDuration: Double,
maximumDuration: Double
) -> DiarizationSegmentPayload? {
let start = max(0, segment.startSeconds)
let end = max(start, segment.endSeconds)
let duration = end - start
guard duration >= minimumDuration else {
return nil
}
if duration <= maximumDuration {
return DiarizationSegmentPayload(speaker: segment.speaker, startSeconds: start, endSeconds: end)
}
let midpoint = start + duration / 2
let clippedStart = max(0, midpoint - maximumDuration / 2)
return DiarizationSegmentPayload(
speaker: segment.speaker,
startSeconds: clippedStart,
endSeconds: clippedStart + maximumDuration
)
}
private func selectSpeakerEmbeddingSegments(
_ segments: [DiarizationSegmentPayload],
limit: Int
) -> [DiarizationSegmentPayload] {
let primary = segments.compactMap {
trimmedSpeakerEmbeddingSegment($0, minimumDuration: 2.5, maximumDuration: 6.0)
}
let fallback = segments.compactMap {
trimmedSpeakerEmbeddingSegment($0, minimumDuration: 1.5, maximumDuration: 4.0)
}
let candidates = primary.isEmpty ? fallback : primary
return Array(
candidates
.sorted { lhs, rhs in
let lhsDuration = diarizationSegmentDuration(lhs)
let rhsDuration = diarizationSegmentDuration(rhs)
if lhsDuration == rhsDuration {
return lhs.startSeconds < rhs.startSeconds
}
return lhsDuration > rhsDuration
}
.prefix(max(1, limit))
)
}
private func sliceAudio(
_ audio: [Float],
sampleRate: Int,
startSeconds: Double,
endSeconds: Double
) -> [Float] {
guard !audio.isEmpty, sampleRate > 0 else {
return []
}
let clampedStart = max(0, startSeconds)
let clampedEnd = max(clampedStart, endSeconds)
let startIndex = min(audio.count, max(0, Int(floor(clampedStart * Double(sampleRate)))))
let endIndex = min(audio.count, max(startIndex, Int(ceil(clampedEnd * Double(sampleRate)))))
guard endIndex > startIndex else {
return []
}
return Array(audio[startIndex..<endIndex])
}
private func normalizedEmbeddingCentroid(_ embeddings: [[Float]]) -> [Float] {
guard let first = embeddings.first, !first.isEmpty else {
return []
}
var centroid = [Float](repeating: 0, count: first.count)
for embedding in embeddings where embedding.count == centroid.count {
for (index, value) in embedding.enumerated() {
centroid[index] += value
}
}
let norm = sqrt(centroid.reduce(Float.zero) { partialResult, value in
partialResult + (value * value)
})
guard norm > 0 else {
return centroid
}
return centroid.map { $0 / norm }
}
private func constrainDiarizedSegments(
_ segments: [DiarizedSegment],
requestedSpeakerCount: Int?
) -> [DiarizedSegment] {
guard
let requestedSpeakerCount,
requestedSpeakerCount > 0,
!segments.isEmpty
else {
return segments
}
if requestedSpeakerCount == 1 {
return segments.map { segment in
DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: 0
)
}
}
let speakerDurations = Dictionary(grouping: segments, by: \.speakerId)
.mapValues { speakerSegments in
speakerSegments.reduce(Float.zero) { partialResult, segment in
partialResult + segment.duration
}
}
if speakerDurations.count <= requestedSpeakerCount {
return compactDiarizedSpeakerIds(segments)
}
let retainedSpeakerIds = Set(
speakerDurations
.sorted { lhs, rhs in
if lhs.value == rhs.value {
return lhs.key < rhs.key
}
return lhs.value > rhs.value
}
.prefix(requestedSpeakerCount)
.map(\.key)
)
let retainedSegments = segments.filter { retainedSpeakerIds.contains($0.speakerId) }
let fallbackSpeakerId = retainedSpeakerIds.min() ?? 0
let remapped = segments.map { segment in
let speakerId: Int
if retainedSpeakerIds.contains(segment.speakerId) {
speakerId = segment.speakerId
} else {
speakerId =
retainedSegments.min(by: { lhs, rhs in
diarizedSegmentDistance(from: segment, to: lhs) < diarizedSegmentDistance(from: segment, to: rhs)
})?.speakerId ?? fallbackSpeakerId
}
return DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: speakerId
)
}
return compactDiarizedSpeakerIds(remapped)
}
private func diarizedSegmentDistance(from lhs: DiarizedSegment, to rhs: DiarizedSegment) -> Float {
if lhs.endTime >= rhs.startTime && rhs.endTime >= lhs.startTime {
return 0
}
return min(abs(lhs.startTime - rhs.endTime), abs(rhs.startTime - lhs.endTime))
}
private func compactDiarizedSpeakerIds(_ segments: [DiarizedSegment]) -> [DiarizedSegment] {
let speakerIds = Array(Set(segments.map(\.speakerId))).sorted()
let speakerMap = Dictionary(uniqueKeysWithValues: speakerIds.enumerated().map { ($1, $0) })
return segments.map { segment in
DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: speakerMap[segment.speakerId] ?? segment.speakerId
)
}
}
private let embeddingReassignmentMinDurationSeconds: Float = 1.0
private let embeddingReassignmentSampleRate = 16000
private func sliceAudioSamples(
_ audio: [Float],
sampleRate: Int,
startSeconds: Float,
endSeconds: Float
) -> [Float] {
guard !audio.isEmpty, sampleRate > 0 else {
return []
}
let clampedStart = max(0, startSeconds)
let clampedEnd = max(clampedStart, endSeconds)
let startIndex = min(audio.count, max(0, Int(floor(Double(clampedStart) * Double(sampleRate)))))
let endIndex = min(audio.count, max(startIndex, Int(ceil(Double(clampedEnd) * Double(sampleRate)))))
guard endIndex > startIndex else {
return []
}
return Array(audio[startIndex..<endIndex])
}
private func constrainDiarizedSegmentsUsingEmbeddings(
_ segments: [DiarizedSegment],
requestedSpeakerCount: Int?,
audio: [Float],
embeddingModel: WeSpeakerModel
) -> [DiarizedSegment] {
guard
let requestedSpeakerCount,
requestedSpeakerCount > 0,
!segments.isEmpty
else {
return segments
}
if requestedSpeakerCount == 1 {
return segments.map { segment in
DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: 0
)
}
}
let speakerDurations = Dictionary(grouping: segments, by: \.speakerId)
.mapValues { speakerSegments in
speakerSegments.reduce(Float.zero) { partialResult, segment in
partialResult + segment.duration
}
}
if speakerDurations.count <= requestedSpeakerCount {
return compactDiarizedSpeakerIds(segments)
}
let retainedSpeakerIds = Set(
speakerDurations
.sorted { lhs, rhs in
if lhs.value == rhs.value {
return lhs.key < rhs.key
}
return lhs.value > rhs.value
}
.prefix(requestedSpeakerCount)
.map(\.key)
)
var retainedCentroids = [Int: [Float]]()
for speakerId in retainedSpeakerIds {
let speakerSegments = segments.filter { $0.speakerId == speakerId }
let embeddings = speakerSegments.compactMap { segment -> [Float]? in
let samples = sliceAudioSamples(
audio,
sampleRate: embeddingReassignmentSampleRate,
startSeconds: segment.startTime,
endSeconds: segment.endTime
)
guard samples.count >= embeddingReassignmentSampleRate else {
return nil
}
let embedding = embeddingModel.embed(
audio: samples,
sampleRate: embeddingReassignmentSampleRate
)
guard embedding.contains(where: { $0 != 0 }) else {
return nil
}
return embedding
}
let centroid = normalizedEmbeddingCentroid(embeddings)
guard !centroid.isEmpty else { continue }
retainedCentroids[speakerId] = centroid
}
let fallbackSpeakerId = retainedSpeakerIds.min() ?? 0
let remapped = segments.map { segment -> DiarizedSegment in
if retainedSpeakerIds.contains(segment.speakerId) {
return segment
}
let samples = sliceAudioSamples(
audio,
sampleRate: embeddingReassignmentSampleRate,
startSeconds: segment.startTime,
endSeconds: segment.endTime
)
let minSamples = Int(
embeddingReassignmentMinDurationSeconds * Float(embeddingReassignmentSampleRate)
)
if samples.count >= minSamples, !retainedCentroids.isEmpty {
let embedding = embeddingModel.embed(
audio: samples,
sampleRate: embeddingReassignmentSampleRate
)
if embedding.contains(where: { $0 != 0 }) {
var bestSpeakerId = fallbackSpeakerId
var bestSimilarity = -Float.infinity
for (speakerId, centroid) in retainedCentroids {
let similarity = WeSpeakerModel.cosineSimilarity(embedding, centroid)
if similarity > bestSimilarity {
bestSimilarity = similarity
bestSpeakerId = speakerId
}
}
return DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: bestSpeakerId
)
}
}
let retainedSegments = segments.filter { retainedSpeakerIds.contains($0.speakerId) }
let temporalFallback = retainedSegments.min(by: { lhs, rhs in
diarizedSegmentDistance(from: segment, to: lhs)
< diarizedSegmentDistance(from: segment, to: rhs)
})?.speakerId ?? fallbackSpeakerId
return DiarizedSegment(
startTime: segment.startTime,
endTime: segment.endTime,
speakerId: temporalFallback
)
}
return compactDiarizedSpeakerIds(remapped)
}
private func encodeJSON<T: Encodable>(_ value: T) -> String {
guard let data = try? JSONEncoder().encode(value),
let string = String(data: data, encoding: .utf8)
else {
return "{}"
}
return string
}
private func waitForValue<T>(_ operation: @escaping () async -> T) -> T {
let semaphore = DispatchSemaphore(value: 0)
var result: T!
Task {
result = await operation()
semaphore.signal()
}
semaphore.wait()
return result
}
private func decodeFloatSamples(from data: Data) throws -> [Float] {
let stride = MemoryLayout<Float>.size
guard data.count.isMultiple(of: stride) else {
throw SpeechBridgeError.message("Invalid audio chunk received from native capture.")
}
let count = data.count / stride
var samples = [Float]()
samples.reserveCapacity(count)
data.withUnsafeBytes { bytes in
for index in 0..<count {
let bits = bytes.loadUnaligned(fromByteOffset: index * stride, as: UInt32.self)
samples.append(Float(bitPattern: UInt32(littleEndian: bits)))
}
}
return samples
}
private final class WAVCaptureWriter {
private let url: URL
private let sampleRate: Int
private let queue = DispatchQueue(
label: "com.johnjeong.unsigned.speech-swift.capture",
qos: .utility
)
private var fileHandle: FileHandle?
private var sampleCount = 0
private var closed = false
private var lastErrorMessage: String?
init(url: URL, sampleRate: Int = 16000) throws {
self.url = url
self.sampleRate = sampleRate
let fileManager = FileManager.default
try fileManager.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
if fileManager.fileExists(atPath: url.path) {
do {
sampleCount = try Self.existingSampleCount(at: url)
} catch {
try? fileManager.removeItem(at: url)
sampleCount = 0
}
}
if !fileManager.fileExists(atPath: url.path) {
fileManager.createFile(atPath: url.path, contents: Self.headerData(sampleRate: sampleRate, sampleCount: 0))
}
let handle = try FileHandle(forWritingTo: url)
try handle.seekToEnd()
fileHandle = handle
}
func append(_ samples: [Float]) {
guard !samples.isEmpty else {
return
}
let pcmData = Self.pcmData(from: samples)
queue.async { [self] in
guard !closed, let fileHandle else {
return
}
if lastErrorMessage != nil {
return
}
do {
try fileHandle.seekToEnd()
try fileHandle.write(contentsOf: pcmData)
sampleCount += samples.count
} catch {
lastErrorMessage = "Failed to write meeting audio: \(error.localizedDescription)"
}
}
}
func finish() throws -> String {
try queue.sync { [self] in
if closed {
return
}
if let lastErrorMessage {
throw SpeechBridgeError.message(lastErrorMessage)
}
closed = true
guard let fileHandle else {
throw SpeechBridgeError.message("Meeting audio writer is unavailable.")
}
do {
try fileHandle.seek(toOffset: 0)
try fileHandle.write(contentsOf: Self.headerData(sampleRate: sampleRate, sampleCount: sampleCount))
try fileHandle.close()
self.fileHandle = nil
} catch {
self.fileHandle = nil
throw SpeechBridgeError.message("Failed to finalize meeting audio: \(error.localizedDescription)")
}
}
return url.path
}
func cancel(removeFile: Bool) {
queue.sync { [self] in
if !closed {
closed = true
try? fileHandle?.close()
fileHandle = nil
}
}
if removeFile {
try? FileManager.default.removeItem(at: url)
}
}
private static func existingSampleCount(at url: URL) throws -> Int {
let handle = try FileHandle(forReadingFrom: url)
defer { try? handle.close() }
let header = try handle.read(upToCount: 44) ?? Data()
guard header.count >= 44,
String(data: header[0..<4], encoding: .ascii) == "RIFF",
String(data: header[8..<12], encoding: .ascii) == "WAVE",
String(data: header[36..<40], encoding: .ascii) == "data"
else {
throw SpeechBridgeError.message("Invalid WAV file at \(url.path)")
}
let dataSize = Int(header[40..<44].withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) })
return dataSize / 2
}
private static func headerData(sampleRate: Int, sampleCount: Int) -> Data {
let numChannels: UInt16 = 1
let bitsPerSample: UInt16 = 16
let bytesPerSample = Int(bitsPerSample) / 8
let dataSize = sampleCount * bytesPerSample
let fileSize = 36 + dataSize
var data = Data(capacity: fileSize + 8)
data.append(contentsOf: "RIFF".utf8)
appendUInt32(&data, UInt32(fileSize))
data.append(contentsOf: "WAVE".utf8)
data.append(contentsOf: "fmt ".utf8)
appendUInt32(&data, 16)
appendUInt16(&data, 1)
appendUInt16(&data, numChannels)
appendUInt32(&data, UInt32(sampleRate))
appendUInt32(&data, UInt32(sampleRate * Int(numChannels) * bytesPerSample))
appendUInt16(&data, numChannels * UInt16(bytesPerSample))
appendUInt16(&data, bitsPerSample)
data.append(contentsOf: "data".utf8)
appendUInt32(&data, UInt32(dataSize))
return data
}
private static func pcmData(from samples: [Float]) -> Data {
var data = Data(capacity: samples.count * 2)
for sample in samples {
let clamped = max(-1.0, min(1.0, sample))
var int16Value = Int16(clamped * 32767.0).littleEndian
data.append(Data(bytes: &int16Value, count: 2))
}
return data
}
private static func appendUInt32(_ data: inout Data, _ value: UInt32) {
var v = value.littleEndian
data.append(Data(bytes: &v, count: 4))
}
private static func appendUInt16(_ data: inout Data, _ value: UInt16) {
var v = value.littleEndian
data.append(Data(bytes: &v, count: 2))
}
}
private final class LiveTranscriptionSession {
private let captureWriter: WAVCaptureWriter
private let finalRecordingURL: URL
private let workingRecordingURL: URL
private let recordingPath: String
private let mode: ProcessingMode
private let streamingSessions: [TranscriptSource: StreamingSession]
private let stateLock = NSLock()
private let bufferLock = NSLock()
private let processingQueue = DispatchQueue(
label: "com.johnjeong.unsigned.speech-swift.processing",
qos: .userInitiated
)
private var processingTimer: DispatchSourceTimer?
private var bufferedSamplesBySource: [TranscriptSource: [Float]] = [:]
private var finalizedEntries: [TranscriptEntryPayload] = []
private var partialTexts: [TranscriptSource: String] = [:]
private var running = false
private var acceptingInput = false
private var errorMessage: String?
init(
mode: ProcessingMode,
recordingURL: URL,
streamingModel: ParakeetStreamingASRModel? = nil
) throws {
self.mode = mode
finalRecordingURL = recordingURL
workingRecordingURL = Self.workingRecordingURL(for: recordingURL)
recordingPath = recordingURL.path
try Self.prepareWorkingRecording(at: workingRecordingURL, from: finalRecordingURL)
captureWriter = try WAVCaptureWriter(url: workingRecordingURL)
if let streamingModel {
streamingSessions = [
.microphone: try streamingModel.createSession(),
.system: try streamingModel.createSession(),
]
} else {
streamingSessions = [:]
}
}
func start() throws {
if !streamingSessions.isEmpty {
let timer = DispatchSource.makeTimerSource(queue: processingQueue)
timer.schedule(deadline: .now(), repeating: .milliseconds(250))
timer.setEventHandler { [weak self] in
self?.processBufferedSamples()
}
timer.resume()
processingTimer = timer
}
stateLock.lock()
running = true
acceptingInput = true
errorMessage = nil
stateLock.unlock()
}
func snapshot() -> TranscriptionPayload {
stateLock.lock()
defer { stateLock.unlock() }
let entries = snapshotEntriesLocked()
return TranscriptionPayload(
running: running,
text: transcriptText(from: entries),
error: errorMessage,
entries: entries,
audioPath: recordingPath,
mode: mode.rawValue
)
}
func stop() throws -> TranscriptionPayload {
stateLock.lock()
let wasRunning = running
running = false
acceptingInput = false
stateLock.unlock()
let timer = processingTimer
processingTimer = nil
timer?.cancel()
if wasRunning && !streamingSessions.isEmpty {
processingQueue.sync {
processBufferedSamples()
finalizeStreamingSession()
}
}
_ = try captureWriter.finish()
try Self.encodeWorkingRecording(from: workingRecordingURL, to: finalRecordingURL)
try? FileManager.default.removeItem(at: workingRecordingURL)
let snapshot = snapshot()
return TranscriptionPayload(
running: false,
text: snapshot.text,
error: snapshot.error,
entries: snapshot.entries,
audioPath: finalRecordingURL.path,
mode: mode.rawValue
)
}
func cancel(removeRecording: Bool) {
stateLock.lock()
running = false
acceptingInput = false
stateLock.unlock()
let timer = processingTimer
processingTimer = nil