Cotton code
634 lines · 24.6 KB · SwiftRaw
// Voice at the boundary: the `voice.*` names and the shapes they carry// (the voice plan, 17 Nov 2026: "audio in, timed words out").//// THE CORE DECIDES, THE PHONE LISTENS AND DRAWS. Every rule about what the// words become (settled and tentative text, spoken punctuation, casing, the// vocabulary, reconciling the second pass, command mode, every line the// control says) is the core's. What this side owns is the microphone, running// the engines the plan names, feeding what they heard back, and drawing the// answer. So nothing here interprets text: a field the core adds later is// ignored, a field it leaves out decodes to its empty value, and a shape the// screen draws is exactly what came back.//// THE CONTRACT is the crate's: `crates/cotton-ffi/src/phone/voice.rs`'s// header. Where this file and that header disagree, the header wins.import Foundationextension CottonMethod {    /// `voice.plan` — before the microphone opens: which engines, which    /// languages, the vocabulary, the downloads a better result needs and the    /// words the control says.    public static let voicePlan = "voice.plan"    /// `voice.heard` — every partial and final from either pass; answers the    /// text as it stands and the edits to apply.    public static let voiceHeard = "voice.heard"    /// `voice.touched` — the person typed or selected inside the dictated text;    /// the second pass never changes that range again.    public static let voiceTouched = "voice.touched"    /// `voice.end` — the session is over; answers what was written.    public static let voiceEnd = "voice.end"    /// `voice.models` — the catalogue joined with what this phone holds.    public static let voiceModels = "voice.models"    /// `voice.model` — one model's state changed on this phone.    public static let voiceModel = "voice.model"    /// `voice.settings` — the person's languages, scripts, passes and the    /// mobile-data rule.    public static let voiceSettings = "voice.settings"}/// Dictating into text, or speaking a command.public enum VoiceMode: String, Codable, Sendable, Equatable {    case dictate    case command}/// Which pass a hearing came from.public enum VoicePass: String, Codable, Sendable, Equatable {    case live    case second}// MARK: - voice.planpublic struct VoicePlanRequest: Encodable, Sendable, Equatable {    /// Where the microphone is: `deck`, `story.writer`, `note`, `fan`, …    public var surface: String    public var table: String?    public var column: String?    public var record: String?    public var database: String?    public var mode: VoiceMode    public init(surface: String, table: String? = nil, column: String? = nil, record: String? = nil, database: String? = nil, mode: VoiceMode) {        self.surface = surface        self.table = table        self.column = column        self.record = record        self.database = database        self.mode = mode    }}/// One engine the plan names: `apple.speech`, `android.speech` or/// `sherpa:<model-id>`, with the model it runs where that is separate.public struct VoiceEngineChoice: Codable, Sendable, Equatable {    public var engine: String    public var model: String?    public init(engine: String, model: String? = nil) {        self.engine = engine        self.model = model    }    /// The model id a `sherpa:` engine names, from `model` or the engine id.    public var sherpaModel: String? {        guard engine.hasPrefix(VoiceEngineChoice.sherpaPrefix) else { return nil }        if let model, !model.isEmpty { return model }        let id = String(engine.dropFirst(VoiceEngineChoice.sherpaPrefix.count))        return id.isEmpty ? nil : id    }    public static let appleSpeech = "apple.speech"    public static let androidSpeech = "android.speech"    public static let sherpaPrefix = "sherpa:"    /// The platform's own recogniser, by either platform's name.    public static let platformRecognisers: Set<String> = [appleSpeech, androidSpeech]}/// A model the plan wants on this phone and does not find.public struct VoiceDownload: Codable, Sendable, Equatable, Identifiable {    public var model: String    /// The file's name in the model's folder (one entry per file).    public var file: String    public var bytes: Int64    public var url: String    public var sha256: String    /// The core's sentence for why: "Better Telugu", with its size in its own words.    public var why: String    public var id: String { model }    public init(model: String, file: String = "", bytes: Int64, url: String, sha256: String, why: String) {        self.model = model        self.file = file        self.bytes = bytes        self.url = url        self.sha256 = sha256        self.why = why    }    enum CodingKeys: String, CodingKey { case model, file, bytes, url, sha256, why }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        model = try c.decode(String.self, forKey: .model)        url = try c.decodeIfPresent(String.self, forKey: .url) ?? ""        file = try c.decodeIfPresent(String.self, forKey: .file) ?? URL(string: url)?.lastPathComponent ?? model        bytes = try c.decodeIfPresent(Int64.self, forKey: .bytes) ?? 0        sha256 = try c.decodeIfPresent(String.self, forKey: .sha256) ?? ""        why = try c.decodeIfPresent(String.self, forKey: .why) ?? ""    }}public struct VoicePlan: Decodable, Sendable, Equatable {    public var session: String    public var mode: VoiceMode    public var languages: [String]    public var live: VoiceEngineChoice    public var second: VoiceEngineChoice?    public var vocabulary: [String]    public var downloads: [VoiceDownload]    /// Each language's script (ISO 15924, lowercase): `{"te": "latn"}`.    public var scripts: [String: String]    /// The person's rule for downloads off Wi-Fi: `never`, `ask`, `always`.    public var mobileData: String    /// Every word the control says, keyed by the core (`listening`,    /// `settling`, `download`, `denied`, …). The control reads a key and    /// falls back to the shell's kit line of the same name.    public var lines: [String: String]    public init(        session: String, mode: VoiceMode, languages: [String], live: VoiceEngineChoice,        second: VoiceEngineChoice? = nil, vocabulary: [String] = [], downloads: [VoiceDownload] = [],        lines: [String: String] = [:]    ) {        self.session = session        self.mode = mode        self.languages = languages        self.live = live        self.second = second        self.vocabulary = vocabulary        self.downloads = downloads        self.lines = lines        scripts = [:]        mobileData = "ask"    }    enum CodingKeys: String, CodingKey {        case session, mode, languages, live, second, vocabulary, downloads, lines, scripts        case mobileData = "mobile_data"    }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        session = try c.decode(String.self, forKey: .session)        mode = try c.decodeIfPresent(VoiceMode.self, forKey: .mode) ?? .dictate        languages = try c.decodeIfPresent([String].self, forKey: .languages) ?? []        live = try c.decode(VoiceEngineChoice.self, forKey: .live)        second = try c.decodeIfPresent(VoiceEngineChoice.self, forKey: .second)        vocabulary = try c.decodeIfPresent([String].self, forKey: .vocabulary) ?? []        downloads = try c.decodeIfPresent([VoiceDownload].self, forKey: .downloads) ?? []        scripts = (try? c.decodeIfPresent([String: String].self, forKey: .scripts)) ?? [:]        mobileData = (try? c.decodeIfPresent(String.self, forKey: .mobileData)) ?? "ask"        // `lines` is "…words the control says…": strings by key. A value that        // is not a string (a nested set) is skipped rather than failing the plan.        if let tree = try c.decodeIfPresent(JSONValue.self, forKey: .lines), case .object(let pairs) = tree {            var flat: [String: String] = [:]            for (key, value) in pairs { if case .string(let s) = value { flat[key] = s } }            lines = flat        } else {            lines = [:]        }    }}// MARK: - voice.heard/// One timed word as an engine heard it.public struct VoiceWord: Codable, Sendable, Equatable {    public var w: String    public var startMs: Int    public var endMs: Int    public var conf: Double?    public init(w: String, startMs: Int, endMs: Int, conf: Double? = nil) {        self.w = w        self.startMs = startMs        self.endMs = endMs        self.conf = conf    }    enum CodingKeys: String, CodingKey {        case w        case startMs = "start_ms"        case endMs = "end_ms"        case conf    }}public struct VoiceHeard: Encodable, Sendable, Equatable {    public var session: String    public var pass: VoicePass    public var final: Bool    public var text: String    public var words: [VoiceWord]?    /// The audio the result covers, from the session's start.    public var fromMs: Int?    public var toMs: Int?    public var language: String?    public init(session: String, pass: VoicePass, final: Bool, text: String, words: [VoiceWord]? = nil,                fromMs: Int? = nil, toMs: Int? = nil, language: String? = nil) {        self.session = session        self.pass = pass        self.final = final        self.text = text        self.words = words        self.fromMs = fromMs        self.toMs = toMs        self.language = language    }    enum CodingKeys: String, CodingKey {        case session, pass, final, text, words, language        case fromMs = "from_ms"        case toMs = "to_ms"    }}/// Replace `from..<to` (offsets into the settled text, in UTF-16 units, the/// unit UIKit's selection reports) with `text`.public struct VoiceEdit: Codable, Sendable, Equatable {    public var from: Int    public var to: Int    public var text: String    public init(from: Int, to: Int, text: String) {        self.from = from        self.to = to        self.text = text    }}public struct VoiceHeardAnswer: Decodable, Sendable, Equatable {    /// The text that will not change again unless a second pass corrects it.    public var settled: String    /// The words still streaming: drawn lighter, after `settled`.    public var tentative: String    /// Rare: settled text after the tentative words (a second pass ran ahead    /// of the live engine). The session's text is settled + tentative + later.    public var later: String    public var edits: [VoiceEdit]    /// A command the shell opens (command mode).    public var command: VoiceCommand?    /// How long the core asks the phone to wait before the next pass.    public var waitMs: Int?    public init(settled: String, tentative: String, later: String = "", edits: [VoiceEdit] = [], command: VoiceCommand? = nil, waitMs: Int? = nil) {        self.settled = settled        self.tentative = tentative        self.later = later        self.edits = edits        self.command = command        self.waitMs = waitMs    }    enum CodingKeys: String, CodingKey {        case settled, tentative, later, edits, command        case waitMs = "wait_ms"    }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        settled = try c.decodeIfPresent(String.self, forKey: .settled) ?? ""        tentative = try c.decodeIfPresent(String.self, forKey: .tentative) ?? ""        later = try c.decodeIfPresent(String.self, forKey: .later) ?? ""        edits = try c.decodeIfPresent([VoiceEdit].self, forKey: .edits) ?? []        command = try? c.decodeIfPresent(VoiceCommand.self, forKey: .command)        waitMs = try c.decodeIfPresent(Int.self, forKey: .waitMs)    }}// MARK: - voice.touched / voice.endpublic struct VoiceTouched: Encodable, Sendable, Equatable {    public var session: String    public var from: Int    public var to: Int    /// What the person wrote over `from..<to` (absent for a selection): the    /// core may keep it as the settled text for that range.    public var text: String?    public init(session: String, from: Int, to: Int, text: String? = nil) {        self.session = session        self.from = from        self.to = to        self.text = text    }}public struct VoiceSessionRef: Encodable, Sendable, Equatable {    public var session: String    public init(session: String) { self.session = session }}/// What `voice.end` answers: the whole session's text, the edits that/// settled what was tentative, and a command when one resolved.public struct VoiceEnded: Decodable, Sendable, Equatable {    public var text: String    public var edits: [VoiceEdit]    public var command: VoiceCommand?    public init(text: String, edits: [VoiceEdit] = [], command: VoiceCommand? = nil) {        self.text = text        self.edits = edits        self.command = command    }    enum CodingKeys: String, CodingKey { case text, edits, command }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        text = try c.decodeIfPresent(String.self, forKey: .text) ?? ""        edits = try c.decodeIfPresent([VoiceEdit].self, forKey: .edits) ?? []        command = try? c.decodeIfPresent(VoiceCommand.self, forKey: .command)    }}/// A spoken command's answer (command mode): a record that resolved, opened;/// or the words, searched.public struct VoiceCommand: Decodable, Sendable, Equatable {    /// `open` or `search`.    public var kind: String    public var query: String    public var table: String?    public var id: String?    public var title: String?    public var path: String?    public var database: String?    /// What the control says as it is carried out ("Opening Ravi").    public var says: String?    public init(kind: String, query: String, table: String? = nil, id: String? = nil, title: String? = nil, database: String? = nil,                path: String? = nil, says: String? = nil) {        self.path = path        self.says = says        self.kind = kind        self.query = query        self.table = table        self.id = id        self.title = title        self.database = database    }    enum CodingKeys: String, CodingKey { case kind, query, table, id, title, path, database, says }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "search"        query = try c.decodeIfPresent(String.self, forKey: .query) ?? ""        table = try c.decodeIfPresent(String.self, forKey: .table)        id = try c.decodeIfPresent(String.self, forKey: .id)        title = try c.decodeIfPresent(String.self, forKey: .title)        database = try c.decodeIfPresent(String.self, forKey: .database)        path = try c.decodeIfPresent(String.self, forKey: .path)        says = try c.decodeIfPresent(String.self, forKey: .says)    }}// MARK: - voice.models / voice.modelpublic enum VoiceModelState: String, Codable, Sendable, Equatable {    case absent    case downloading    case ready    case failed}/// One file of a model, as the catalogue lists it. `part` is what the file is/// to the kind's sherpa-onnx configuration (encoder, decoder, joiner, tokens,/// model), the catalogue's word for it: no file is found by its name.public struct VoiceModelFile: Codable, Sendable, Equatable {    public var name: String    public var url: String    public var bytes: Int64    public var sha256: String    public var part: String    public init(name: String, url: String, bytes: Int64, sha256: String, part: String = "") {        self.name = name        self.url = url        self.bytes = bytes        self.sha256 = sha256        self.part = part    }    enum CodingKeys: String, CodingKey { case name, url, bytes, sha256, path, part }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        url = try c.decodeIfPresent(String.self, forKey: .url) ?? ""        name = try c.decodeIfPresent(String.self, forKey: .name)            ?? c.decodeIfPresent(String.self, forKey: .path)            ?? URL(string: url)?.lastPathComponent ?? ""        bytes = try c.decodeIfPresent(Int64.self, forKey: .bytes) ?? 0        sha256 = try c.decodeIfPresent(String.self, forKey: .sha256) ?? ""        part = try c.decodeIfPresent(String.self, forKey: .part) ?? ""    }    public func encode(to encoder: any Encoder) throws {        var c = encoder.container(keyedBy: CodingKeys.self)        try c.encode(name, forKey: .name)        try c.encode(url, forKey: .url)        try c.encode(bytes, forKey: .bytes)        try c.encode(sha256, forKey: .sha256)        if !part.isEmpty { try c.encode(part, forKey: .part) }    }}/// The catalogue's levelling, on a model that does not level its own input/// (`level_input`): while the microphone's running peak stays under/// `belowPeak`, the samples are raised so the peak reads `toPeak`, by at most/// `maxGain`.public struct VoiceLevelling: Codable, Sendable, Equatable {    public var belowPeak: Float    public var toPeak: Float    public var maxGain: Float    public init(belowPeak: Float, toPeak: Float, maxGain: Float) {        self.belowPeak = belowPeak        self.toPeak = toPeak        self.maxGain = maxGain    }    enum CodingKeys: String, CodingKey {        case belowPeak = "below_peak"        case toPeak = "to_peak"        case maxGain = "max_gain"    }}/// A catalogue option's value as sherpa-onnx takes it: a word or a number.private struct VoiceOptionValue: Decodable {    let text: String    init(from decoder: any Decoder) throws {        let c = try decoder.singleValueContainer()        if let word = try? c.decode(String.self) { text = word } else if let number = try? c.decode(Double.self) { text = String(number) } else { text = String(try c.decode(Bool.self)) }    }}/// A catalogue entry joined with what this phone holds.public struct VoiceModelEntry: Decodable, Sendable, Equatable, Identifiable {    public var model: String    public var family: String    /// How sherpa-onnx is configured for it (the catalogue's `kind`):    /// `online-transducer`, `online-ctc`, `offline-transducer`,    /// `offline-nemo-ctc`, `offline-whisper`, `offline-sense-voice`,    /// `offline-moonshine`, `vad-silero`, …    public var kind: String    public var role: String    public var languages: [String]    public var files: [VoiceModelFile]    public var state: VoiceModelState    public var bytesDone: Int64?    /// Passed to the kind's sherpa-onnx configuration as the catalogue gives    /// them (`model_type: nemo_transducer` for a NeMo transducer).    public var options: [String: String]    /// The code the model reads for a language, where it is not the language's own.    public var languageCodes: [String: String]    /// The microphone is levelled before a model that does not level its own input.    public var level: VoiceLevelling?    public var id: String { model }    public var bytes: Int64 { files.reduce(0) { $0 + $1.bytes } }    public init(        model: String, family: String = "", kind: String, role: String = "both", languages: [String] = [],        files: [VoiceModelFile] = [], state: VoiceModelState = .absent, bytesDone: Int64? = nil,        options: [String: String] = [:], languageCodes: [String: String] = [:], level: VoiceLevelling? = nil    ) {        self.options = options        self.languageCodes = languageCodes        self.level = level        self.model = model        self.family = family        self.kind = kind        self.role = role        self.languages = languages        self.files = files        self.state = state        self.bytesDone = bytesDone    }    enum CodingKeys: String, CodingKey {        case model, id, family, kind, role, languages, files, state, options        case bytesDone = "bytes_done"        case languageCodes = "language_codes"        case level = "level_input"    }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        model = try c.decodeIfPresent(String.self, forKey: .model) ?? c.decode(String.self, forKey: .id)        family = try c.decodeIfPresent(String.self, forKey: .family) ?? ""        kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? ""        role = try c.decodeIfPresent(String.self, forKey: .role) ?? ""        languages = try c.decodeIfPresent([String].self, forKey: .languages) ?? []        files = try c.decodeIfPresent([VoiceModelFile].self, forKey: .files) ?? []        state = (try? c.decodeIfPresent(VoiceModelState.self, forKey: .state)) ?? .absent        bytesDone = try c.decodeIfPresent(Int64.self, forKey: .bytesDone)        options = (try? c.decodeIfPresent([String: VoiceOptionValue].self, forKey: .options))?.mapValues(\.text) ?? [:]        languageCodes = (try? c.decodeIfPresent([String: String].self, forKey: .languageCodes)) ?? [:]        level = try? c.decodeIfPresent(VoiceLevelling.self, forKey: .level)    }    /// The catalogue's word on how to run this model, over what a marker kept:    /// kind, role, family, options, levelling and each file's part (by name).    public func taught(by known: VoiceModelEntry) -> VoiceModelEntry {        var out = self        if out.kind.isEmpty { out.kind = known.kind }        if out.family.isEmpty { out.family = known.family }        if out.role.isEmpty { out.role = known.role }        if !known.options.isEmpty { out.options = known.options }        if !known.languageCodes.isEmpty { out.languageCodes = known.languageCodes }        out.level = known.level ?? out.level        out.files = files.map { file in            var file = file            if file.part.isEmpty, let named = known.files.first(where: { $0.name == file.name }) { file.part = named.part }            return file        }        return out    }}public struct VoiceModelsAnswer: Decodable, Sendable, Equatable {    public var models: [VoiceModelEntry]    /// The catalogue's voice-activity and language-identification models.    public var vad: String?    public var lid: String?    public init(models: [VoiceModelEntry], vad: String? = nil, lid: String? = nil) {        self.models = models        self.vad = vad        self.lid = lid    }    enum CodingKeys: String, CodingKey { case models, vad, lid }    public init(from decoder: any Decoder) throws {        // Either `{ models: [...] }` or the bare list.        if let c = try? decoder.container(keyedBy: CodingKeys.self),           let models = try c.decodeIfPresent([VoiceModelEntry].self, forKey: .models) {            self.models = models            vad = try c.decodeIfPresent(String.self, forKey: .vad)            lid = try c.decodeIfPresent(String.self, forKey: .lid)        } else {            models = try decoder.singleValueContainer().decode([VoiceModelEntry].self)        }    }}public struct VoiceModelChange: Encodable, Sendable, Equatable {    public var model: String    public var state: VoiceModelState    public var path: String?    public var bytesDone: Int64?    public init(model: String, state: VoiceModelState, path: String? = nil, bytesDone: Int64? = nil) {        self.model = model        self.state = state        self.path = path        self.bytesDone = bytesDone    }    enum CodingKeys: String, CodingKey {        case model, state, path        case bytesDone = "bytes_done"    }}// MARK: - voice.settings/// The person's voice settings — read here only for what the PHONE acts on/// (the mobile-data rule for downloads); the rest is the core's.public struct VoiceSettings: Decodable, Sendable, Equatable {    public struct Language: Decodable, Sendable, Equatable {        public var code: String        public var script: String?    }    public var languages: [Language]    /// `never`, `ask` or `always`: may a model download off Wi-Fi.    public var mobileData: String    public init(languages: [Language] = [], mobileData: String = "ask") {        self.languages = languages        self.mobileData = mobileData    }    /// Off Wi-Fi: `always` yes; `ask` yes when the person asked for this    /// download (a tap on the offer is the asking); `never` no.    public func mobileDataAllowed(asked: Bool) -> Bool {        mobileData == "always" || (mobileData == "ask" && asked)    }    enum CodingKeys: String, CodingKey {        case languages        case mobileData = "mobile_data"    }    public init(from decoder: any Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        languages = (try? c.decodeIfPresent([Language].self, forKey: .languages)) ?? []        mobileData = (try? c.decodeIfPresent(String.self, forKey: .mobileData)) ?? "ask"    }}