|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+import Foundation
|
|
|
2
|
+import AVFoundation
|
|
|
3
|
+import Speech
|
|
|
4
|
+
|
|
|
5
|
+/// A single piece of transcript text attributed to a channel and a time range
|
|
|
6
|
+/// (offsets are in seconds from the start of the recording).
|
|
|
7
|
+struct TranscriptSegment: Codable, Hashable {
|
|
|
8
|
+ let speaker: String
|
|
|
9
|
+ let startOffset: TimeInterval
|
|
|
10
|
+ let endOffset: TimeInterval
|
|
|
11
|
+ let text: String
|
|
|
12
|
+}
|
|
|
13
|
+
|
|
|
14
|
+/// Logical speaker labels used when merging per-channel transcripts.
|
|
|
15
|
+enum TranscriptSpeaker: String {
|
|
|
16
|
+ case microphone = "You"
|
|
|
17
|
+ case system = "Meeting"
|
|
|
18
|
+}
|
|
|
19
|
+
|
|
|
20
|
+/// Progress snapshot for UI status updates.
|
|
|
21
|
+struct MeetingTranscriptionProgress: Sendable {
|
|
|
22
|
+ let totalChunks: Int
|
|
|
23
|
+ let completedChunks: Int
|
|
|
24
|
+}
|
|
|
25
|
+
|
|
|
26
|
+enum MeetingTranscriptionError: Error, LocalizedError {
|
|
|
27
|
+ case authorizationDenied
|
|
|
28
|
+ case authorizationRestricted
|
|
|
29
|
+ case recognizerUnavailable(locale: String)
|
|
|
30
|
+ case noAudioToTranscribe
|
|
|
31
|
+
|
|
|
32
|
+ var errorDescription: String? {
|
|
|
33
|
+ switch self {
|
|
|
34
|
+ case .authorizationDenied:
|
|
|
35
|
+ return "Speech recognition permission denied. Enable it in System Settings and try again."
|
|
|
36
|
+ case .authorizationRestricted:
|
|
|
37
|
+ return "Speech recognition is restricted on this Mac."
|
|
|
38
|
+ case .recognizerUnavailable(let locale):
|
|
|
39
|
+ return "Speech recognizer is unavailable for \(locale)."
|
|
|
40
|
+ case .noAudioToTranscribe:
|
|
|
41
|
+ return "No audio was available to transcribe."
|
|
|
42
|
+ }
|
|
|
43
|
+ }
|
|
|
44
|
+}
|
|
|
45
|
+
|
|
|
46
|
+/// Transcribes meeting audio by running Apple Speech on per-channel files
|
|
|
47
|
+/// in fixed-size chunks, falling back across a list of locales per chunk.
|
|
|
48
|
+final class MeetingTranscriptionService {
|
|
|
49
|
+ private struct ChunkPlan {
|
|
|
50
|
+ let index: Int
|
|
|
51
|
+ let startFrame: AVAudioFramePosition
|
|
|
52
|
+ let frameCount: AVAudioFrameCount
|
|
|
53
|
+ let startOffset: TimeInterval
|
|
|
54
|
+ let endOffset: TimeInterval
|
|
|
55
|
+ }
|
|
|
56
|
+
|
|
|
57
|
+ /// Shared progress counter used across concurrent channels.
|
|
|
58
|
+ private actor ProgressCounter {
|
|
|
59
|
+ private let total: Int
|
|
|
60
|
+ private var completed: Int = 0
|
|
|
61
|
+ private let onProgress: (@Sendable (MeetingTranscriptionProgress) -> Void)?
|
|
|
62
|
+
|
|
|
63
|
+ init(total: Int, onProgress: (@Sendable (MeetingTranscriptionProgress) -> Void)?) {
|
|
|
64
|
+ self.total = total
|
|
|
65
|
+ self.onProgress = onProgress
|
|
|
66
|
+ }
|
|
|
67
|
+
|
|
|
68
|
+ func emitInitial() {
|
|
|
69
|
+ onProgress?(MeetingTranscriptionProgress(totalChunks: total, completedChunks: 0))
|
|
|
70
|
+ }
|
|
|
71
|
+
|
|
|
72
|
+ func increment() {
|
|
|
73
|
+ completed += 1
|
|
|
74
|
+ onProgress?(MeetingTranscriptionProgress(totalChunks: total, completedChunks: completed))
|
|
|
75
|
+ }
|
|
|
76
|
+ }
|
|
|
77
|
+
|
|
|
78
|
+ func requestAuthorization() async throws {
|
|
|
79
|
+ switch SFSpeechRecognizer.authorizationStatus() {
|
|
|
80
|
+ case .authorized:
|
|
|
81
|
+ return
|
|
|
82
|
+ case .notDetermined:
|
|
|
83
|
+ let status: SFSpeechRecognizerAuthorizationStatus = await withCheckedContinuation { continuation in
|
|
|
84
|
+ SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) }
|
|
|
85
|
+ }
|
|
|
86
|
+ guard status == .authorized else { throw MeetingTranscriptionError.authorizationDenied }
|
|
|
87
|
+ case .denied:
|
|
|
88
|
+ throw MeetingTranscriptionError.authorizationDenied
|
|
|
89
|
+ case .restricted:
|
|
|
90
|
+ throw MeetingTranscriptionError.authorizationRestricted
|
|
|
91
|
+ @unknown default:
|
|
|
92
|
+ throw MeetingTranscriptionError.authorizationDenied
|
|
|
93
|
+ }
|
|
|
94
|
+ }
|
|
|
95
|
+
|
|
|
96
|
+ /// Transcribes the mic and system channel audio (either may be nil) and
|
|
|
97
|
+ /// returns a flat, time-ordered list of transcript segments labeled with
|
|
|
98
|
+ /// the speaker channel.
|
|
|
99
|
+ func transcribeMeeting(
|
|
|
100
|
+ micURL: URL?,
|
|
|
101
|
+ systemURL: URL?,
|
|
|
102
|
+ chunkSeconds: TimeInterval = 30,
|
|
|
103
|
+ overlapSeconds: TimeInterval = 0,
|
|
|
104
|
+ locales: [Locale] = [Locale(identifier: "en-US")],
|
|
|
105
|
+ onProgress: (@Sendable (MeetingTranscriptionProgress) -> Void)? = nil
|
|
|
106
|
+ ) async throws -> [TranscriptSegment] {
|
|
|
107
|
+ try await requestAuthorization()
|
|
|
108
|
+
|
|
|
109
|
+ let micPlan: (URL, [ChunkPlan])? = try micURL.flatMap { url -> (URL, [ChunkPlan])? in
|
|
|
110
|
+ guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
|
|
111
|
+ let chunks = try planChunks(for: url, chunkSeconds: chunkSeconds, overlapSeconds: overlapSeconds)
|
|
|
112
|
+ return chunks.isEmpty ? nil : (url, chunks)
|
|
|
113
|
+ }
|
|
|
114
|
+ let systemPlan: (URL, [ChunkPlan])? = try systemURL.flatMap { url -> (URL, [ChunkPlan])? in
|
|
|
115
|
+ guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
|
|
116
|
+ let chunks = try planChunks(for: url, chunkSeconds: chunkSeconds, overlapSeconds: overlapSeconds)
|
|
|
117
|
+ return chunks.isEmpty ? nil : (url, chunks)
|
|
|
118
|
+ }
|
|
|
119
|
+
|
|
|
120
|
+ let totalChunks = (micPlan?.1.count ?? 0) + (systemPlan?.1.count ?? 0)
|
|
|
121
|
+ guard totalChunks > 0 else {
|
|
|
122
|
+ throw MeetingTranscriptionError.noAudioToTranscribe
|
|
|
123
|
+ }
|
|
|
124
|
+
|
|
|
125
|
+ let counter = ProgressCounter(total: totalChunks, onProgress: onProgress)
|
|
|
126
|
+ await counter.emitInitial()
|
|
|
127
|
+
|
|
|
128
|
+ let effectiveLocales = locales.isEmpty ? [Locale(identifier: "en-US")] : locales
|
|
|
129
|
+
|
|
|
130
|
+ async let micSegments: [TranscriptSegment] = {
|
|
|
131
|
+ guard let plan = micPlan else { return [] }
|
|
|
132
|
+ return try await self.transcribeChannel(
|
|
|
133
|
+ url: plan.0,
|
|
|
134
|
+ chunks: plan.1,
|
|
|
135
|
+ speaker: .microphone,
|
|
|
136
|
+ locales: effectiveLocales,
|
|
|
137
|
+ counter: counter
|
|
|
138
|
+ )
|
|
|
139
|
+ }()
|
|
|
140
|
+ async let systemSegments: [TranscriptSegment] = {
|
|
|
141
|
+ guard let plan = systemPlan else { return [] }
|
|
|
142
|
+ return try await self.transcribeChannel(
|
|
|
143
|
+ url: plan.0,
|
|
|
144
|
+ chunks: plan.1,
|
|
|
145
|
+ speaker: .system,
|
|
|
146
|
+ locales: effectiveLocales,
|
|
|
147
|
+ counter: counter
|
|
|
148
|
+ )
|
|
|
149
|
+ }()
|
|
|
150
|
+
|
|
|
151
|
+ let combined = try await micSegments + systemSegments
|
|
|
152
|
+ return combined
|
|
|
153
|
+ .filter { $0.text.isEmpty == false }
|
|
|
154
|
+ .sorted { $0.startOffset < $1.startOffset }
|
|
|
155
|
+ }
|
|
|
156
|
+
|
|
|
157
|
+ // MARK: - Chunk planning
|
|
|
158
|
+
|
|
|
159
|
+ private func planChunks(for url: URL, chunkSeconds: TimeInterval, overlapSeconds: TimeInterval) throws -> [ChunkPlan] {
|
|
|
160
|
+ let audioFile = try AVAudioFile(forReading: url)
|
|
|
161
|
+ let sampleRate = audioFile.processingFormat.sampleRate
|
|
|
162
|
+ guard sampleRate > 0 else { return [] }
|
|
|
163
|
+ let totalFrames = audioFile.length
|
|
|
164
|
+ guard totalFrames > 0 else { return [] }
|
|
|
165
|
+
|
|
|
166
|
+ let chunkSamples = AVAudioFramePosition(max(1, chunkSeconds * sampleRate))
|
|
|
167
|
+ let overlapSamples = AVAudioFramePosition(max(0, overlapSeconds * sampleRate))
|
|
|
168
|
+ let step = max(AVAudioFramePosition(1), chunkSamples - overlapSamples)
|
|
|
169
|
+
|
|
|
170
|
+ var plans: [ChunkPlan] = []
|
|
|
171
|
+ var start: AVAudioFramePosition = 0
|
|
|
172
|
+ var index = 0
|
|
|
173
|
+ while start < totalFrames {
|
|
|
174
|
+ let end = min(start + chunkSamples, totalFrames)
|
|
|
175
|
+ let frameCount = AVAudioFrameCount(end - start)
|
|
|
176
|
+ let startOffset = Double(start) / sampleRate
|
|
|
177
|
+ let endOffset = Double(end) / sampleRate
|
|
|
178
|
+ plans.append(ChunkPlan(
|
|
|
179
|
+ index: index,
|
|
|
180
|
+ startFrame: start,
|
|
|
181
|
+ frameCount: frameCount,
|
|
|
182
|
+ startOffset: startOffset,
|
|
|
183
|
+ endOffset: endOffset
|
|
|
184
|
+ ))
|
|
|
185
|
+ index += 1
|
|
|
186
|
+ if end >= totalFrames { break }
|
|
|
187
|
+ start += step
|
|
|
188
|
+ }
|
|
|
189
|
+ return plans
|
|
|
190
|
+ }
|
|
|
191
|
+
|
|
|
192
|
+ // MARK: - Per-channel transcription
|
|
|
193
|
+
|
|
|
194
|
+ private func transcribeChannel(
|
|
|
195
|
+ url: URL,
|
|
|
196
|
+ chunks: [ChunkPlan],
|
|
|
197
|
+ speaker: TranscriptSpeaker,
|
|
|
198
|
+ locales: [Locale],
|
|
|
199
|
+ counter: ProgressCounter
|
|
|
200
|
+ ) async throws -> [TranscriptSegment] {
|
|
|
201
|
+ var segments: [TranscriptSegment] = []
|
|
|
202
|
+ segments.reserveCapacity(chunks.count)
|
|
|
203
|
+
|
|
|
204
|
+ for plan in chunks {
|
|
|
205
|
+ try Task.checkCancellation()
|
|
|
206
|
+ let buffer = try readChunkBuffer(url: url, startFrame: plan.startFrame, frameCount: plan.frameCount)
|
|
|
207
|
+ let text = await transcribeBufferWithLocaleFallback(buffer: buffer, locales: locales)
|
|
|
208
|
+ await counter.increment()
|
|
|
209
|
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
210
|
+ if trimmed.isEmpty { continue }
|
|
|
211
|
+ segments.append(TranscriptSegment(
|
|
|
212
|
+ speaker: speaker.rawValue,
|
|
|
213
|
+ startOffset: plan.startOffset,
|
|
|
214
|
+ endOffset: plan.endOffset,
|
|
|
215
|
+ text: trimmed
|
|
|
216
|
+ ))
|
|
|
217
|
+ }
|
|
|
218
|
+ return segments
|
|
|
219
|
+ }
|
|
|
220
|
+
|
|
|
221
|
+ private func readChunkBuffer(url: URL, startFrame: AVAudioFramePosition, frameCount: AVAudioFrameCount) throws -> AVAudioPCMBuffer {
|
|
|
222
|
+ let audioFile = try AVAudioFile(forReading: url)
|
|
|
223
|
+ audioFile.framePosition = startFrame
|
|
|
224
|
+ guard let buffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: frameCount) else {
|
|
|
225
|
+ throw NSError(domain: "MeetingTranscriptionService", code: 1, userInfo: [NSLocalizedDescriptionKey: "Unable to allocate audio buffer."])
|
|
|
226
|
+ }
|
|
|
227
|
+ try audioFile.read(into: buffer, frameCount: frameCount)
|
|
|
228
|
+ return buffer
|
|
|
229
|
+ }
|
|
|
230
|
+
|
|
|
231
|
+ private func transcribeBufferWithLocaleFallback(buffer: AVAudioPCMBuffer, locales: [Locale]) async -> String {
|
|
|
232
|
+ for locale in locales {
|
|
|
233
|
+ guard let recognizer = SFSpeechRecognizer(locale: locale), recognizer.isAvailable else { continue }
|
|
|
234
|
+ do {
|
|
|
235
|
+ let text = try await transcribeBuffer(buffer: buffer, recognizer: recognizer)
|
|
|
236
|
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
237
|
+ if trimmed.isEmpty == false { return trimmed }
|
|
|
238
|
+ } catch {
|
|
|
239
|
+ // One transient retry before moving on to the next locale.
|
|
|
240
|
+ try? await Task.sleep(nanoseconds: 500_000_000)
|
|
|
241
|
+ if let text = try? await transcribeBuffer(buffer: buffer, recognizer: recognizer) {
|
|
|
242
|
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
243
|
+ if trimmed.isEmpty == false { return trimmed }
|
|
|
244
|
+ }
|
|
|
245
|
+ continue
|
|
|
246
|
+ }
|
|
|
247
|
+ }
|
|
|
248
|
+ return ""
|
|
|
249
|
+ }
|
|
|
250
|
+
|
|
|
251
|
+ private func transcribeBuffer(buffer: AVAudioPCMBuffer, recognizer: SFSpeechRecognizer) async throws -> String {
|
|
|
252
|
+ let request = SFSpeechAudioBufferRecognitionRequest()
|
|
|
253
|
+ request.shouldReportPartialResults = false
|
|
|
254
|
+ if #available(macOS 13.0, *) {
|
|
|
255
|
+ request.addsPunctuation = true
|
|
|
256
|
+ }
|
|
|
257
|
+
|
|
|
258
|
+ return try await withCheckedThrowingContinuation { continuation in
|
|
|
259
|
+ var hasResumed = false
|
|
|
260
|
+ let lock = NSLock()
|
|
|
261
|
+ func resumeOnce(with result: Result<String, Error>) {
|
|
|
262
|
+ lock.lock()
|
|
|
263
|
+ defer { lock.unlock() }
|
|
|
264
|
+ if hasResumed { return }
|
|
|
265
|
+ hasResumed = true
|
|
|
266
|
+ switch result {
|
|
|
267
|
+ case .success(let text):
|
|
|
268
|
+ continuation.resume(returning: text)
|
|
|
269
|
+ case .failure(let error):
|
|
|
270
|
+ continuation.resume(throwing: error)
|
|
|
271
|
+ }
|
|
|
272
|
+ }
|
|
|
273
|
+
|
|
|
274
|
+ let task = recognizer.recognitionTask(with: request) { result, error in
|
|
|
275
|
+ if let error {
|
|
|
276
|
+ let nsError = error as NSError
|
|
|
277
|
+ // "No speech detected" is a normal empty-chunk outcome (code 203 in kafAssistant domain).
|
|
|
278
|
+ if nsError.domain == "kAFAssistantErrorDomain" && (nsError.code == 203 || nsError.code == 1110) {
|
|
|
279
|
+ resumeOnce(with: .success(""))
|
|
|
280
|
+ return
|
|
|
281
|
+ }
|
|
|
282
|
+ resumeOnce(with: .failure(error))
|
|
|
283
|
+ return
|
|
|
284
|
+ }
|
|
|
285
|
+ if let result, result.isFinal {
|
|
|
286
|
+ resumeOnce(with: .success(result.bestTranscription.formattedString))
|
|
|
287
|
+ }
|
|
|
288
|
+ }
|
|
|
289
|
+
|
|
|
290
|
+ request.append(buffer)
|
|
|
291
|
+ request.endAudio()
|
|
|
292
|
+ _ = task
|
|
|
293
|
+ }
|
|
|
294
|
+ }
|
|
|
295
|
+}
|
|
|
296
|
+
|
|
|
297
|
+extension Array where Element == TranscriptSegment {
|
|
|
298
|
+ /// Renders segments as a human-readable timeline like:
|
|
|
299
|
+ /// `[00:12] You: Hello everyone.`
|
|
|
300
|
+ func renderedTimelineText() -> String {
|
|
|
301
|
+ let formatter: (TimeInterval) -> String = { seconds in
|
|
|
302
|
+ let total = Int(seconds.rounded(.down))
|
|
|
303
|
+ let h = total / 3600
|
|
|
304
|
+ let m = (total % 3600) / 60
|
|
|
305
|
+ let s = total % 60
|
|
|
306
|
+ if h > 0 {
|
|
|
307
|
+ return String(format: "%02d:%02d:%02d", h, m, s)
|
|
|
308
|
+ }
|
|
|
309
|
+ return String(format: "%02d:%02d", m, s)
|
|
|
310
|
+ }
|
|
|
311
|
+ return self.map { segment in
|
|
|
312
|
+ "[\(formatter(segment.startOffset))] \(segment.speaker): \(segment.text)"
|
|
|
313
|
+ }.joined(separator: "\n")
|
|
|
314
|
+ }
|
|
|
315
|
+}
|