Cotton code
228 lines · 10.5 KB · SwiftRaw
// `apple.speech`: Apple's on-device recogniser, SpeechAnalyzer over// SpeechTranscriber, with the vocabulary the core hands over as contextual// strings. Where SpeechTranscriber is not offered (a device or simulator// without it, or a language it lacks) the same analyzer runs Apple's// DictationTranscriber instead, which the system offers more widely. Volatile results are the partials, finalised results the finals;// each word carries its audio time range and the model's confidence.//// The system fetches the language's model the first time (Apple's download,// no audio leaves the phone): `SpeechModel.install`, the one place that does.@preconcurrency import AVFoundationimport CottonKitimport CottonSpeechimport CoreMediaimport Foundationimport Speechpublic final class AppleSpeechEngine: LiveVoiceEngine, @unchecked Sendable {    private let language: String?    private let vocabulary: [String]    private var transcriber: SpeechTranscriber?    private var dictation: DictationTranscriber?    private var analyzer: SpeechAnalyzer?    private var format: AVAudioFormat?    private var input: AsyncStream<AnalyzerInput>.Continuation?    private var reader: Task<Void, Never>?    private let converter = AppleFormatConverter()    public init(language: String?, vocabulary: [String]) {        self.language = language        self.vocabulary = vocabulary    }    static func locale(_ language: String?) -> Locale {        guard let language, !language.isEmpty else { return Locale.current }        let wanted = Locale.Language(identifier: language)        guard let code = wanted.languageCode else { return Locale.current }        return Locale(languageCode: code, script: wanted.script, languageRegion: Locale.current.region)    }    public func prepare() async throws {        let wanted = Self.locale(language)        let module: any SpeechModule        if SpeechTranscriber.isAvailable, let locale = await SpeechModel.locale(SpeechTranscriber.self, for: wanted) {            let made = SpeechTranscriber(                locale: locale,                transcriptionOptions: [],                reportingOptions: [.volatileResults, .fastResults],                attributeOptions: [.audioTimeRange, .transcriptionConfidence])            transcriber = made            module = made        } else if let locale = await SpeechModel.locale(DictationTranscriber.self, for: wanted) {            let made = DictationTranscriber(                locale: locale, contentHints: [], transcriptionOptions: [.punctuation],                reportingOptions: [.volatileResults], attributeOptions: [.audioTimeRange, .transcriptionConfidence])            dictation = made            module = made        } else {            throw VoiceFailure.engineUnavailable("\(VoiceEngineChoice.appleSpeech):no_model:\(language ?? Locale.current.identifier)")        }        try await SpeechModel.install([module])        let analyzer = SpeechAnalyzer(            modules: [module],            options: SpeechAnalyzer.Options(priority: .userInitiated, modelRetention: .processLifetime))        if !vocabulary.isEmpty {            let context = AnalysisContext()            // Apple ignores past a hundred, silently: the core ranked them, so            // the head is what matters.            context.contextualStrings[.general] = Array(vocabulary.prefix(100))            try await analyzer.setContext(context)        }        guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module]) else {            throw VoiceFailure.engineUnavailable(VoiceEngineChoice.appleSpeech)        }        try await analyzer.prepareToAnalyze(in: format)        self.analyzer = analyzer        self.format = format    }    public func start(_ hear: @escaping VoiceHearingSink) async throws {        if analyzer == nil { try await prepare() }        guard let analyzer else { throw VoiceFailure.engineUnavailable(VoiceEngineChoice.appleSpeech) }        let (stream, continuation) = AsyncStream<AnalyzerInput>.makeStream(bufferingPolicy: .unbounded)        input = continuation        let language = self.language        let transcriber = self.transcriber        let dictation = self.dictation        reader = Task.detached(priority: .userInitiated) {            do {                if let transcriber {                    for try await result in transcriber.results {                        hear(AppleSpeechEngine.hearing(result.text, final: result.isFinal, range: result.range, language: language))                    }                } else if let dictation {                    for try await result in dictation.results {                        hear(AppleSpeechEngine.hearing(result.text, final: result.isFinal, range: result.range, language: language))                    }                }            } catch {}        }        try await analyzer.start(inputSequence: stream)    }    public func feed(_ chunk: VoiceChunk) {        guard let format, let buffer = chunk.buffer(), let converted = converter.convert(buffer, to: format) else { return }        input?.yield(AnalyzerInput(buffer: converted))    }    public func finish() async {        input?.finish()        input = nil        try? await analyzer?.finalizeAndFinishThroughEndOfInput()        await reader?.value        reader = nil        analyzer = nil    }    public func cancel() {        input?.finish()        input = nil        reader?.cancel()        let analyzer = self.analyzer        self.analyzer = nil        Task { await analyzer?.cancelAndFinishNow() }    }    /// One result as a hearing: its words with their time ranges.    static func hearing(_ text: AttributedString, final: Bool, range: CMTimeRange, language: String?) -> VoiceHearing {        var words: [VoiceWord] = []        for run in text.runs {            let said = String(text[run.range].characters).trimmingCharacters(in: .whitespacesAndNewlines)            guard !said.isEmpty else { continue }            let span = run.audioTimeRange            let start = span.map { ms($0.start) } ?? ms(range.start)            let end = span.map { ms($0.end) } ?? ms(range.end)            // A run may hold several words (the model's own grouping): split            // on spaces, sharing its span.            let parts = said.split(separator: " ")            for (index, part) in parts.enumerated() {                let step = parts.count > 1 ? (end - start) / parts.count : 0                words.append(VoiceWord(                    w: String(part), startMs: start + index * step,                    endMs: parts.count > 1 ? start + (index + 1) * step : end,                    conf: run.transcriptionConfidence))            }        }        return VoiceHearing(            final: final, text: String(text.characters).trimmingCharacters(in: .whitespaces), words: words,            language: language, startMs: ms(range.start), endMs: ms(range.end))    }    static func ms(_ time: CMTime) -> Int {        guard time.isValid, time.isNumeric else { return 0 }        return Int((CMTimeGetSeconds(time) * 1000).rounded())    }}/// `apple.speech` as a second pass: one closed utterance, read whole.public final class AppleSpeechSecond: SecondVoiceEngine, @unchecked Sendable {    private let language: String?    public init(language: String?) { self.language = language }    public func prepare() async throws {}    public func transcribe(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing {        guard let locale = await SpeechModel.locale(SpeechTranscriber.self, for: AppleSpeechEngine.locale(language)) else {            throw VoiceFailure.engineUnavailable(VoiceEngineChoice.appleSpeech)        }        let transcriber = SpeechTranscriber(            locale: locale, transcriptionOptions: [], reportingOptions: [],            attributeOptions: [.audioTimeRange, .transcriptionConfidence])        try await SpeechModel.install([transcriber])        guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber]),              let buffer = VoiceChunk(samples: samples, startMs: 0).buffer(),              let converted = AppleFormatConverter().convert(buffer, to: format)        else { throw VoiceFailure.engineUnavailable(VoiceEngineChoice.appleSpeech) }        let analyzer = SpeechAnalyzer(modules: [transcriber])        let (stream, continuation) = AsyncStream<AnalyzerInput>.makeStream()        continuation.yield(AnalyzerInput(buffer: converted))        continuation.finish()        let collect = Task {            var text = AttributedString()            for try await result in transcriber.results where result.isFinal { text += result.text }            return text        }        try await analyzer.start(inputSequence: stream)        try await analyzer.finalizeAndFinishThroughEndOfInput()        let text = try await collect.value        var hearing = AppleSpeechEngine.hearing(            text, final: true,            range: CMTimeRange(start: .zero, duration: CMTime(value: CMTimeValue(samples.count), timescale: 16_000)),            language: language)        hearing.startMs += offsetMs        hearing.endMs += offsetMs        hearing.words = hearing.words.map { VoiceWord(w: $0.w, startMs: $0.startMs + offsetMs, endMs: $0.endMs + offsetMs, conf: $0.conf) }        return hearing    }}/// 16 kHz Float32 to the analyzer's best format.final class AppleFormatConverter: @unchecked Sendable {    private var converter: AVAudioConverter?    func convert(_ buffer: AVAudioPCMBuffer, to format: AVAudioFormat) -> AVAudioPCMBuffer? {        if buffer.format == format { return buffer }        if converter == nil || converter?.outputFormat != format {            converter = AVAudioConverter(from: buffer.format, to: format)            converter?.primeMethod = .none        }        guard let converter else { return nil }        let ratio = format.sampleRate / buffer.format.sampleRate        let capacity = AVAudioFrameCount((Double(buffer.frameLength) * ratio).rounded(.up)) + 32        guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return nil }        var given = false        var error: NSError?        let status = converter.convert(to: out, error: &error) { _, state in            if given {                state.pointee = .noDataNow                return nil            }            given = true            state.pointee = .haveData            return buffer        }        guard status != .error, out.frameLength > 0 else { return nil }        return out    }}