Cotton code
506 lines · 21.4 KB · SwiftRaw
// `sherpa:<model>`: an open model run by sherpa-onnx, configured by the// catalogue's `kind` (crates/cotton-core/kits/shell/voice/models.json):////   online-transducer, online-ctc     a streaming live engine with endpoints//   offline-*                         a second pass over one utterance, or a//                                     live engine on voice-activity segments//                                     (silero-vad-v5) when the plan says so//// A model's files are found by the part the catalogue says each plays// (encoder, decoder, joiner, tokens, model, ...), its options are passed as// the catalogue gives them, and the microphone is levelled first where its// row says `level_input`: nothing is read from a model's id, family or file// names. sherpa-onnx copies every path at creation, so the C strings live only// for the call.//// Calls into sherpa-onnx are blocking CPU work: each engine runs them on its// own serial queue, never on the main actor.import CottonKitimport Foundation#if canImport(SherpaOnnxC)import SherpaOnnxC/// C strings that live until the holder goes.final class CStrings {    private var held: [UnsafeMutablePointer<CChar>] = []    func callAsFunction(_ value: String?) -> UnsafePointer<CChar>? {        guard let value else { return nil }        let copy = strdup(value)!        held.append(copy)        return UnsafePointer(copy)    }    deinit { held.forEach { free($0) } }}/// A model's files by the part the catalogue says each plays.struct SherpaFiles {    let folder: URL    let files: [VoiceModelFile]    func find(_ part: String) -> String? {        files.first { $0.part == part }.map { folder.appendingPathComponent($0.name).path }    }    var tokens: String? { find("tokens") }    var encoder: String? { find("encoder") }    var decoder: String? { find("decoder") }    var joiner: String? { find("joiner") }    var bpeVocab: String? { find("bpe_vocab") }    /// The one file of a single-file model.    var model: String? { find("model") }    static let threads: Int32 = 2}/// Whisper and SenseVoice name a language; the plan's is BCP-47.private func shortLanguage(_ language: String?) -> String {    guard let language, let code = Locale.Language(identifier: language).languageCode?.identifier else { return "" }    return code}private func onlineRecognizer(_ entry: VoiceModelEntry, files: SherpaFiles, vocabulary: [String]) throws -> OpaquePointer {    let s = CStrings()    var config = SherpaOnnxOnlineRecognizerConfig()    config.feat_config.sample_rate = 16_000    config.feat_config.feature_dim = 80    switch entry.kind {    case "online-transducer":        config.model_config.transducer.encoder = s(files.encoder)        config.model_config.transducer.decoder = s(files.decoder)        config.model_config.transducer.joiner = s(files.joiner)    case "online-ctc":        config.model_config.zipformer2_ctc.model = s(files.model)    case "online-nemo-ctc":        config.model_config.nemo_ctc.model = s(files.model)    default:        throw VoiceFailure.engineUnavailable("sherpa:\(entry.model)")    }    config.model_config.tokens = s(files.tokens)    config.model_config.num_threads = SherpaFiles.threads    config.model_config.provider = s("cpu")    if let type = entry.options["model_type"] { config.model_config.model_type = s(type) }    config.decoding_method = s("greedy_search")    config.max_active_paths = 4    config.enable_endpoint = 1    config.rule1_min_trailing_silence = 2.4    config.rule2_min_trailing_silence = 0.8    config.rule3_min_utterance_length = 20    // The vocabulary as hotwords, where the model can take them: a transducer    // with its BPE vocabulary listed.    let hotwords = vocabulary.prefix(100).joined(separator: "\n")    if entry.kind == "online-transducer", let vocab = files.bpeVocab, !hotwords.isEmpty {        config.model_config.modeling_unit = s("bpe")        config.model_config.bpe_vocab = s(vocab)        config.decoding_method = s("modified_beam_search")        config.hotwords_buf = s(hotwords)        config.hotwords_buf_size = Int32(hotwords.utf8.count)        config.hotwords_score = 1.5    }    guard let made = SherpaOnnxCreateOnlineRecognizer(&config) else {        throw VoiceFailure.engineUnavailable("sherpa:\(entry.model)")    }    return made}private func offlineRecognizer(_ entry: VoiceModelEntry, files: SherpaFiles, language: String?) throws -> OpaquePointer {    let s = CStrings()    var config = SherpaOnnxOfflineRecognizerConfig()    config.feat_config.sample_rate = 16_000    config.feat_config.feature_dim = 80    let code = entry.languageCodes[shortLanguage(language)] ?? shortLanguage(language)    switch entry.kind {    case "offline-transducer":        config.model_config.transducer.encoder = s(files.encoder)        config.model_config.transducer.decoder = s(files.decoder)        config.model_config.transducer.joiner = s(files.joiner)    case "offline-nemo-ctc":        config.model_config.nemo_ctc.model = s(files.model)    case "offline-whisper":        config.model_config.whisper.encoder = s(files.encoder)        config.model_config.whisper.decoder = s(files.decoder)        config.model_config.whisper.language = s(code)        config.model_config.whisper.task = s("transcribe")        config.model_config.whisper.tail_paddings = -1        config.model_config.whisper.enable_token_timestamps = 1    case "offline-sense-voice":        config.model_config.sense_voice.model = s(files.model)        config.model_config.sense_voice.language = s(code)        config.model_config.sense_voice.use_itn = 1    case "offline-moonshine":        config.model_config.moonshine.preprocessor = s(files.find("preprocessor"))        config.model_config.moonshine.encoder = s(files.encoder)        config.model_config.moonshine.uncached_decoder = s(files.find("uncached_decoder"))        config.model_config.moonshine.cached_decoder = s(files.find("cached_decoder"))        config.model_config.moonshine.merged_decoder = s(files.find("merged_decoder"))    case "offline-omnilingual-ctc":        config.model_config.omnilingual.model = s(files.model)    default:        throw VoiceFailure.engineUnavailable("sherpa:\(entry.model)")    }    config.model_config.tokens = s(files.tokens)    config.model_config.num_threads = SherpaFiles.threads    config.model_config.provider = s("cpu")    if let type = entry.options["model_type"] { config.model_config.model_type = s(type) }    config.decoding_method = s("greedy_search")    guard let made = SherpaOnnxCreateOfflineRecognizer(&config) else {        throw VoiceFailure.engineUnavailable("sherpa:\(entry.model)")    }    return made}private func tokens(_ array: UnsafePointer<UnsafePointer<CChar>?>?, count: Int32) -> [String] {    guard let array else { return [] }    return (0 ..< Int(count)).map { array[$0].map { String(cString: $0) } ?? "" }}/// One utterance's samples through an offline recognizer.private func decodeOffline(_ recognizer: OpaquePointer, samples: [Float], offsetMs: Int, language: String?) -> VoiceHearing {    let typed = recognizer    let stream = SherpaOnnxCreateOfflineStream(typed)    defer { SherpaOnnxDestroyOfflineStream(stream) }    samples.withUnsafeBufferPointer { SherpaOnnxAcceptWaveformOffline(stream, 16_000, $0.baseAddress, Int32($0.count)) }    SherpaOnnxDecodeOfflineStream(typed, stream)    let endMs = offsetMs + samples.count * 1000 / 16_000    guard let result = SherpaOnnxGetOfflineStreamResult(stream) else {        return VoiceHearing(final: true, text: "", language: language, startMs: offsetMs, endMs: endMs)    }    defer { SherpaOnnxDestroyOfflineRecognizerResult(result) }    let text = result.pointee.text.map { String(cString: $0) }?.trimmingCharacters(in: .whitespaces) ?? ""    let pieces = tokens(result.pointee.tokens_arr, count: result.pointee.count)    let times = result.pointee.timestamps.map { Array(UnsafeBufferPointer(start: $0, count: Int(result.pointee.count))) }    var words = VoiceTokens.words(tokens: pieces, times: times, offsetMs: offsetMs, endMs: endMs)    // A model with no tokens (or none that make words) still says its text.    if words.isEmpty, !text.isEmpty {        words = text.split(separator: " ").map { VoiceWord(w: String($0), startMs: offsetMs, endMs: endMs) }    }    let heard = result.pointee.lang.map { String(cString: $0) }.flatMap { $0.isEmpty ? nil : $0 }    return VoiceHearing(final: true, text: text, words: words, language: heard.map(cleanLanguage) ?? language, startMs: offsetMs, endMs: endMs)}/// SenseVoice says `<|ja|>`.private func cleanLanguage(_ tag: String) -> String {    tag.trimmingCharacters(in: CharacterSet(charactersIn: "<|>"))}// MARK: Second passpublic final class SherpaSecond: SecondVoiceEngine, @unchecked Sendable {    private let entry: VoiceModelEntry    private let language: String?    private let files: SherpaFiles    private var recognizer: OpaquePointer?    private let queue = DispatchQueue(label: "cotton.voice.sherpa.second", qos: .userInitiated)    init(entry: VoiceModelEntry, language: String?, folder: URL) throws {        self.entry = entry        self.language = language        files = SherpaFiles(folder: folder, files: entry.files)    }    deinit {        if let recognizer { SherpaOnnxDestroyOfflineRecognizer(recognizer) }    }    public func prepare() async throws {        try await withCheckedThrowingContinuation { (done: CheckedContinuation<Void, Error>) in            queue.async { [self] in                do {                    if recognizer == nil { recognizer = try offlineRecognizer(entry, files: files, language: language) }                    done.resume()                } catch { done.resume(throwing: error) }            }        }    }    public func transcribe(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing {        try await prepare()        return await withCheckedContinuation { done in            queue.async { [self] in                // One utterance, levelled by its own peak where the model does not level itself.                let heard = entry.level.map { VoiceLeveller($0).level(samples) } ?? samples                done.resume(returning: decodeOffline(recognizer!, samples: heard, offsetMs: offsetMs, language: language))            }        }    }}// MARK: Live@MainActorenum SherpaLive {    static func make(entry: VoiceModelEntry, language: String?, vocabulary: [String], store: VoiceModelStore) throws -> any LiveVoiceEngine {        let files = SherpaFiles(folder: store.folder(entry.model), files: entry.files)        if entry.kind.hasPrefix("online-") {            return SherpaStreaming(entry: entry, files: files, language: language, vocabulary: vocabulary)        }        guard let vadModel = store.vadModel else { throw VoiceFailure.modelMissing("vad") }        guard let vad = store.readyNow(vadModel) else { throw VoiceFailure.modelMissing(vadModel) }        return SherpaSegmented(            entry: entry, files: files, language: language,            vad: SherpaFiles(folder: store.folder(vad.model), files: vad.files), vadEntry: vad)    }}/// A streaming model: partials as the words come, a final at each endpoint.final class SherpaStreaming: LiveVoiceEngine, @unchecked Sendable {    private let entry: VoiceModelEntry    private let files: SherpaFiles    private let language: String?    private let vocabulary: [String]    private let queue = DispatchQueue(label: "cotton.voice.sherpa.live", qos: .userInitiated)    private var recognizer: OpaquePointer?    private var stream: OpaquePointer?    private var hear: VoiceHearingSink?    /// Samples fed since the session began, and where the open utterance began.    private var fed = 0    private var utteranceStart = 0    private var lastText = ""    private let leveller: VoiceLeveller?    init(entry: VoiceModelEntry, files: SherpaFiles, language: String?, vocabulary: [String]) {        leveller = VoiceLeveller.over([entry])        self.entry = entry        self.files = files        self.language = language        self.vocabulary = vocabulary    }    deinit {        if let stream { SherpaOnnxDestroyOnlineStream(stream) }        if let recognizer { SherpaOnnxDestroyOnlineRecognizer(recognizer) }    }    func prepare() async throws {        try await withCheckedThrowingContinuation { (done: CheckedContinuation<Void, Error>) in            queue.async { [self] in                do {                    if recognizer == nil { recognizer = try onlineRecognizer(entry, files: files, vocabulary: vocabulary) }                    done.resume()                } catch { done.resume(throwing: error) }            }        }    }    func start(_ hear: @escaping VoiceHearingSink) async throws {        try await prepare()        queue.sync {            self.hear = hear            stream = SherpaOnnxCreateOnlineStream(recognizer!)            fed = 0            utteranceStart = 0            lastText = ""        }    }    func feed(_ chunk: VoiceChunk) {        queue.async { [self] in            guard let recognizer, let stream else { return }            let r = recognizer            let st = stream            let samples = leveller?.level(chunk.samples) ?? chunk.samples            samples.withUnsafeBufferPointer { SherpaOnnxOnlineStreamAcceptWaveform(st, 16_000, $0.baseAddress, Int32($0.count)) }            fed += chunk.samples.count            while SherpaOnnxIsOnlineStreamReady(r, st) == 1 { SherpaOnnxDecodeOnlineStream(r, st) }            let endpoint = SherpaOnnxOnlineStreamIsEndpoint(r, st) == 1            emit(final: endpoint)            if endpoint {                SherpaOnnxOnlineStreamReset(r, st)                utteranceStart = fed                lastText = ""            }        }    }    /// The stream's result now, as a partial or (at an endpoint) a final.    private func emit(final: Bool) {        guard let recognizer, let stream else { return }        let r = recognizer        let st = stream        guard let result = SherpaOnnxGetOnlineStreamResult(r, st) else { return }        defer { SherpaOnnxDestroyOnlineRecognizerResult(result) }        let text = result.pointee.text.map { String(cString: $0) }?.trimmingCharacters(in: .whitespaces) ?? ""        // A partial that says nothing new is not sent; an empty final is not        // an utterance.        if text.isEmpty { return }        if !final, text == lastText { return }        lastText = text        let offset = utteranceStart * 1000 / 16_000        let end = fed * 1000 / 16_000        let pieces = tokens(result.pointee.tokens_arr, count: result.pointee.count)        let times = result.pointee.timestamps.map { Array(UnsafeBufferPointer(start: $0, count: Int(result.pointee.count))) }        hear?(VoiceHearing(            final: final, text: text,            words: VoiceTokens.words(tokens: pieces, times: times, offsetMs: offset, endMs: end),            language: language, startMs: offset, endMs: end))    }    func finish() async {        await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in            queue.async { [self] in                if let recognizer, let stream {                    let r = recognizer                    let st = stream                    // A little silence lets the last word out of the model.                    let tail = [Float](repeating: 0, count: 16_000 * 8 / 10)                    tail.withUnsafeBufferPointer { SherpaOnnxOnlineStreamAcceptWaveform(st, 16_000, $0.baseAddress, Int32($0.count)) }                    SherpaOnnxOnlineStreamInputFinished(st)                    while SherpaOnnxIsOnlineStreamReady(r, st) == 1 { SherpaOnnxDecodeOnlineStream(r, st) }                    emit(final: true)                    SherpaOnnxDestroyOnlineStream(st)                    self.stream = nil                }                hear = nil                done.resume()            }        }    }    func cancel() {        queue.async { [self] in            if let stream { SherpaOnnxDestroyOnlineStream(stream) }            stream = nil            hear = nil        }    }}/// An offline model as a live engine: silero voice activity cuts the audio/// into utterances, and each is read whole. No partials (the model cannot/// stream); the control shows it is listening until the utterance closes.final class SherpaSegmented: LiveVoiceEngine, @unchecked Sendable {    private let entry: VoiceModelEntry    private let files: SherpaFiles    private let vadFiles: SherpaFiles    private let language: String?    private let queue = DispatchQueue(label: "cotton.voice.sherpa.segmented", qos: .userInitiated)    private var recognizer: OpaquePointer?    private var vad: OpaquePointer?    private var hear: VoiceHearingSink?    private var pending: [Float] = []    private let window = 512    private let vadModel: String    /// Levels what the voice activity and the model hear, where either lacks its own levelling.    private let leveller: VoiceLeveller?    init(entry: VoiceModelEntry, files: SherpaFiles, language: String?, vad: SherpaFiles, vadEntry: VoiceModelEntry) {        self.entry = entry        self.files = files        self.language = language        vadFiles = vad        vadModel = vadEntry.model        leveller = VoiceLeveller.over([vadEntry, entry])    }    deinit {        if let vad { SherpaOnnxDestroyVoiceActivityDetector(vad) }        if let recognizer { SherpaOnnxDestroyOfflineRecognizer(recognizer) }    }    func prepare() async throws {        try await withCheckedThrowingContinuation { (done: CheckedContinuation<Void, Error>) in            queue.async { [self] in                do {                    if recognizer == nil { recognizer = try offlineRecognizer(entry, files: files, language: language) }                    if vad == nil {                        let s = CStrings()                        var config = SherpaOnnxVadModelConfig()                        config.silero_vad.model = s(vadFiles.model)                        config.silero_vad.threshold = 0.5                        config.silero_vad.min_silence_duration = 0.4                        config.silero_vad.min_speech_duration = 0.25                        config.silero_vad.max_speech_duration = 15                        config.silero_vad.window_size = Int32(window)                        config.sample_rate = 16_000                        config.num_threads = 1                        config.provider = s("cpu")                        guard let made = SherpaOnnxCreateVoiceActivityDetector(&config, 60) else {                            throw VoiceFailure.engineUnavailable("sherpa:\(vadModel)")                        }                        vad = made                    }                    done.resume()                } catch { done.resume(throwing: error) }            }        }    }    func start(_ hear: @escaping VoiceHearingSink) async throws {        try await prepare()        queue.sync {            self.hear = hear            pending = []            SherpaOnnxVoiceActivityDetectorReset(vad!)        }    }    func feed(_ chunk: VoiceChunk) {        queue.async { [self] in            guard let vad else { return }            pending.append(contentsOf: leveller?.level(chunk.samples) ?? chunk.samples)            while pending.count >= window {                let piece = Array(pending.prefix(window))                pending.removeFirst(window)                piece.withUnsafeBufferPointer {                    SherpaOnnxVoiceActivityDetectorAcceptWaveform(vad, $0.baseAddress, Int32(window))                }            }            drain()        }    }    private func drain() {        guard let vad, let recognizer else { return }        let v = vad        while SherpaOnnxVoiceActivityDetectorEmpty(v) == 0 {            guard let segment = SherpaOnnxVoiceActivityDetectorFront(v) else { break }            let samples = Array(UnsafeBufferPointer(start: segment.pointee.samples, count: Int(segment.pointee.n)))            let offset = Int(segment.pointee.start) * 1000 / 16_000            SherpaOnnxDestroySpeechSegment(segment)            SherpaOnnxVoiceActivityDetectorPop(v)            let hearing = decodeOffline(recognizer, samples: samples, offsetMs: offset, language: language)            if !hearing.text.isEmpty { hear?(hearing) }        }    }    func finish() async {        await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in            queue.async { [self] in                if let vad {                    SherpaOnnxVoiceActivityDetectorFlush(vad)                    drain()                }                hear = nil                done.resume()            }        }    }    func cancel() {        queue.async { [self] in hear = nil }    }}#else// macOS (the package's own tests) and any build without the archive: the// engine says plainly it is not here.public final class SherpaSecond: SecondVoiceEngine, @unchecked Sendable {    init(entry: VoiceModelEntry, language: String?, folder: URL) throws {        throw VoiceFailure.notInThisBuild("sherpa:\(entry.model)")    }    public func prepare() async throws {}    public func transcribe(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing {        throw VoiceFailure.notInThisBuild("sherpa")    }}@MainActorenum SherpaLive {    static func make(entry: VoiceModelEntry, language: String?, vocabulary: [String], store: VoiceModelStore) throws -> any LiveVoiceEngine {        throw VoiceFailure.notInThisBuild("sherpa:\(entry.model)")    }}#endif