// The engines: what turns audio into timed words. The core's plan names them// (`apple.speech`, `sherpa:<model>`); 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.importCottonKitimportFoundation/// What an engine heard.publicstructVoiceHearing: Sendable, Equatable {publicvarfinal: Boolpublicvar text: Stringpublicvar words: [VoiceWord]publicvar language: String?/// The utterance's span in session time.publicvar startMs: Intpublicvar endMs: Intpublicinit(final: Bool, text: String, words: [VoiceWord] = [], language: String? = nil, startMs: Int, endMs: Int) {self.final = finalself.text = textself.words = wordsself.language = languageself.startMs = startMsself.endMs = endMs }}publictypealiasVoiceHearingSink = @Sendable (VoiceHearing) -> VoidpublicprotocolLiveVoiceEngine: AnyObject, Sendable {/// Load what the engine needs (the model into memory, the system's asset)./// Never opens the microphone.func prepare() asyncthrows/// Begin; hearings go to `hear` (off the main actor).func start(_ hear: @escaping VoiceHearingSink) asyncthrowsfunc feed(_ chunk: VoiceChunk)/// The audio has ended: settle what is in flight, then return.func finish() asyncfunc cancel()}publicprotocolSecondVoiceEngine: AnyObject, Sendable {func prepare() asyncthrows/// 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) asyncthrows -> VoiceHearing}/// Builds the engine a plan names.@MainActorpublicenumVoiceEngines {publicstaticfunc live( _ choice: VoiceEngineChoice, language: String?, vocabulary: [String], store: VoiceModelStore ) asyncthrows -> any LiveVoiceEngine {// The platform's recogniser: on an iPhone that is Apple's, whichever// platform's name the plan used for it.ifVoiceEngineChoice.platformRecognisers.contains(choice.engine) {let apple = AppleSpeechEngine(language: language, vocabulary: vocabulary)do {tryawait 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.guardlet entry = store.heldStandIn(for: language) else { throw error }returntrySherpaLive.make(entry: entry, language: language, vocabulary: vocabulary, store: store) } }iflet model = choice.sherpaModel {iflet entry = try? await store.ready(model) {returntrySherpaLive.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)iflet standIn = try? await live(platform, language: language, vocabulary: vocabulary, store: store) {return standIn }throwVoiceFailure.modelMissing(model) }throwVoiceFailure.engineUnavailable(choice.engine) }publicstaticfunc second( _ choice: VoiceEngineChoice, language: String?, store: VoiceModelStore ) asyncthrows -> any SecondVoiceEngine {iflet model = choice.sherpaModel {let entry = tryawait store.ready(model)returntrySherpaSecond(entry: entry, language: language, folder: store.folder(model)) }if choice.engine == VoiceEngineChoice.appleSpeech {returnAppleSpeechSecond(language: language) }throwVoiceFailure.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.enumVoiceTokens {staticfunc words(tokens: [String], times: [Float]?, offsetMs: Int, endMs: Int) -> [VoiceWord] {var words: [VoiceWord] = []var current = ""var start = 0func 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 } ?? offsetMslet piece = token.replacingOccurrences(of: "▁", with: " ")let ideographic = piece.unicodeScalars.first.map(isIdeographic) ?? falseif piece.hasPrefix(" ") || ideographic || current.isEmpty { close(at: at) start = at } current += pieceif 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 }staticfunc isIdeographic(_ scalar: Unicode.Scalar) -> Bool {switch scalar.value {case0x3040 ... 0x30FF, 0x3400 ... 0x4DBF, 0x4E00 ... 0x9FFF, 0xF900 ... 0xFAFF, 0xFF66 ... 0xFF9F: truedefault: false } }}