Cotton code
168 lines · 7.0 KB · SwiftRaw
// The snap: after a dictation settles, a word the model nearly heard as one of// the person's names BECOMES that name.//// The contextual strings bias the model towards the hinted names, but a model// still writes "Rathor" for "Rathore" or "Kohly" for "Kohli". The snap is the// deterministic second chance, and it is deliberately narrow — a wrong snap// puts a name where a person said something else, which is worse than the// near-miss it was meant to fix:////   • **Only a near-miss snaps.** Within an edit distance that scales with the//     name's length (none for a name of three letters or fewer, one up to five,//     two up to eight, three beyond), compared without case.//   • **A word of the language never snaps**, however near a name it is: "Rohan"//     is a name, "roan" is a horse, and the person may have meant the horse.//     The dictionary is the system's own spell checker in the dictation's//     language. A name part that is itself a word ("Desk" of "Juniper Desk") is//     no candidate either: its near-misses are words too.//   • **Two names equally near leave the word alone.** The snap never guesses.//// It edits nothing else — no case, no punctuation, no spacing — so "what the// recogniser said is what lands" (Dictation.swift's header) still holds for// every word that is not a hinted name. Guard: `DictationSnapTests`.import Foundation#if canImport(UIKit)import UIKit#elseif canImport(AppKit)import AppKit#endifpublic enum DictationSnap {    /// Whether `word` is a word of `language` (a BCP-47 tag) — the snap's    /// dictionary check.    public typealias Dictionary = @MainActor (_ word: String, _ language: String) -> Bool    /// `text` with every near-miss of a hinted name replaced by that name.    @MainActor    public static func apply(        _ text: String, names: [String], language: String, isWord: Dictionary    ) -> String {        let candidates = parts(of: names, language: language, isWord: isWord)        guard !candidates.isEmpty else { return text }        var out = ""        var rest = text[...]        while let token = rest.firstRange(of: /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*/) {            out += rest[rest.startIndex..<token.lowerBound]            out += snap(String(rest[token]), to: candidates, language: language, isWord: isWord)            rest = rest[token.upperBound...]        }        return out + rest    }    /// The settled words, each snapped the same way. A word the snap changed    /// carries no confidence: the model was not confident in THAT word.    @MainActor    public static func apply(        _ words: [HeardWord], names: [String], language: String, isWord: Dictionary    ) -> [HeardWord] {        words.map { word in            let snapped = apply(word.text, names: names, language: language, isWord: isWord)            return snapped == word.text ? word : HeardWord(text: snapped, confidence: nil)        }    }    /// The dictionary's language for a dictation's locale: `en_IN`, `hi`.    public static func language(of locale: Locale) -> String {        guard let code = locale.language.languageCode?.identifier else { return locale.identifier }        guard let region = locale.region?.identifier else { return code }        return code + "_" + region    }    /// How far a token may be from a name of this length and still snap.    static func allowance(_ length: Int) -> Int {        switch length {        case ...3: 0        case ...5: 1        case ...8: 2        default: 3        }    }    /// The single words of the hinted names that are not words themselves.    @MainActor    private static func parts(of names: [String], language: String, isWord: Dictionary) -> [String] {        var seen = Set<String>()        return names            .flatMap { $0.split(whereSeparator: \.isWhitespace).map(String.init) }            .filter { part in                part.count > 3 && !isWord(part, language) && seen.insert(part.lowercased()).inserted            }    }    @MainActor    private static func snap(        _ token: String, to candidates: [String], language: String, isWord: Dictionary    ) -> String {        // A possessive keeps its ending: "Rathor's" snaps as "Rathor".        var stem = token        var ending = ""        for suffix in ["'s", "’s"] where token.lowercased().hasSuffix(suffix) {            stem = String(token.dropLast(suffix.count))            ending = String(token.suffix(suffix.count))        }        let said = stem.lowercased()        guard stem.count > 3, !candidates.contains(where: { $0.lowercased() == said }),              !isWord(stem, language)        else { return token }        var best: [String] = []        var bestDistance = Int.max        for name in candidates {            let limit = allowance(name.count)            guard abs(name.count - stem.count) <= limit else { continue }            let distance = editDistance(said, name.lowercased())            guard distance <= limit else { continue }            if distance < bestDistance {                best = [name]                bestDistance = distance            } else if distance == bestDistance {                best.append(name)            }        }        guard best.count == 1, let name = best.first else { return token }        return name + ending    }    static func editDistance(_ a: String, _ b: String) -> Int {        let a = Array(a), b = Array(b)        guard !a.isEmpty else { return b.count }        guard !b.isEmpty else { return a.count }        var row = Array(0...b.count)        for i in 1...a.count {            var previous = row[0]            row[0] = i            for j in 1...b.count {                let above = row[j]                row[j] = min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] == b[j - 1] ? 0 : 1))                previous = above            }        }        return row[b.count]    }    /// The system's spell checker, in the dictation's language: a word it does    /// not flag is a word of the language.    @MainActor    public static func systemDictionary(_ word: String, _ language: String) -> Bool {        #if canImport(UIKit)        let checker = UITextChecker()        let languages = UITextChecker.availableLanguages        let tag = language.replacingOccurrences(of: "-", with: "_")        let chosen = languages.first { $0 == tag }            ?? languages.first { $0.hasPrefix(String(tag.prefix(while: { $0 != "_" })) + "_") || $0 == tag }        guard let chosen else { return false }        let range = NSRange(location: 0, length: (word as NSString).length)        return checker.rangeOfMisspelledWord(            in: word, range: range, startingAt: 0, wrap: false, language: chosen        ).location == NSNotFound        #elseif canImport(AppKit)        let checker = NSSpellChecker.shared        let range = checker.checkSpelling(            of: word, startingAt: 0, language: language, wrap: false,            inSpellDocumentWithTag: 0, wordCount: nil)        return range.location == NSNotFound        #else        return false        #endif    }}