Cotton code
505 lines · 23.7 KB · SwiftRaw
// The person's own dictation language model, compiled ON THIS DEVICE from// their names and their own phrasing, so the recogniser expects the words they// actually say — "Anvika Rathore", "Koramangala", "the Kestrel invoice" — and// not the English words that sound nearest.//// The source is `read.voiceCorpus` (the Rust core: every name the device's kept// voice pass holds, tagged as the hints are — words and names only, never a// whole text). From it this file builds the system's custom language model// data — the names in short spoken frames ("call <person>", "in <place>") and a// phonetic spelling for each name that reads as romanized Indic// (`NamePhonetics`) — and has the system compile// it (`SFSpeechLanguageModel.prepareCustomLanguageModel`). Dictation then hands// the compiled model to `DictationTranscriber` as// `.customizedLanguage(modelConfiguration:)`, beside the screen's ranked// hundred contextual strings, which stay.//// THE MODEL NEVER LEAVES THE DEVICE. It is written under the app's own// Application Support (never a database file, never a synced folder), marked// excluded from backup, never attached to a report; compiling calls no network// and no model — the system's compiler runs on device over the files written// here. Guards: `VoiceModelTests`.//// TWO PREPARES, MEASURED 14 Oct 2026 (macOS 27, en-IN): a model is heard only// in a process that ran `prepareCustomLanguageModel(ignoresCache: true)` over an// ALREADY-COMPILED model. The first prepare writes the files and is silently// ignored by every session after it, in this process and the next; a second// prepare over the written files is what the recogniser then uses. So// `compile` writes, and `load` — run once per process for every model it// will dictate with — prepares again.//// A CORE OF THE SERVING MAC, MEASURED 19 Oct 2026: the corpus then carried the// person's own lines and a name-pair frame, 237 MB per build, rebuilt on every// change, never cleaned — 83 builds and 18 GB in five days, and the system's// compiler at 99% of a core for 23 hours. So the corpus is names only, a build// runs at most once a day and only when the names moved, at background// priority, and a ready build deletes every other one.import CottonKitimport CottonSpeechimport CryptoKitimport Foundationimport Speech#if os(iOS)    import UIKit#elseif os(macOS)    import IOKit.ps#endif/// What the model is compiled from.public struct VoiceCorpus: Sendable, Equatable {    /// Every name, grouped by why it is there (manual, people, places,    /// projects, screen) — the hints' own tags.    public let names: [DictationHints.Group]    /// The person's language (BCP-47), when their setting names one.    public let language: String?    public init(names: [DictationHints.Group], language: String? = nil) {        self.names = names        self.language = language    }    /// `read.voiceCorpus`'s answer: `{names: [{tag, terms}], language?}`.    public init(_ read: JSONValue) {        names = (read["names"]?.array ?? []).compactMap { group in            guard let tag = group["tag"]?.string else { return nil }            return DictationHints.Group(tag: tag, terms: group["terms"]?.strings ?? [])        }        language = read["language"]?.string    }    /// Which model this corpus compiles to, for `locale`: equal corpora answer    /// the same fingerprint on every device, and a changed name changes it.    public func fingerprint(locale: String) -> String {        var canonical = "v\(VoiceModelCompiler.version)\n\(locale)\n"        for group in names { canonical += "#\(group.tag)\n" + group.terms.joined(separator: "\n") + "\n" }        return SHA256.hash(data: Data(canonical.utf8)).map { String(format: "%02x", $0) }.joined()    }    func terms(_ tag: String) -> [String] { names.first { $0.tag == tag }?.terms ?? [] }}/// A compiled model on this device, for one locale: what the recogniser is/// handed. Paths only — the model itself stays where it was written.public struct VoiceModelFiles: Sendable, Equatable {    public let locale: String    public let fingerprint: String    public let languageModel: URL    public let vocabulary: URL    init(locale: String, fingerprint: String, folder: URL) {        self.locale = locale        self.fingerprint = fingerprint        languageModel = folder.appendingPathComponent("model")        vocabulary = folder.appendingPathComponent("vocabulary")    }    var folder: URL { languageModel.deletingLastPathComponent() }    /// The system's model data the model was compiled from.    var source: URL { folder.appendingPathComponent("corpus.bin") }    var isWritten: Bool {        [languageModel, vocabulary, source].allSatisfy { FileManager.default.fileExists(atPath: $0.path) }    }}/// The two steps a model takes, behind a seam so the keeper's timing is/// tested without the system compiler.public protocol VoiceModelCompiling: Sendable {    /// Write the model for `corpus` into `files`' folder.    func compile(_ corpus: VoiceCorpus, locale: Locale, into files: VoiceModelFiles) async throws    /// Make a written model the one this process's recogniser hears with.    func load(_ files: VoiceModelFiles, locale: Locale) async throws}/// The system's compiler, on device.public struct VoiceModelCompiler: VoiceModelCompiling {    /// Bumped when what is compiled from a corpus changes, so every device    /// recompiles once — and, as the folder's layout, clears every model an    /// earlier version wrote (`VoiceModelKeeper.clearEarlierLayout`).    public static let version = 2    /// How often a name is said in each frame. Short frames — what a person    /// says AROUND a name — rather than whole sentences, so the model learns    /// the name's company, not a script. One class per frame: a frame naming    /// two is every pair of names, the square of the vocabulary (the 237 MB of    /// 19 Oct 2026).    static let templates: [(String, Int)] = [        ("<person>", 40), ("with <person>", 12), ("to <person>", 12), ("call <person>", 12),        ("ask <person>", 10), ("tell <person>", 8), ("message <person>", 8),        ("<place>", 20), ("in <place>", 12), ("at <place>", 12), ("to <place>", 10), ("from <place>", 6),        ("<project>", 20), ("the <project>", 12), ("about <project>", 8), ("for <project>", 8),        ("<name>", 10),    ]    public init() {}    public func compile(_ corpus: VoiceCorpus, locale: Locale, into files: VoiceModelFiles) async throws {        try FileManager.default.createDirectory(at: files.folder, withIntermediateDirectories: true)        try await Self.data(corpus, locale: locale, version: String(files.fingerprint.prefix(16))).export(to: files.source)        try await prepare(files)    }    /// The second prepare, over the same source and the model it wrote — the    /// source stays beside the model for exactly this (on this device, in the    /// same excluded folder).    public func load(_ files: VoiceModelFiles, locale: Locale) async throws {        try await prepare(files)    }    private func prepare(_ files: VoiceModelFiles) async throws {        let configuration = SFSpeechLanguageModel.Configuration(languageModel: files.languageModel, vocabulary: files.vocabulary)        try await SFSpeechLanguageModel.prepareCustomLanguageModel(for: files.source, configuration: configuration, ignoresCache: true)    }    static let identifier = (Bundle.main.bundleIdentifier ?? "cotton") + ".dictation"    /// The system's model data for a corpus: the names in their frames, each    /// name on its own, and the spellings.    static func data(_ corpus: VoiceCorpus, locale: Locale, version: String) -> SFCustomLanguageModelData {        let data = SFCustomLanguageModelData(locale: locale, identifier: identifier, version: version)        let people = corpus.terms("people") + corpus.terms("manual")        // A person is called by their first name as often as their whole one.        let firstNames = people.compactMap { name -> String? in            let parts = name.split(separator: " ")            return parts.count > 1 ? String(parts[0]) : nil        }        let classes: [String: [String]] = [            "person": unique(people + firstNames),            "place": unique(corpus.terms("places")),            "project": unique(corpus.terms("projects")),            "name": unique(corpus.terms("screen")),        ]        let generator = SFCustomLanguageModelData.TemplatePhraseCountGenerator()        for (name, values) in classes where !values.isEmpty {            generator.define(className: name, values: values)        }        for (template, count) in templates        where classes.allSatisfy({ name, values in !values.isEmpty || !template.contains("<\(name)>") }) {            generator.insert(template: template, count: count)        }        data.insert(phraseCountGenerator: generator)        for (grapheme, readings) in pronunciations(people + corpus.terms("places"), locale: locale) {            data.insert(term: SFCustomLanguageModelData.CustomPronunciation(grapheme: grapheme, phonemes: readings))        }        return data    }    /// Each name word's spellings that the locale's recogniser accepts: every    /// phoneme in a reading must be one the locale names, or the reading goes —    /// a spelling is never bent to fit.    static func pronunciations(_ names: [String], locale: Locale) -> [(String, [String])] {        let accepted = Set(SFCustomLanguageModelData.supportedPhonemes(locale: locale))        var seen = Set<String>()        var out: [(String, [String])] = []        for name in names {            for (grapheme, readings) in NamePhonetics.words(of: name) where seen.insert(grapheme.lowercased()).inserted {                let fits = readings.filter { reading in reading.split(separator: " ").allSatisfy { accepted.contains(String($0)) } }                if !fits.isEmpty { out.append((grapheme, fits)) }            }        }        return out    }    private static func unique(_ terms: [String]) -> [String] {        var seen = Set<String>()        return terms.filter { !$0.isEmpty && seen.insert($0.lowercased()).inserted }    }}/// Keeps the compiled model current: reads the corpus when it may have/// changed, debounced, recompiles when its fingerprint moved — at most once in/// `Timing.interval`, at background priority, on power when it can — and loads/// the model into this process so dictation hears with it.////// On disk, per locale: `VoiceModel/<locale>/<fingerprint>/` (the one model/// in use: `corpus.bin`, `model`, `vocabulary`) and `VoiceModel/<locale>/built`/// (when it was compiled); `VoiceModel/layout` names the version that wrote/// the folder.@MainActorpublic final class VoiceModelKeeper {    public static let shared = VoiceModelKeeper()    public struct Timing: Sendable {        /// From the last change to the corpus read: a burst of edits is one        /// compile.        public var debounce: Duration        /// On battery, how much longer a compile waits for power before it        /// runs anyway — preferred, never required.        public var batteryGrace: Duration        /// At most one compile per locale in this long: a name that moves        /// within the day waits for the day to end, while the model already        /// written serves.        public var interval: Duration        public init(debounce: Duration = .seconds(30), batteryGrace: Duration = .seconds(600), interval: Duration = .seconds(86_400)) {            self.debounce = debounce            self.batteryGrace = batteryGrace            self.interval = interval        }    }    /// Compiling and loading run at background priority: the system's    /// compiler (`localspeechrecognition`) works at the priority it is asked    /// at, and on the serving Mac it must never take a core from the app that    /// serves (item 29, 19 Oct 2026).    nonisolated static let buildPriority: TaskPriority = .background    private let compiler: any VoiceModelCompiling    private let root: URL    private let timing: Timing    private let onPower: @MainActor () -> Bool    private let resolve: @Sendable (Locale) async -> Locale?    private let now: @Sendable () -> Date    private var read: (@Sendable () async -> VoiceCorpus?)?    /// Loaded in THIS process, by resolved locale.    private var ready: [String: VoiceModelFiles] = [:]    /// The fingerprint being compiled or loaded, by locale.    private var pending: [String: String] = [:]    private var debounced: Task<Void, Never>?    private var work: [String: Task<Void, Never>] = [:]    private var passed = false    public init(        compiler: any VoiceModelCompiling = VoiceModelCompiler(),        root: URL = VoiceModelKeeper.defaultRoot(),        timing: Timing = Timing(),        onPower: @escaping @MainActor () -> Bool = VoiceModelKeeper.isOnPower,        resolve: @escaping @Sendable (Locale) async -> Locale? = VoiceModelKeeper.transcriberLocale,        now: @escaping @Sendable () -> Date = Date.init    ) {        self.compiler = compiler        self.root = root        self.timing = timing        self.onPower = onPower        self.resolve = resolve        self.now = now    }    /// The core to read the corpus from — `read.voiceCorpus`, answered on    /// device.    public func attach(_ core: any CottonCalling) {        attach { try? await VoiceCorpus(core.callJSON(CottonMethod.readVoiceCorpus)) }    }    func attach(_ read: @escaping @Sendable () async -> VoiceCorpus?) {        self.read = read    }    /// A `data` event: names live in records and the vocabulary, phrasing in    /// thoughts and sent messages; any of them moving MAY change the corpus.    public func receive(_ event: ClientEvent) {        guard case .data(let tables, _, _) = event,            tables.contains(where: Self.sources.contains) else { return }        changed()    }    /// The voice pass republishes this table whenever a name it holds moved    /// (`voice_words::refresh`), so the records themselves need not be listed.    static let sources: Set<String> = ["cotton_voice_vocabulary", "cotton_inbox_items", "cotton_msg_messages"]    /// Something the corpus is read from moved: read it after the debounce,    /// every further change restarting the wait.    public func changed() {        debounced?.cancel()        let wait = timing.debounce        debounced = Task { [weak self] in            try? await Task.sleep(for: wait)            guard !Task.isCancelled else { return }            await self?.pass()        }    }    /// The first microphone of a process reads the corpus at once (a model    /// compiled earlier is loaded, not recompiled); later ones read nothing.    public func ensure() {        guard !passed else { return }        passed = true        Task { [weak self] in await self?.pass() }    }    /// The model dictation in `language`'s locale hears with, when this    /// process has one loaded.    public func model(for requested: Locale) async -> VoiceModelFiles? {        guard let locale = await resolve(requested) else { return nil }        return ready[locale.identifier]    }    func pass() async {        passed = true        guard let read, let corpus = await read() else { return }        let requested = DictationHints(language: corpus.language).locale        guard let locale = await resolve(requested) else { return }        observe(corpus, locale: locale)    }    /// Bring `locale`'s model to `corpus`: nothing when it already is; a model    /// already written for exactly this corpus is loaded; otherwise the last    /// written one serves while the new one waits out the day and compiles.    /// Before any of it, the first pass after a layout change clears every    /// model an earlier version wrote.    func observe(_ corpus: VoiceCorpus, locale: Locale) {        let key = locale.identifier        let fingerprint = corpus.fingerprint(locale: key)        guard ready[key]?.fingerprint != fingerprint, pending[key] != fingerprint else { return }        pending[key] = fingerprint        work[key]?.cancel()        let folder = folder(key)        let files = VoiceModelFiles(locale: key, fingerprint: fingerprint, folder: folder.appendingPathComponent(fingerprint))        work[key] = Task(priority: Self.buildPriority) { [weak self, compiler, timing, root, now] in            await Self.clearEarlierLayout(root)            if files.isWritten {                await self?.loaded(files, locale: locale, compiler: compiler)                return            }            if self?.ready[key] == nil, let earlier = await Self.written(folder).first(where: { $0.fingerprint != fingerprint }) {                await self?.loaded(earlier, locale: locale, compiler: compiler, keep: true)            }            if let built = Self.built(folder) {                // A stamp from a clock set back never holds a build past one interval.                let wait = min(timing.interval, timing.interval - .seconds(now().timeIntervalSince(built)))                if wait > .zero {                    Log.write("voice model: \(key) changed; compiles once the day is out")                    try? await Task.sleep(for: wait)                }            }            if let self, !self.onPower() { try? await Task.sleep(for: timing.batteryGrace) }            guard !Task.isCancelled else { return }            do {                try await compiler.compile(corpus, locale: locale, into: files)            } catch {                Log.write("voice model: compile failed for \(key): \(error)")                self?.pending[key] = nil                return            }            Self.stamp(folder, now())            guard !Task.isCancelled else { return }            await self?.loaded(files, locale: locale, compiler: compiler)        }    }    private func loaded(_ files: VoiceModelFiles, locale: Locale, compiler: any VoiceModelCompiling, keep: Bool = false) async {        do {            try await compiler.load(files, locale: locale)        } catch {            Log.write("voice model: load failed for \(files.locale): \(error)")            if !keep { pending[files.locale] = nil }            return        }        guard keep || pending[files.locale] == files.fingerprint else { return }        ready[files.locale] = files        guard !keep else { return }        pending[files.locale] = nil        Log.write("voice model: \(files.locale) \(files.fingerprint.prefix(12)) ready")        await Self.keepOnly(files)    }    private func folder(_ locale: String) -> URL { root.appendingPathComponent(locale, isDirectory: true) }    // MARK: - On disk    nonisolated static let builtName = "built"    nonisolated static let layoutName = "layout"    /// One model per locale stays on disk: the one in use. Everything else in    /// the locale's folder — older models, half-written ones — goes.    nonisolated static func keepOnly(_ files: VoiceModelFiles) async {        let folder = files.folder.deletingLastPathComponent()        let entries = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []        for entry in entries where entry.lastPathComponent != files.fingerprint && entry.lastPathComponent != builtName {            try? FileManager.default.removeItem(at: entry)        }    }    /// The first pass after the folder's layout changed deletes every model    /// and every stamp an earlier version wrote, in every locale, before    /// anything is loaded or compiled — the version-1 models were 237 MB each    /// and never cleaned.    nonisolated static func clearEarlierLayout(_ root: URL) async {        let layout = root.appendingPathComponent(layoutName)        let current = "\(VoiceModelCompiler.version)"        if (try? String(contentsOf: layout, encoding: .utf8)) == current { return }        let entries = (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []        for entry in entries where entry.lastPathComponent != layoutName {            try? FileManager.default.removeItem(at: entry)        }        try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)        try? Data(current.utf8).write(to: layout, options: .atomic)        Log.write("voice model: cleared \(entries.count) entries an earlier layout wrote")    }    /// When the locale's last model was compiled.    nonisolated static func built(_ folder: URL) -> Date? {        guard let text = try? String(contentsOf: folder.appendingPathComponent(builtName), encoding: .utf8),            let seconds = TimeInterval(text) else { return nil }        return Date(timeIntervalSince1970: seconds)    }    nonisolated static func stamp(_ folder: URL, _ date: Date) {        try? Data("\(date.timeIntervalSince1970)".utf8).write(to: folder.appendingPathComponent(builtName), options: .atomic)    }    /// Every model written in a locale's folder, newest first.    nonisolated static func written(_ folder: URL) async -> [VoiceModelFiles] {        let locale = folder.lastPathComponent        let folders = (try? FileManager.default.contentsOfDirectory(            at: folder, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []        return folders            .map { VoiceModelFiles(locale: locale, fingerprint: $0.lastPathComponent, folder: $0) }            .filter(\.isWritten)            .sorted {                let a = (try? $0.folder.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast                let b = (try? $1.folder.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast                return a > b            }    }    // MARK: - Where, and when    /// The locale dictation listens in for `requested` — the recogniser's own    /// resolution, so the model is compiled for exactly the locale it is    /// handed in.    public nonisolated static func transcriberLocale(_ requested: Locale) async -> Locale? {        await SpeechModel.locale(DictationTranscriber.self, for: requested)    }    /// `Application Support/<this app's bundle id>/VoiceModel` — this app's own    /// folder (a development build's is its own), never a database folder,    /// and excluded from backup: the model is rebuilt from the records, which    /// are what is backed up.    public nonisolated static func defaultRoot() -> URL {        let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]        var root = support            .appendingPathComponent(Bundle.main.bundleIdentifier ?? "cotton", isDirectory: true)            .appendingPathComponent("VoiceModel", isDirectory: true)        excludeFromBackup(&root)        return root    }    nonisolated static func excludeFromBackup(_ root: inout URL) {        try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)        var values = URLResourceValues()        values.isExcludedFromBackup = true        try? root.setResourceValues(values)    }    /// Plugged in (or charging). Unknown counts as on power: a desktop Mac    /// has no battery to spare.    public static func isOnPower() -> Bool {        #if os(iOS)            UIDevice.current.isBatteryMonitoringEnabled = true            switch UIDevice.current.batteryState {            case .charging, .full: return true            case .unplugged: return false            case .unknown: return true            @unknown default: return true            }        #elseif os(macOS)            guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),                let type = IOPSGetProvidingPowerSourceType(info)?.takeUnretainedValue() as String?            else { return true }            return type != kIOPSBatteryPowerValue        #else            return true        #endif    }}