Branchwell

Jotley / app · jotley.ai / Shared / Services / TranscriptionService.swift

1import Foundation
2import Speech
3import AVFoundation
4import CoreMedia
5import FoundationModels
6
7enum CustomSpeechWords {
8 static let defaultsKey = "jotley.customSpeechWords.v1"
9 static let limit = 100
10 static let entryLengthLimit = 100
11
12 static func key(for entry: String) -> String {
13 entry.folding(options: [.caseInsensitive], locale: Locale(identifier: "en_US_POSIX"))
14 }
15
16 static func entries(in text: String) -> [String] {
17 var seen = Set<String>()
18 return text.components(separatedBy: .newlines)
19 .map { $0.split(whereSeparator: \.isWhitespace).joined(separator: " ") }
20 .filter { !$0.isEmpty && seen.insert(key(for: $0)).inserted }
21 }
22
23 static var saved: [String] { saved(in: .standard) }
24
25 static func saved(in defaults: UserDefaults) -> [String] {
26 Array(entries(in: defaults.string(forKey: defaultsKey) ?? "").prefix(limit))
27 }
28
29 static func importedEntries(in text: String, fileExtension: String) throws -> [String] {
30 let separators: Set<Character>
31 switch fileExtension.lowercased() {
32 case "csv": separators = [","]
33 case "tsv": separators = ["\t"]
34 default: separators = [",", ";", "\t"]
35 }
36 var fields: [String] = []
37 var field = ""
38 var quoted = false
39 var index = text.startIndex
40 if index < text.endIndex, text[index] == "\u{FEFF}" { text.formIndex(after: &index) }
41 while index < text.endIndex {
42 let character = text[index]
43 text.formIndex(after: &index)
44 if quoted {
45 if character == "\"" {
46 if index < text.endIndex, text[index] == "\"" {
47 field.append(character)
48 text.formIndex(after: &index)
49 } else { quoted = false }
50 } else { field.append(character) }
51 } else if separators.contains(character) || character.isNewline {
52 fields.append(field.split(whereSeparator: \.isWhitespace).joined(separator: " "))
53 field = ""
54 } else if character == "\"", field.allSatisfy(\.isWhitespace) {
55 quoted = true
56 } else { field.append(character) }
57 }
58 guard !quoted else { throw LocalError.message("A quoted entry is missing its closing quote.") }
59 fields.append(field.split(whereSeparator: \.isWhitespace).joined(separator: " "))
60 return entries(in: fields.joined(separator: "\n"))
61 }
62}
63
64@available(macOS 26.0, iOS 26.0, *)
65public enum LocalSpeech {
66 public enum Engine: String, Sendable { case speech = "SpeechTranscriber", dictation = "DictationTranscriber" }
67 public struct Configuration: Sendable {
68 public let module: any SpeechModule
69 public let engine: Engine
70 public let locale: Locale
71 }
72 public struct Language: Identifiable, Sendable {
73 public let id: String
74 public var name: String { Locale.current.localizedString(forIdentifier: LocalSpeech.languageKey(for: Locale(identifier: id)) ?? id) ?? id }
75 }
76 public struct Readiness: Sendable {
77 public enum Status: Sendable { case unsupported, downloading, supported, installed }
78 public let configuration: Configuration?
79 public let status: Status
80 public let details: String
81 init(configuration: Configuration?, status: AssetInventory.Status, details: String = "") {
82 self.configuration = configuration
83 self.details = details
84 switch status {
85 case .installed: self.status = .installed
86 case .supported: self.status = .supported
87 case .downloading: self.status = .downloading
88 case .unsupported: self.status = .unsupported
89 @unknown default: self.status = .unsupported
90 }
91 }
92 public var needsSetup: Bool { configuration != nil && status != .installed }
93 var customWordsStatus: String? {
94 guard !CustomSpeechWords.saved.isEmpty else { return nil }
95 if configuration?.engine != .dictation {
96 return "Custom Words are unavailable for this language on this device. Standard transcription can still run."
97 }
98 return status == .installed ? "Custom Words are ready for new transcription sessions."
99 : "Choose Set Up On-Device Speech to enable Custom Words. Existing speech models can still be used while you wait."
100 }
101 public var message: String {
102 if status == .installed { return "On-device speech is ready. Transcription works offline." }
103 if needsSetup {
104 return "The Apple speech model for this language needs setup. Open Settings and choose Set Up On-Device Speech. Apple Intelligence uses a separate model."
105 }
106 return "Transcription is unavailable for the selected language on this device. Choose a supported Apple Intelligence language in Settings, or refresh speech availability."
107 }
108 }
109 // Prefer an installed fallback over downloading a better engine. Otherwise
110 // explicit setup selects SpeechTranscriber before DictationTranscriber.
111 static func preferredIndex(statuses: [AssetInventory.Status]) -> Int? {
112 statuses.firstIndex(of: .installed) ?? statuses.firstIndex(where: { $0 == .supported || $0 == .downloading }) ?? statuses.indices.first
113 }
114 static func exactLocale(_ requested: Locale, in supported: [Locale]) -> Locale? {
115 supported.first { $0.language.maximalIdentifier == requested.language.maximalIdentifier }
116 }
117 public static func languages() async -> [Language] {
118 let speech = await SpeechTranscriber.supportedLocales
119 let dictation = await DictationTranscriber.supportedLocales
120 return languages(speechLocales: speech + dictation, supportsLocale: SystemLanguageModel.default.supportsLocale)
121 }
122 // Apple's 16 published Intelligence languages, with Chinese scripts kept distinct.
123 // The runtime model and on-device speech inventory must both support a choice.
124 // Regional speech variants are implementations of a language, not extra choices.
125 static let intelligenceLanguageKeys: Set<String> = [
126 "en", "da", "nl", "fr", "de", "it", "nb", "pt", "es", "sv", "tr",
127 "zh-Hans", "zh-Hant", "ja", "ko", "vi"
128 ]
129 static func languageKey(for locale: Locale) -> String? {
130 guard let code = locale.language.languageCode?.identifier else { return nil }
131 let key = code == "zh" ? "zh-\(locale.language.script?.identifier ?? "")" : code
132 return intelligenceLanguageKeys.contains(key) ? key : nil
133 }
134 static func languages(speechLocales: [Locale], preferredLocale: Locale = .current,
135 supportsLocale: (Locale) -> Bool) -> [Language] {
136 let supported = speechLocales.filter { languageKey(for: $0) != nil && supportsLocale($0) }
137 let groups = Dictionary(grouping: supported) { languageKey(for: $0)! }
138 return groups.compactMap { key, locales in
139 let defaultLocale = Locale(identifier: Locale(identifier: key).language.maximalIdentifier)
140 let preferred = languageKey(for: preferredLocale) == key ? preferredLocale : defaultLocale
141 let selected = exactLocale(preferred, in: locales) ?? exactLocale(defaultLocale, in: locales)
142 ?? locales.sorted { $0.identifier(.bcp47) < $1.identifier(.bcp47) }.first
143 return selected.map { Language(id: $0.identifier(.bcp47)) }
144 }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
145 }
146 /// Normalize older regional choices, without silently changing an unsupported language.
147 public static func selectedLanguage(locale: Locale, in languages: [Language]) -> Language? {
148 guard let key = languageKey(for: locale) else { return nil }
149 return languages.first { languageKey(for: Locale(identifier: $0.id)) == key }
150 }
151 static func supportsIntelligence(locale: Locale) -> Bool {
152 languageKey(for: locale) != nil && SystemLanguageModel.default.supportsLocale(locale)
153 }
154 /// A local availability check only: never initiates an installation or download.
155 public static func readiness(locale: Locale, checkingCustomWordsSetup: Bool = false) async -> Readiness {
156 let wantsCustomWords = !CustomSpeechWords.saved.isEmpty
157 guard supportsIntelligence(locale: locale) else {
158 return .init(configuration: nil, status: .unsupported,
159 details: "Requested language: \(locale.identifier(.bcp47))\nNot supported by Apple Intelligence. Choose a supported language in Settings.")
160 }
161 var candidates: [(Configuration, AssetInventory.Status)] = []
162 let speechAvailable = SpeechTranscriber.isAvailable
163 let speechLocales = await SpeechTranscriber.supportedLocales
164 let dictationLocales = await DictationTranscriber.supportedLocales
165 var speechEquivalent = exactLocale(locale, in: speechLocales)
166 var dictationEquivalent = exactLocale(locale, in: dictationLocales)
167 if speechAvailable && speechEquivalent == nil {
168 speechEquivalent = await SpeechTranscriber.supportedLocale(equivalentTo: locale)
169 }
170 if dictationEquivalent == nil {
171 dictationEquivalent = await DictationTranscriber.supportedLocale(equivalentTo: locale)
172 }
173 var details = ["Requested language: \(locale.identifier(.bcp47))",
174 "SpeechTranscriber available: \(speechAvailable)",
175 "SpeechTranscriber languages: \(speechLocales.map { $0.identifier(.bcp47) }.sorted().joined(separator: ", "))",
176 "DictationTranscriber languages: \(dictationLocales.map { $0.identifier(.bcp47) }.sorted().joined(separator: ", "))"]
177 if speechAvailable, let equivalent = speechEquivalent, supportsIntelligence(locale: equivalent) {
178 let module = SpeechTranscriber(locale: equivalent, preset: .timeIndexedProgressiveTranscription)
179 let status = await AssetInventory.status(forModules: [module])
180 candidates.append((.init(module: module, engine: .speech, locale: equivalent), status))
181 details.append("SpeechTranscriber \(equivalent.identifier(.bcp47)): \(status)")
182 }
183 if let equivalent = dictationEquivalent, supportsIntelligence(locale: equivalent) {
184 let module = DictationTranscriber(locale: equivalent, contentHints: [],
185 transcriptionOptions: [.punctuation], reportingOptions: [.volatileResults], attributeOptions: [.audioTimeRange])
186 let status = await AssetInventory.status(forModules: [module])
187 candidates.append((.init(module: module, engine: .dictation, locale: equivalent), status))
188 details.append("DictationTranscriber \(equivalent.identifier(.bcp47)): \(status)")
189 }
190 for index in candidates.indices where candidates[index].1 == .installed {
191 let config = candidates[index].0
192 let formats = await config.module.availableCompatibleAudioFormats
193 details.append("\(config.engine.rawValue) usable audio formats: \(formats)")
194 if formats.isEmpty {
195 // Asset inventory alone can report installed while the engine
196 // cannot analyze audio. Keep explicit setup available and prefer
197 // another usable installed engine over this incomplete one.
198 candidates[index].1 = .supported
199 details.append("\(config.engine.rawValue) assets reported installed, but no usable audio format is exposed; setup is still required.")
200 }
201 }
202 let customIndex = wantsCustomWords ? candidates.firstIndex { config, status in
203 config.engine == .dictation && (status == .installed ||
204 (checkingCustomWordsSetup && (status == .supported || status == .downloading)))
205 } : nil
206 guard let index = customIndex ?? preferredIndex(statuses: candidates.map(\.1)) else {
207 return .init(configuration: nil, status: .unsupported, details: details.joined(separator: "\n"))
208 }
209 return .init(configuration: candidates[index].0, status: candidates[index].1, details: details.joined(separator: "\n"))
210 }
211 static func configuration(from ready: Readiness) throws -> Configuration {
212 guard ready.status == .installed, let config = ready.configuration else {
213 throw LocalError.message(ready.message)
214 }
215 return config
216 }
217 public static func configuration(locale: Locale) async throws -> Configuration {
218 // Use exactly the same canonical locale and engine selection as Settings.
219 // A separate equivalent-locale lookup can disagree with explicit setup.
220 let ready = await readiness(locale: locale)
221 do {
222 guard let config = ready.configuration else { throw LocalError.message(ready.message) }
223 // Reassert local asset ownership whenever speech is used. Reservation
224 // does not install/download assets; only explicit setUp can do that.
225 try await AssetInventory.reserve(locale: config.locale)
226 let status = await AssetInventory.status(forModules: [config.module])
227 return try configuration(from: .init(configuration: config, status: status, details: ready.details))
228 } catch {
229 recordFailure(error, locale: locale, details: ready.details)
230 throw error
231 }
232 }
233 public static let lastFailureDefaultsKey = "localSpeechLastFailure"
234 static func recordFailure(_ error: Error, locale: Locale, details: String = "") {
235 guard !(error is CancellationError) else { return }
236 let failure = error as NSError
237 UserDefaults.standard.set("\(Date().formatted(.iso8601)) · \(locale.identifier(.bcp47))\n\(failure.localizedDescription) (\(failure.domain), \(failure.code))\n\(details)", forKey: lastFailureDefaultsKey)
238 }
239 static func prepare(configuration: Configuration, customWords: [String] = CustomSpeechWords.saved) async throws -> (SpeechAnalyzer, AVAudioFormat) {
240 guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [configuration.module]) else {
241 throw LocalError.message("No compatible on-device speech audio format.")
242 }
243 let analyzer = SpeechAnalyzer(modules: [configuration.module])
244 do {
245 if configuration.engine == .dictation, !customWords.isEmpty {
246 let context = AnalysisContext()
247 context.contextualStrings[.general] = Array(customWords.prefix(CustomSpeechWords.limit))
248 try await analyzer.setContext(context)
249 }
250 try await analyzer.prepareToAnalyze(in: format)
251 try Task.checkCancellation()
252 return (analyzer, format)
253 } catch {
254 await analyzer.cancelAndFinishNow()
255 throw error
256 }
257 }
258 /// Invoked only by the user's explicit Settings action. Apple's shared asset
259 /// installation needs connectivity; audio and transcription stay on-device.
260 public static func setUp(locale: Locale,
261 progress: @escaping @Sendable (Double) async -> Void) async throws {
262 try Task.checkCancellation()
263 let ready = await readiness(locale: locale, checkingCustomWordsSetup: true)
264 guard let config = ready.configuration else { throw LocalError.message(ready.message) }
265 try Task.checkCancellation()
266 // Reserve even preinstalled assets so Apple knows this app uses them.
267 try await AssetInventory.reserve(locale: config.locale)
268 // Recheck after reservation rather than rejecting a supported locale based
269 // on its pre-reservation inventory status. The request returns nil if ready.
270 if let request = try await AssetInventory.assetInstallationRequest(supporting: [config.module]) {
271 let reporter = Task {
272 while !Task.isCancelled {
273 await progress(request.progress.fractionCompleted)
274 do { try await Task.sleep(for: .milliseconds(250)) } catch { break }
275 }
276 }
277 defer { reporter.cancel() }
278 try await withTaskCancellationHandler {
279 try Task.checkCancellation()
280 try await request.downloadAndInstall()
281 } onCancel: { request.progress.cancel() }
282 }
283 try Task.checkCancellation()
284 guard await AssetInventory.status(forModules: [config.module]) == .installed else {
285 throw LocalError.message("Apple has not finished installing this language's speech model. Connect to the internet and try Set Up On-Device Speech again.")
286 }
287 // A successful asset request is not sufficient: verify the same analyzer
288 // preparation that live recording uses before presenting speech as ready.
289 let verified = try await configuration(locale: locale)
290 do {
291 let (analyzer, _) = try await prepare(configuration: verified)
292 await analyzer.cancelAndFinishNow()
293 } catch {
294 recordFailure(error, locale: locale, details: "Setup verification: \(verified.engine.rawValue) \(verified.locale.identifier(.bcp47))")
295 throw error
296 }
297 UserDefaults.standard.removeObject(forKey: lastFailureDefaultsKey)
298 await progress(1)
299 }
300}
301
302/// Receives microphone/system audio while it is being captured. Only already-installed
303/// on-device assets are used; explicit setup lives separately in Settings.
304/// Audio is only held in memory while it is analyzed; it is never written to disk.
305@available(macOS 26.0, iOS 26.0, *)
306public final class LiveSpeechSession: @unchecked Sendable {
307 private let analyzer: SpeechAnalyzer
308 private let format: AVAudioFormat
309 private let continuation: AsyncStream<AnalyzerInput>.Continuation
310 private let analysis: Task<Void, Error>
311 private let results: Task<LocalTranscript, Error>
312 private let lock = NSLock()
313 private var converter: AVAudioConverter?
314 private var inputRate: Double = 0
315 private var conversionError: Error?
316 private let failure: (@Sendable (Error) -> Void)?
317
318 private init(analyzer: SpeechAnalyzer, format: AVAudioFormat,
319 continuation: AsyncStream<AnalyzerInput>.Continuation,
320 analysis: Task<Void, Error>, results: Task<LocalTranscript, Error>,
321 failure: (@Sendable (Error) -> Void)?) {
322 self.analyzer = analyzer; self.format = format; self.continuation = continuation
323 self.analysis = analysis; self.results = results; self.failure = failure
324 }
325 public static func start(locale: Locale,
326 failure: (@Sendable (Error) -> Void)? = nil,
327 snapshot: @escaping @Sendable (LocalTranscript) async -> Void) async throws -> LiveSpeechSession {
328 let config = try await LocalSpeech.configuration(locale: locale)
329 let analyzer: SpeechAnalyzer
330 let format: AVAudioFormat
331 do {
332 (analyzer, format) = try await LocalSpeech.prepare(configuration: config)
333 } catch {
334 LocalSpeech.recordFailure(error, locale: locale, details: "Transcription: \(config.engine.rawValue) \(config.locale.identifier(.bcp47))")
335 throw error
336 }
337 UserDefaults.standard.removeObject(forKey: LocalSpeech.lastFailureDefaultsKey)
338 let stream = AsyncStream<AnalyzerInput>.makeStream(bufferingPolicy: .bufferingOldest(128))
339 let results: Task<LocalTranscript, Error>
340 if let module = config.module as? SpeechTranscriber {
341 results = Task {
342 var value = LocalTranscript()
343 do {
344 for try await result in module.results {
345 value.accept(text: String(result.text.characters), start: result.range.start.seconds,
346 end: CMTimeRangeGetEnd(result.range).seconds, final: result.isFinal)
347 await snapshot(value)
348 }
349 } catch {
350 if !(error is CancellationError), !Task.isCancelled { failure?(error) }
351 throw error
352 }
353 return value
354 }
355 } else if let module = config.module as? DictationTranscriber {
356 results = Task {
357 var value = LocalTranscript()
358 do {
359 for try await result in module.results {
360 value.accept(text: String(result.text.characters), start: result.range.start.seconds,
361 end: CMTimeRangeGetEnd(result.range).seconds, final: result.isFinal)
362 await snapshot(value)
363 }
364 } catch {
365 if !(error is CancellationError), !Task.isCancelled { failure?(error) }
366 throw error
367 }
368 return value
369 }
370 } else { throw LocalError.message("Unsupported on-device speech module.") }
371 let analysis = Task {
372 do { try await analyzer.start(inputSequence: stream.stream) }
373 catch {
374 if !(error is CancellationError), !Task.isCancelled { failure?(error) }
375 throw error
376 }
377 }
378 do { try await analysis.value }
379 catch { results.cancel(); await analyzer.cancelAndFinishNow(); throw error }
380 return LiveSpeechSession(analyzer: analyzer, format: format, continuation: stream.continuation,
381 analysis: analysis, results: results, failure: failure)
382 }
383 /// Called on the capture queue with mono Float32 microphone samples.
384 public func append(_ data: Data, sampleRate: Double) {
385 lock.lock(); defer { lock.unlock() }
386 guard conversionError == nil else { return }
387 do {
388 guard !data.isEmpty, data.count.isMultiple(of: MemoryLayout<Float>.size) else {
389 throw LocalError.message("Live audio contains an incomplete PCM sample.")
390 }
391 guard let inputFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate,
392 channels: 1, interleaved: false),
393 let input = AVAudioPCMBuffer(pcmFormat: inputFormat, frameCapacity: UInt32(data.count / 4)),
394 let samples = input.floatChannelData?[0] else { throw LocalError.message("Invalid live audio buffer.") }
395 input.frameLength = UInt32(data.count / 4)
396 data.withUnsafeBytes { bytes in if let base = bytes.baseAddress { memcpy(samples, base, data.count) } }
397 if inputFormat == format { try enqueue(input); return }
398 if converter == nil || inputRate != sampleRate {
399 converter = AVAudioConverter(from: inputFormat, to: format); inputRate = sampleRate
400 }
401 guard let converter, let output = AVAudioPCMBuffer(pcmFormat: format,
402 frameCapacity: UInt32(ceil(Double(input.frameLength) * format.sampleRate / sampleRate)) + 256) else {
403 throw LocalError.message("Live audio conversion is unavailable.")
404 }
405 var supplied = false, error: NSError?
406 let status = converter.convert(to: output, error: &error) { _, state in
407 if supplied { state.pointee = .noDataNow; return nil }
408 supplied = true; state.pointee = .haveData; return input
409 }
410 if status == .error { throw error ?? LocalError.message("Live audio conversion failed.") as NSError }
411 if output.frameLength > 0 { try enqueue(output) }
412 } catch { conversionError = error; continuation.finish(); failure?(error) }
413 }
414 private func enqueue(_ buffer: AVAudioPCMBuffer) throws {
415 if case .dropped = continuation.yield(AnalyzerInput(buffer: buffer)) {
416 throw LocalError.message("Live transcription fell behind the microphone. Transcription must stop to avoid silently losing words.")
417 }
418 }
419 private func capturedError() -> Error? { lock.lock(); defer { lock.unlock() }; return conversionError }
420 public func finish() async throws -> LocalTranscript {
421 continuation.finish()
422 do {
423 try await analysis.value
424 try await analyzer.finalizeAndFinishThroughEndOfInput()
425 let value = try await results.value
426 if let error = capturedError() { throw error }
427 return value
428 } catch {
429 results.cancel(); analysis.cancel(); await analyzer.cancelAndFinishNow(); throw capturedError() ?? error
430 }
431 }
432 public func cancel() async {
433 continuation.finish(); results.cancel(); analysis.cancel(); await analyzer.cancelAndFinishNow()
434 }
435}