Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/PredictionCore/Lexicon.swift10// Description : Compact in-memory word index: sorted folded keys in one11// byte blob, binary search, length buckets.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/// One language's word list. Memory layout is deliberately flat (a byte blob plus parallel arrays): the keyboard92/// extension has a small memory budget, so there is no trie node graph and no symmetric-delete table.93struct Lexicon: Sendable {94 static let maxEntries = 200_00095 static let maxKeyLength = 409697 /// Display forms ("école", "Paris", "I'm"), sorted by folded key.98 let words: [String]99 /// Folded keys, concatenated UTF-8.100 let keyBytes: [UInt8]101 /// `keyStart[i] ..< keyStart[i + 1]` is the folded key of entry i.102 let keyStart: [UInt32]103 /// log(count) − log(max count): 0 for the most frequent word, negative below.104 let logFrequency: [Float]105 /// Bag-of-letters signature (bit n = letter n is present) used to prune edit-distance candidates.106 let letterMask: [UInt32]107 /// Entry indices grouped by folded key length (index = length, capped).108 let byLength: [[Int32]]109110 var count: Int { words.count }111112 /// Approximate resident size, for diagnostics.113 var estimatedBytes: Int {114 words.count * (MemoryLayout<String>.stride + MemoryLayout<UInt32>.stride * 2 + MemoryLayout<Float>.stride115 + MemoryLayout<Int32>.stride) + keyBytes.count116 }117118 init(data: Data, language: LexiconLanguage) throws {119 struct Row { var word: String; var key: [UInt8]; var count: Double }120 var rows: [Row] = []121 rows.reserveCapacity(32_000)122 var sorted = true123 data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in124 let bytes = raw.bindMemory(to: UInt8.self)125 var lineStart = 0126 let end = bytes.count127 var i = 0128 while i <= end {129 if i == end || bytes[i] == 0x0A {130 if i > lineStart, rows.count < Lexicon.maxEntries {131 var lineEnd = i132 if bytes[lineEnd - 1] == 0x0D { lineEnd -= 1 }133 if let tab = (lineStart..<lineEnd).first(where: { bytes[$0] == 0x09 }), tab > lineStart, tab + 1 < lineEnd {134 var value = 0.0135 var digits = true136 for j in (tab + 1)..<lineEnd {137 let b = bytes[j]138 guard b >= 0x30, b <= 0x39, value < 1e15 else { digits = false; break }139 value = value * 10 + Double(b - 0x30)140 }141 if digits, let word = String(bytes: UnsafeBufferPointer(rebasing: bytes[lineStart..<tab]), encoding: .utf8),142 !word.isEmpty, !word.contains(where: { $0.isWhitespace || $0.isNewline }) {143 let key = Array(TextFolding.fold(word).utf8)144 if !key.isEmpty, key.count <= Lexicon.maxKeyLength {145 if let last = rows.last, sorted, last.key.lexicographicallyPrecedes(key) == false, last.key != key {146 sorted = false147 }148 rows.append(Row(word: word, key: key, count: value))149 }150 }151 }152 }153 lineStart = i + 1154 }155 i += 1156 }157 }158 guard !rows.isEmpty else { throw LexiconError.malformed(language) }159 if !sorted {160 rows.sort { $0.key == $1.key ? $0.word < $1.word : $0.key.lexicographicallyPrecedes($1.key) }161 }162 let maxLog = log(max(rows.map(\.count).max() ?? 1, 1) + 1)163 var words: [String] = []164 var keyBytes: [UInt8] = []165 var keyStart: [UInt32] = [0]166 var logFrequency: [Float] = []167 var letterMask: [UInt32] = []168 var byLength = [[Int32]](repeating: [], count: Lexicon.maxKeyLength + 1)169 words.reserveCapacity(rows.count)170 keyStart.reserveCapacity(rows.count + 1)171 logFrequency.reserveCapacity(rows.count)172 letterMask.reserveCapacity(rows.count)173 for (index, row) in rows.enumerated() {174 words.append(row.word)175 keyBytes.append(contentsOf: row.key)176 keyStart.append(UInt32(keyBytes.count))177 logFrequency.append(Float(log(row.count + 1) - maxLog))178 letterMask.append(Lexicon.mask(of: row.key))179 byLength[row.key.count].append(Int32(index))180 }181 self.words = words182 self.keyBytes = keyBytes183 self.keyStart = keyStart184 self.logFrequency = logFrequency185 self.letterMask = letterMask186 self.byLength = byLength187 }188189 static func mask(of key: [UInt8]) -> UInt32 {190 var mask: UInt32 = 0191 for byte in key where byte >= 0x61 && byte <= 0x7A {192 mask |= 1 << UInt32(byte - 0x61)193 }194 return mask195 }196197 @inline(__always)198 func keyRange(_ index: Int) -> Range<Int> {199 Int(keyStart[index])..<Int(keyStart[index + 1])200 }201202 /// −1 / 0 / +1: entry key compared with `key`; with `prefixOnly`, a key that starts with `key` compares equal.203 @inline(__always)204 private func compare(_ index: Int, with key: [UInt8], prefixOnly: Bool) -> Int {205 let range = keyRange(index)206 let length = range.count207 let common = min(length, key.count)208 var i = 0209 while i < common {210 let a = keyBytes[range.lowerBound + i], b = key[i]211 if a != b { return a < b ? -1 : 1 }212 i += 1213 }214 if length == key.count { return 0 }215 if length < key.count { return -1 }216 return prefixOnly ? 0 : 1217 }218219 /// Entries whose folded key equals `key` (accent and case variants of the same word).220 func exactRange(_ key: [UInt8]) -> Range<Int> {221 bounds(key, prefixOnly: false)222 }223224 /// Entries whose folded key starts with `key`.225 func prefixRange(_ key: [UInt8]) -> Range<Int> {226 bounds(key, prefixOnly: true)227 }228229 private func bounds(_ key: [UInt8], prefixOnly: Bool) -> Range<Int> {230 guard !key.isEmpty else { return 0..<0 }231 var low = 0, high = count232 while low < high {233 let mid = (low + high) / 2234 if compare(mid, with: key, prefixOnly: prefixOnly) < 0 { low = mid + 1 } else { high = mid }235 }236 let start = low237 high = count238 while low < high {239 let mid = (low + high) / 2240 if compare(mid, with: key, prefixOnly: prefixOnly) <= 0 { low = mid + 1 } else { high = mid }241 }242 return start..<low243 }244}245246/// Hand-written continuation table: previous word (or "<s>" / "*") → likely next words with a weight (2…9).247struct BigramTable: Sendable {248 struct Entry: Sendable {249 let word: String250 let folded: String251 let weight: Float252 }253254 static let sentenceStart = "<s>"255 static let fallback = "*"256 private let table: [String: [Entry]]257258 static let empty = BigramTable(table: [:])259260 private init(table: [String: [Entry]]) {261 self.table = table262 }263264 init(data: Data) {265 var table: [String: [Entry]] = [:]266 let text = String(decoding: data, as: UTF8.self)267 for line in text.split(whereSeparator: \.isNewline).prefix(20_000) {268 let parts = line.split(separator: "\t", omittingEmptySubsequences: false)269 guard parts.count == 3, let weight = Float(parts[2]), weight > 0, !parts[0].isEmpty, !parts[1].isEmpty else { continue }270 let head = String(parts[0])271 let key = head == BigramTable.sentenceStart || head == BigramTable.fallback ? head : TextFolding.fold(head)272 let word = String(parts[1])273 table[key, default: []].append(Entry(word: word, folded: TextFolding.fold(word), weight: min(weight, 9)))274 }275 self.table = table276 }277278 var pairCount: Int { table.values.reduce(0) { $0 + $1.count } }279280 func continuations(after foldedHead: String) -> [Entry] {281 table[foldedHead] ?? []282 }283284 func weight(after foldedHead: String, of foldedWord: String) -> Float {285 guard let entries = table[foldedHead] else { return 0 }286 for entry in entries where entry.folded == foldedWord { return entry.weight }287 return 0288 }289}290