// The engines: what turns audio into timed words. The core's plan names them // (`apple.speech`, `sherpa:`); this file is the seam they share. // // A LIVE engine streams: words within a few hundred milliseconds, a partial // for the utterance in progress (cumulative within it, so it REPLACES the // last partial) and a final when the utterance closes. Every partial and // final goes to the core as `voice.heard` pass live. // // A SECOND engine reads a closed utterance's audio again with a larger model; // its text goes to the core as `voice.heard` pass second, and the core decides // what, if anything, to correct. import CottonKit import Foundation /// What an engine heard. public struct VoiceHearing: Sendable, Equatable { public var final: Bool public var text: String public var words: [VoiceWord] public var language: String? /// The utterance's span in session time. public var startMs: Int public var endMs: Int public init(final: Bool, text: String, words: [VoiceWord] = [], language: String? = nil, startMs: Int, endMs: Int) { self.final = final self.text = text self.words = words self.language = language self.startMs = startMs self.endMs = endMs } } public typealias VoiceHearingSink = @Sendable (VoiceHearing) -> Void public protocol LiveVoiceEngine: AnyObject, Sendable { /// Load what the engine needs (the model into memory, the system's asset). /// Never opens the microphone. func prepare() async throws /// Begin; hearings go to `hear` (off the main actor). func start(_ hear: @escaping VoiceHearingSink) async throws func feed(_ chunk: VoiceChunk) /// The audio has ended: settle what is in flight, then return. func finish() async func cancel() } public protocol SecondVoiceEngine: AnyObject, Sendable { func prepare() async throws /// Read `samples` (16 kHz mono) again; `offsetMs` is where they start in /// session time, so the words come back in session time. func transcribe(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing } /// Builds the engine a plan names. @MainActor public enum VoiceEngines { public static func live( _ choice: VoiceEngineChoice, language: String?, vocabulary: [String], store: VoiceModelStore ) async throws -> any LiveVoiceEngine { // The platform's recogniser: on an iPhone that is Apple's, whichever // platform's name the plan used for it. if VoiceEngineChoice.platformRecognisers.contains(choice.engine) { let apple = AppleSpeechEngine(language: language, vocabulary: vocabulary) do { try await apple.prepare() return apple } catch { // Apple's recogniser is not on this device for the language // (a simulator offers none): a voice model this phone already // holds for it stands in, live first, then one that reads // whole sentences on voice-activity segments. guard let entry = store.heldStandIn(for: language) else { throw error } return try SherpaLive.make(entry: entry, language: language, vocabulary: vocabulary, store: store) } } if let model = choice.sherpaModel { if let entry = try? await store.ready(model) { return try SherpaLive.make(entry: entry, language: language, vocabulary: vocabulary, store: store) } // Not held yet: the plan's downloads say what to fetch, and the // platform's recogniser stands in until it is (the contract), // else another model this phone holds for the language. let platform = VoiceEngineChoice(engine: VoiceEngineChoice.appleSpeech) if let standIn = try? await live(platform, language: language, vocabulary: vocabulary, store: store) { return standIn } throw VoiceFailure.modelMissing(model) } throw VoiceFailure.engineUnavailable(choice.engine) } public static func second( _ choice: VoiceEngineChoice, language: String?, store: VoiceModelStore ) async throws -> any SecondVoiceEngine { if let model = choice.sherpaModel { let entry = try await store.ready(model) return try SherpaSecond(entry: entry, language: language, folder: store.folder(model)) } if choice.engine == VoiceEngineChoice.appleSpeech { return AppleSpeechSecond(language: language) } throw VoiceFailure.engineUnavailable(choice.engine) } } /// Words from an engine's tokens: a token beginning with a space or `▁` (the /// sentencepiece word mark) begins a word; a CJK or kana character is a word /// of its own; anything else joins the word before it. enum VoiceTokens { static func words(tokens: [String], times: [Float]?, offsetMs: Int, endMs: Int) -> [VoiceWord] { var words: [VoiceWord] = [] var current = "" var start = 0 func close(at end: Int) { let trimmed = current.trimmingCharacters(in: .whitespaces) if !trimmed.isEmpty { words.append(VoiceWord(w: trimmed, startMs: start, endMs: max(end, start))) } current = "" } for (index, token) in tokens.enumerated() { let at = times.flatMap { index < $0.count ? offsetMs + Int($0[index] * 1000) : nil } ?? offsetMs let piece = token.replacingOccurrences(of: "▁", with: " ") let ideographic = piece.unicodeScalars.first.map(isIdeographic) ?? false if piece.hasPrefix(" ") || ideographic || current.isEmpty { close(at: at) start = at } current += piece if ideographic { close(at: at + 1) ; start = at } } close(at: endMs) // Each word ends where the next begins. for index in words.indices.dropLast() where words[index].endMs <= words[index].startMs { words[index].endMs = words[index + 1].startMs } return words } static func isIdeographic(_ scalar: Unicode.Scalar) -> Bool { switch scalar.value { case 0x3040 ... 0x30FF, 0x3400 ... 0x4DBF, 0x4E00 ... 0x9FFF, 0xF900 ... 0xFAFF, 0xFF66 ... 0xFF9F: true default: false } } }