SPB Git

Repository Public

PredictionEngine.swift 27.3 KB 587 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/PredictionCore/PredictionEngine.swift10// Description      : Offline suggestion and autocorrection engine: completion,11//                    typo correction, context ranking, bounded cache.12// Module           : PredictionCore13// Repository       : https://git.spboucher.ai/sp-keyboard14// Created          : 2026-12-0115// Last Modified    : 2026-12-0116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091/// Runs entirely on device and never stores or logs what is typed: a query lives only in the bounded result cache,92/// which is dropped on `trimMemory()` and whenever a dictionary changes.93public actor PredictionEngine {94    private struct Loaded {95        let lexicon: Lexicon96        let bigrams: BigramTable97    }9899    private struct UserWord {100        let display: String101        let lower: String102        let folded: String103        let weight: Float104    }105106    private struct Candidate {107        var text: String108        var kind: Suggestion.Kind109        var score: Float110        var cost: Float111        var frequency: Float112        /// The text already contains the elision prefix ("j'ai" from the bigram table).113        var absolute = false114        /// Capitalised lexicon entry (a name, a place): offered, never an automatic replacement for a typo.115        var proper = false116    }117118    private enum CasePattern { case lower, firstUpper, allUpper, mixed }119120    private let provider: LexiconProviding121    private let cacheLimit: Int122    private var loaded: [LexiconLanguage: Loaded] = [:]123    private var lastUsed: LexiconLanguage?124    private var personal: [UserWord] = []125    private var learned: [UserWord] = []126    private var userLower: Set<String> = []127    private var supplementary: [String: String] = [:]128    private var cache: [PredictionQuery: (result: PredictionResult, tick: UInt64)] = [:]129    private var tick: UInt64 = 0130    /// Shape-writing indexes, built lazily per (language, key geometry); see `decodeGlide`.131    private var glideIndexes: [GlideIndexKey: GlideIndex] = [:]132133    private static let maxWordLength = 40134    /// Noisy-channel weight: how many natural-log units of frequency one unit of typing cost is worth.135    private static let costWeight: Float = 5136    private static let frenchElisions: Set<String> = [137        "j", "l", "qu", "c", "d", "n", "s", "t", "m", "jusqu", "lorsqu", "puisqu", "quoiqu", "quelqu", "presqu",138    ]139    private static let codeCharacters = Set("@/\\._:#$%&*+=<>[]{}()|~^`\"0123456789")140141    public init(provider: LexiconProviding, cacheLimit: Int = 256) {142        self.provider = provider143        self.cacheLimit = max(cacheLimit, 0)144    }145146    // MARK: Loading147148    public func load(_ language: LexiconLanguage) async throws {149        guard loaded[language] == nil else { return }150        let words = try provider.data(for: language, resource: .words)151        let lexicon = try Lexicon(data: words, language: language)152        // The bigram table only improves ranking: a missing or unreadable file must not disable the language.153        let bigrams = (try? provider.data(for: language, resource: .bigrams)).map(BigramTable.init(data:)) ?? .empty154        loaded[language] = Loaded(lexicon: lexicon, bigrams: bigrams)155        cache.removeAll()156        glideIndexes.removeAll()157    }158159    public func isLoaded(_ language: LexiconLanguage) -> Bool {160        loaded[language] != nil161    }162163    public func unload(_ language: LexiconLanguage) {164        loaded[language] = nil165        if lastUsed == language { lastUsed = nil }166        cache.removeAll()167        glideIndexes.removeAll()168    }169170    /// Drops the cache and every language but the last one used (memory warning).171    public func trimMemory() {172        cache.removeAll(keepingCapacity: false)173        glideIndexes.removeAll(keepingCapacity: false)174        for language in loaded.keys where language != lastUsed {175            loaded[language] = nil176        }177    }178179    /// Diagnostics: number of words and approximate bytes held for a language (0 when not loaded).180    public func footprint(of language: LexiconLanguage) -> (words: Int, bytes: Int) {181        guard let entry = loaded[language] else { return (0, 0) }182        return (entry.lexicon.count, entry.lexicon.estimatedBytes)183    }184185    /// Diagnostics: entries currently held by the result cache.186    public var cachedResultCount: Int { cache.count }187188    // MARK: User dictionaries189190    public func setPersonalWords(_ words: [String]) {191        personal = Self.userWords(words.map { ($0, 1) }, boost: 3)192        rebuildUserIndex()193    }194195    public func setLearnedWords(_ words: [String: Int]) {196        learned = Self.userWords(words.map { ($0.key, $0.value) }, boost: 1.5)197        rebuildUserIndex()198    }199200    public func setSupplementary(_ pairs: [String: String]) {201        var table: [String: String] = [:]202        for (input, text) in pairs.prefix(5_000) where !input.isEmpty && !text.isEmpty && input.count <= Self.maxWordLength {203            table[TextFolding.normalizeApostrophes(input).lowercased()] = text204        }205        supplementary = table206        cache.removeAll()207    }208209    private static func userWords(_ words: [(String, Int)], boost: Float) -> [UserWord] {210        var seen = Set<String>()211        var out: [UserWord] = []212        for (raw, count) in words.prefix(10_000) {213            let word = TextFolding.normalizeApostrophes(raw.trimmingCharacters(in: .whitespacesAndNewlines))214            guard !word.isEmpty, word.count <= maxWordLength, !word.contains(where: \.isWhitespace) else { continue }215            let lower = word.lowercased()216            guard seen.insert(lower).inserted else { continue }217            out.append(UserWord(display: word, lower: lower, folded: TextFolding.fold(word),218                                weight: boost + min(Float(max(count, 1)).squareRoot() * 0.25, 1.5)))219        }220        return out221    }222223    private func rebuildUserIndex() {224        userLower = Set(personal.map(\.lower)).union(learned.map(\.lower))225        cache.removeAll()226        glideIndexes.removeAll()227    }228229    // MARK: Prediction230231    public func predict(_ query: PredictionQuery) async -> PredictionResult {232        guard !Task.isCancelled, let language = loaded[query.language] else { return .empty }233        lastUsed = query.language234        tick &+= 1235        if let hit = cache[query] {236            cache[query] = (hit.result, tick)237            return hit.result238        }239        guard let result = compute(query, language) else { return .empty }240        if cacheLimit > 0 {241            if cache.count >= cacheLimit, let oldest = cache.min(by: { $0.value.tick < $1.value.tick })?.key {242                cache[oldest] = nil243            }244            cache[query] = (result, tick)245        }246        return result247    }248249    /// nil when the task was cancelled mid-way.250    private func compute(_ query: PredictionQuery, _ language: Loaded) -> PredictionResult? {251        let typed = TextFolding.normalizeApostrophes(query.currentWord)252        let contextKeys = Self.contextKeys(query)253        if typed.isEmpty {254            return nextWords(query, language, contextKeys)255        }256        guard typed.count <= Self.maxWordLength else { return .empty }257258        var leading: [Suggestion] = []259        if let replacement = supplementary[typed.lowercased()], replacement != typed {260            leading.append(Suggestion(text: replacement, kind: .shortcut, score: 100))261        }262        if typed.contains(where: { Self.codeCharacters.contains($0) }) || !typed.contains(where: \.isLetter) {263            return PredictionResult(suggestions: leading)264        }265266        let pattern = Self.casePattern(typed)267        // French elision: "j'ai", "l'école", "qu'il" are predicted on the part after the apostrophe.268        var prefix = ""269        var stem = typed270        if query.language == .french, let apostrophe = typed.lastIndex(of: "'") {271            let head = TextFolding.fold(String(typed[..<apostrophe]))272            if Self.frenchElisions.contains(head) {273                prefix = String(typed[...apostrophe])274                stem = String(typed[typed.index(after: apostrophe)...])275            }276        }277        guard !stem.isEmpty else { return PredictionResult(suggestions: leading) }278279        let lexicon = language.lexicon280        let stemLower = stem.lowercased()281        let stemFolded = TextFolding.fold(stem)282        let key = Array(stemFolded.utf8)283        let typedFolded = TextFolding.fold(typed)284        guard key.count <= Lexicon.maxKeyLength else { return PredictionResult(suggestions: leading) }285286        func render(_ candidate: Candidate) -> String {287            let full = candidate.absolute ? candidate.text : prefix + candidate.text288            switch pattern {289            case .allUpper: return full.uppercased()290            case .firstUpper: return Self.capitalized(full)291            case .lower, .mixed: return query.isSentenceStart ? Self.capitalized(full) : full292            }293        }294        func contextBonus(_ folded: String) -> Float {295            var best: Float = 0296            for (rank, head) in contextKeys.enumerated() where head != BigramTable.fallback {297                let weight = language.bigrams.weight(after: head, of: folded)298                if weight > 0 { best = max(best, weight * (rank == 0 && contextKeys.count > 2 ? 0.55 : 0.4)) }299            }300            return best301        }302303        // Is the typed word a word? Exact spelling, a capitalised lexicon form ("london"), or a user word.304        let exact = lexicon.exactRange(key)305        var known = userLower.contains(stemLower) || userLower.contains(typed.lowercased())306        var pool: [Candidate] = []307        var pronoun: Candidate?308        for index in exact {309            let word = lexicon.words[index]310            if word == stem || word == stemLower {311                known = true312                continue313            }314            // "j'a" must not become "j'à": a one-letter word is not what follows an elision.315            if !prefix.isEmpty, key.count == 1 { continue }316            let frequency = lexicon.logFrequency[index]317            var candidate = Candidate(text: word, kind: .correction, score: frequency + 3, cost: 0.05, frequency: frequency)318            if word.lowercased() == stemLower {319                // Only the capitalisation differs: the word exists, offer its proper form.320                known = true321                candidate.kind = .completion322                if query.language == .english, word == "I" || word.hasPrefix("I'") { pronoun = candidate }323            }324            pool.append(candidate)325        }326327        // Completions: binary-searched prefix range, best few by frequency.328        let elided = !prefix.isEmpty329        let prefixRange = lexicon.prefixRange(key)330        var completions: [Candidate] = []331        var visited = 0332        for index in prefixRange where !exact.contains(index) {333            visited += 1334            if visited & 1023 == 0, Task.isCancelled { return nil }335            if elided, !Self.startsWithVowelSound(lexicon.keyBytes[Int(lexicon.keyStart[index])]) { continue }336            let frequency = lexicon.logFrequency[index]337            let extra = Float(lexicon.keyRange(index).count - key.count)338            let score = frequency - 0.15 * extra339            if completions.count == 8, score <= completions[7].score { continue }340            Self.insert(Candidate(text: lexicon.words[index], kind: .completion, score: score, cost: 0, frequency: frequency),341                        into: &completions, limit: 8)342        }343        pool.append(contentsOf: completions)344345        // Corrections: only for an unknown word, bounded weighted Damerau-Levenshtein over nearby lengths.346        let protected = pattern == .mixed347        if !known, !protected, key.count >= 2 {348            let limit: Float = key.count <= 2 ? 0.5 : key.count <= 3 ? 0.75 : key.count <= 4 ? 1.0 : key.count <= 6 ? 1.4 : 2.0349            let window = limit <= 1.0 ? 1 : 2350            let maskBudget = limit <= 1.0 ? 2 : 4351            let mask = Lexicon.mask(of: key)352            let proximity = KeyProximity.table(for: query.geometry)353            var scratch = EditDistanceScratch()354            var corrections: [Candidate] = []355            var scanned = 0356            for length in max(1, key.count - window)...min(Lexicon.maxKeyLength, key.count + window) {357                for raw in lexicon.byLength[length] {358                    scanned += 1359                    if scanned & 2047 == 0, Task.isCancelled { return nil }360                    let index = Int(raw)361                    if (lexicon.letterMask[index] ^ mask).nonzeroBitCount > maskBudget { continue }362                    if exact.contains(index) { continue }363                    if elided, !Self.startsWithVowelSound(lexicon.keyBytes[Int(lexicon.keyStart[index])]) { continue }364                    guard let cost = EditDistance.cost(typed: key, candidate: lexicon.keyBytes, range: lexicon.keyRange(index),365                                                       proximity: proximity, limit: limit, scratch: &scratch) else { continue }366                    let frequency = lexicon.logFrequency[index]367                    let word = lexicon.words[index]368                    let proper = Self.isProperNoun(word, query.language)369                    let score = frequency - Self.costWeight * cost - (proper ? 3.5 : 0.5)370                    if corrections.count == 8, score <= corrections[7].score { continue }371                    Self.insert(Candidate(text: word, kind: .correction, score: score, cost: cost, frequency: frequency, proper: proper),372                                into: &corrections, limit: 8)373                }374            }375            pool.append(contentsOf: corrections)376        }377378        // Words the context makes likely, even when their frequency alone would not surface them.379        for head in contextKeys where head != BigramTable.fallback {380            for entry in language.bigrams.continuations(after: head) where entry.folded != typedFolded {381                if entry.folded.hasPrefix(typedFolded) {382                    pool.append(Candidate(text: entry.word, kind: .completion, score: -6, cost: 0, frequency: -6, absolute: true))383                }384            }385        }386387        // User words: always valid, boosted.388        for word in personal + learned where word.folded.hasPrefix(typedFolded) && word.lower != typed.lowercased() {389            pool.append(Candidate(text: word.display, kind: .personal, score: -4 + word.weight, cost: 0, frequency: 0, absolute: true))390        }391392        for index in pool.indices {393            let folded = TextFolding.fold(pool[index].absolute ? pool[index].text : prefix + pool[index].text)394            var bonus = contextBonus(folded)395            if !prefix.isEmpty, !pool[index].absolute { bonus = max(bonus, contextBonus(TextFolding.fold(pool[index].text))) }396            pool[index].score += bonus397        }398        pool.sort { $0.score == $1.score ? $0.text < $1.text : $0.score > $1.score }399400        // Autocorrection: a confident, unambiguous fix of an unknown lowercase (or sentence-initial) word.401        var autocorrection: Suggestion?402        if query.autocorrectionEnabled, leading.isEmpty, !protected, pattern != .allUpper,403           pattern != .firstUpper || query.isSentenceStart {404            if let pronoun {405                autocorrection = Suggestion(text: render(pronoun), kind: .correction, score: Double(pronoun.score))406            } else if !known, key.count >= 2 {407                let fixes = pool.filter { $0.kind == .correction && !$0.proper }408                if let best = fixes.first, !Profanity.folded.contains(TextFolding.fold(best.text)) {409                    let margin = fixes.count > 1 ? best.score - fixes[1].score : Float.infinity410                    let confident: Bool411                    if best.cost <= 0.1 {412                        confident = margin >= 0.7413                    } else if best.cost <= 0.75 {414                        // Cheap slips: transposition, neighbouring key, doubled letter, missing apostrophe.415                        confident = best.frequency >= -10.5 && margin >= 1.0416                    } else if best.cost <= 1.0 {417                        // One full-price edit: only towards a common word that clearly dominates.418                        confident = best.frequency >= -9.5 && margin >= 1.5419                    } else {420                        confident = key.count >= 7 && best.cost <= 1.6 && best.frequency >= -8.5 && margin >= 2.5421                    }422                    if confident {423                        autocorrection = Suggestion(text: render(best), kind: .correction, score: Double(best.score))424                    }425                }426            }427        }428429        // Bar: [shortcut] [verbatim when unknown] [autocorrection] then the best of the rest; three at most.430        var texts = Set<String>()431        var ranked: [Suggestion] = []432        for candidate in pool {433            let text = render(candidate)434            guard text != typed, texts.insert(text).inserted else { continue }435            ranked.append(Suggestion(text: text, kind: candidate.kind, score: Double(candidate.score)))436            if ranked.count >= 6 { break }437        }438        var suggestions = leading439        if !known, !ranked.isEmpty, key.count >= 2 {440            suggestions.append(Suggestion(text: typed, kind: .verbatim, score: 0))441        }442        if let autocorrection {443            suggestions.append(autocorrection)444        }445        for suggestion in ranked where suggestions.count < 3 {446            if !suggestions.contains(where: { $0.text == suggestion.text }) { suggestions.append(suggestion) }447        }448        return PredictionResult(suggestions: Array(suggestions.prefix(3)), autocorrection: autocorrection)449    }450451    private func nextWords(_ query: PredictionQuery, _ language: Loaded, _ contextKeys: [String]) -> PredictionResult {452        var suggestions: [Suggestion] = []453        var seen = Set<String>()454        for (rank, head) in contextKeys.enumerated() {455            for entry in language.bigrams.continuations(after: head) {456                let text = query.isSentenceStart ? Self.capitalized(entry.word) : entry.word457                guard seen.insert(text.lowercased()).inserted else { continue }458                suggestions.append(Suggestion(text: text, kind: .nextWord, score: Double(entry.weight) - Double(rank) * 10))459                if suggestions.count == 3 { return PredictionResult(suggestions: suggestions) }460            }461        }462        return PredictionResult(suggestions: suggestions)463    }464465    // MARK: Glide typing466467    private struct GlideIndexKey: Hashable {468        let language: LexiconLanguage469        let layout: GlideLayout470    }471472    /// Decodes a finger trace (raw touch points, in the coordinates of `layout`) into candidate words, best first.473    /// Words come back in their lexicon form; capitalising a sentence start is the caller's business. Empty when474    /// the language is not loaded, the trace is a tap (shorter than 0.6 key width) or the task was cancelled.475    public func decodeGlide(path: [SIMD2<Double>], layout: GlideLayout, language: LexiconLanguage,476                            previousWords: [String], limit: Int = 4) -> [GlideCandidate] {477        guard limit > 0, path.count >= 2, !Task.isCancelled, let entry = loaded[language] else { return [] }478        lastUsed = language479        let key = GlideIndexKey(language: language, layout: layout)480        let index: GlideIndex481        if let cached = glideIndexes[key] {482            index = cached483        } else {484            // One geometry at a time is live (rotation and one-handed mode replace it): keep the two most recent.485            if glideIndexes.count >= 2 { glideIndexes.removeAll() }486            let user = (personal + learned).map { GlideUserWord(display: $0.display, logFrequency: -4 + $0.weight) }487            index = GlideIndex(lexicon: entry.lexicon, userWords: user, layout: layout)488            glideIndexes[key] = index489        }490        let query = PredictionQuery(currentWord: "", previousWords: previousWords, language: language,491                                    isSentenceStart: previousWords.isEmpty)492        let heads = Self.contextKeys(query).filter { $0 != BigramTable.fallback }493        return index.decode(path: path, lexicon: entry.lexicon, limit: limit) { folded in494            var best: Float = 0495            for (rank, head) in heads.enumerated() {496                let weight = entry.bigrams.weight(after: head, of: folded)497                if weight > 0 { best = max(best, weight * (rank == 0 && heads.count > 1 ? 0.55 : 0.4)) }498            }499            return best500        }501    }502503    /// Diagnostics: shape-writing indexes currently held.504    public var glideIndexCount: Int { glideIndexes.count }505506    // MARK: Touch model507508    /// Share of the lexicon's usage that continues `prefix` with each letter (folded: "e" stands for é, è, ê…).509    /// The typing surface uses it to settle touches that land between two keys. Empty for an empty prefix, an510    /// unloaded language or a prefix no word starts with.511    public func nextLetterWeights(prefix: String, language: LexiconLanguage) -> [Character: Double] {512        let folded = Array(TextFolding.fold(TextFolding.normalizeApostrophes(prefix)).utf8)513        guard !folded.isEmpty, folded.count < Lexicon.maxKeyLength, let lexicon = loaded[language]?.lexicon else { return [:] }514        var mass = [Double](repeating: 0, count: 256)515        var total = 0.0516        for index in lexicon.prefixRange(folded) {517            let range = lexicon.keyRange(index)518            guard range.count > folded.count else { continue }519            let weight = Double(exp(lexicon.logFrequency[index]))520            mass[Int(lexicon.keyBytes[range.lowerBound + folded.count])] += weight521            total += weight522        }523        guard total > 0 else { return [:] }524        var weights: [Character: Double] = [:]525        for byte in UInt8(ascii: "a")...UInt8(ascii: "z") where mass[Int(byte)] > 0 {526            weights[Character(UnicodeScalar(byte))] = mass[Int(byte)] / total527        }528        return weights529    }530531    // MARK: Helpers532533    /// Bigram heads to consult, most specific first: "prev2 prev1", "prev1" (or "<s>"), then the generic fallback.534    private static func contextKeys(_ query: PredictionQuery) -> [String] {535        var keys: [String] = []536        let previous = query.previousWords.map { TextFolding.fold(TextFolding.normalizeApostrophes($0)) }.filter { !$0.isEmpty }537        if query.isSentenceStart || previous.isEmpty {538            if query.isSentenceStart { keys.append(BigramTable.sentenceStart) }539        } else {540            if previous.count >= 2 { keys.append(previous[previous.count - 2] + " " + previous[previous.count - 1]) }541            keys.append(previous[previous.count - 1])542        }543        keys.append(BigramTable.fallback)544        return keys545    }546547    private static func casePattern(_ word: String) -> CasePattern {548        var letters = 0, upper = 0, firstUpper = false549        for character in word where character.isLetter {550            if character.isUppercase {551                upper += 1552                if letters == 0 { firstUpper = true }553            }554            letters += 1555        }556        if upper == 0 { return .lower }557        if letters >= 2, upper == letters { return .allUpper }558        if upper == 1, firstUpper { return .firstUpper }559        return .mixed560    }561562    private static func isProperNoun(_ word: String, _ language: LexiconLanguage) -> Bool {563        guard let first = word.first, first.isUppercase else { return false }564        return !(language == .english && (word == "I" || word.hasPrefix("I'")))565    }566567    private static func capitalized(_ text: String) -> String {568        guard let first = text.first, first.isLowercase else { return text }569        return first.uppercased() + text.dropFirst()570    }571572    private static func startsWithVowelSound(_ byte: UInt8) -> Bool {573        switch byte {574        case 0x61, 0x65, 0x69, 0x6F, 0x75, 0x79, 0x68: true  // a e i o u y h575        default: false576        }577    }578579    /// Keeps `list` sorted by decreasing score and at most `limit` long.580    private static func insert(_ candidate: Candidate, into list: inout [Candidate], limit: Int) {581        var position = list.count582        while position > 0, list[position - 1].score < candidate.score { position -= 1 }583        list.insert(candidate, at: position)584        if list.count > limit { list.removeLast() }585    }586}587
Files main
Menu

Theme