SPB Git

Repository Public

GlideDecoder.swift 16.4 KB 356 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP Keyboard7// File             : Shared/Sources/PredictionCore/GlideDecoder.swift8// Module           : Utilities9// Repository       : Private repository (SPB Git)10// Project Website  : Not specified11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// Where the letter keys are, as the surface laid them out. Built by the keyboard surface from the live layout,44/// so the decoder follows the real geometry (one-handed mode, landscape, AZERTY, dedicated é / ñ keys).45public struct GlideLayout: Sendable, Hashable {46    /// Centre of each letter key, keyed by its lowercase character ("a", "é", "ñ", "'"), in points.47    public var centers: [Character: SIMD2<Double>]48    /// Width of one letter key, in points: the unit every distance is measured in.49    public var keyWidth: Double5051    public init(centers: [Character: SIMD2<Double>], keyWidth: Double) {52        self.centers = centers53        self.keyWidth = keyWidth54    }55}5657public struct GlideCandidate: Sendable, Hashable {58    /// Lexicon form, accents included ("été", "mañana", "aujourd'hui", "Paris").59    public let word: String60    /// Higher is better; only comparable within one decode.61    public let score: Double6263    public init(word: String, score: Double) {64        self.word = word65        self.score = score66    }67}6869/// A word the user added or the keyboard learned, with its frequency-equivalent weight.70struct GlideUserWord: Sendable {71    let display: String72    let logFrequency: Float73}7475/// Shape-writing index of one lexicon on one key geometry (SHARK2 family). Every word is stored as the sequence of76/// keys its trace goes through (doubled letters merged, apostrophes and hyphens skipped), bucketed by first and last77/// key. Templates are resampled on the fly for the few hundred words that survive pruning, so the index stays small:78/// about a dozen bytes per word plus its key sequence.79struct GlideIndex: Sendable {80    static let sampleCount = 4081    /// A trace shorter than this many key widths is a tap, not a glide.82    static let minimumPathLength: Float = 0.683    /// Keys within this many key widths of the first / last point are possible first / last letters.84    static let endpointRadius: Float = 1.285    /// How many natural-log units of frequency one squared key width of mean deviation is worth.86    static let shapeWeight: Float = 2687    static let endpointWeight: Float = 3.588    static let lengthWeight: Float = 0.989    static let shortlist = 329091    private let keyCount: Int92    /// Key centres in key-width units.93    private let centers: [SIMD2<Float>]94    private let scale: Double95    private var sequenceBytes: [UInt8] = []96    private var sequenceStart: [UInt32] = [0]97    /// ≥ 0: lexicon entry; < 0: user word `-1 - value`.98    private var source: [Int32] = []99    private var idealLength: [Float] = []100    private var buckets: [[Int32]]101    private let userWords: [GlideUserWord]102103    var templateCount: Int { source.count }104105    init(lexicon: Lexicon, userWords: [GlideUserWord], layout: GlideLayout) {106        let ordered = layout.centers.keys.sorted { String($0) < String($1) }.prefix(250)107        let width = layout.keyWidth.isFinite && layout.keyWidth > 0 ? layout.keyWidth : 1108        scale = 1 / width109        var ascii = [UInt8](repeating: 255, count: 26)110        var dedicated: [Character: UInt8] = [:]111        var centers: [SIMD2<Float>] = []112        for (offset, character) in ordered.enumerated() {113            let point = layout.centers[character] ?? .zero114            centers.append(SIMD2(Float(point.x * scale), Float(point.y * scale)))115            let scalars = String(character).unicodeScalars116            if scalars.count == 1, let scalar = scalars.first, scalar.value >= 0x61, scalar.value <= 0x7A {117                ascii[Int(scalar.value) - 0x61] = UInt8(offset)118            } else if character.isLetter {119                dedicated[character] = UInt8(offset)120            }121        }122        self.centers = centers123        self.userWords = userWords124        keyCount = centers.count125        buckets = [[Int32]](repeating: [], count: keyCount * keyCount)126        guard keyCount >= 2 else { return }127        sequenceBytes.reserveCapacity(lexicon.count * 7)128        source.reserveCapacity(lexicon.count + userWords.count)129130        var base: [UInt8] = []131        var variant: [UInt8] = []132        func baseSequence(_ key: some Sequence<UInt8>, into out: inout [UInt8]) -> Bool {133            for byte in key {134                if byte >= 0x61, byte <= 0x7A {135                    let id = ascii[Int(byte) - 0x61]136                    if id == 255 { return false }137                    if out.last != id { out.append(id) }138                } else if byte != 0x27, byte != 0x2D {139                    return false140                }141            }142            return true143        }144        func dedicatedSequence(_ word: String, into out: inout [UInt8]) -> Bool {145            for character in word.lowercased() {146                if let id = dedicated[character] {147                    if out.last != id { out.append(id) }148                } else if !baseSequence(TextFolding.fold(String(character)).utf8, into: &out) {149                    return false150                }151            }152            return true153        }154        func add(_ sequence: [UInt8], _ id: Int32) {155            guard sequence.count >= 2, sequence.count <= Lexicon.maxKeyLength else { return }156            var length: Float = 0157            for index in 1..<sequence.count {158                length += Self.distance(centers[Int(sequence[index - 1])], centers[Int(sequence[index])])159            }160            buckets[Int(sequence[0]) * keyCount + Int(sequence[sequence.count - 1])].append(Int32(source.count))161            sequenceBytes.append(contentsOf: sequence)162            sequenceStart.append(UInt32(sequenceBytes.count))163            source.append(id)164            idealLength.append(length)165        }166        func addWord(_ word: String, folded: some Sequence<UInt8>, isASCII: Bool, id: Int32) {167            base.removeAll(keepingCapacity: true)168            let valid = baseSequence(folded, into: &base)169            if valid { add(base, id) }170            guard !dedicated.isEmpty, !isASCII else { return }171            variant.removeAll(keepingCapacity: true)172            if dedicatedSequence(word, into: &variant), !valid || variant != base { add(variant, id) }173        }174175        for index in 0..<lexicon.count {176            let range = lexicon.keyRange(index)177            var isASCII = true178            if !dedicated.isEmpty {179                // Folding only shortens or keeps the UTF-8 length when a diacritic is present.180                isASCII = !lexicon.words[index].utf8.contains { $0 >= 0x80 }181            }182            addWord(lexicon.words[index], folded: lexicon.keyBytes[range], isASCII: isASCII, id: Int32(index))183        }184        for (offset, word) in userWords.enumerated() {185            addWord(word.display, folded: TextFolding.fold(word.display).utf8,186                    isASCII: !word.display.utf8.contains { $0 >= 0x80 }, id: Int32(-1 - offset))187        }188    }189190    @inline(__always)191    private static func distance(_ a: SIMD2<Float>, _ b: SIMD2<Float>) -> Float {192        let d = a - b193        return (d.x * d.x + d.y * d.y).squareRoot()194    }195196    /// `count` points evenly spaced along the polyline `points` of total length `total`.197    private static func resample(_ points: UnsafeBufferPointer<SIMD2<Float>>, total: Float,198                                 into out: UnsafeMutableBufferPointer<SIMD2<Float>>) {199        let count = out.count200        guard let first = points.first else { return }201        guard total > 1e-6, points.count > 1 else {202            for index in 0..<count { out[index] = first }203            return204        }205        let step = total / Float(count - 1)206        out[0] = first207        var written = 1208        var segment = 1209        var segmentStart = first210        var travelled: Float = 0211        var target = step212        while written < count - 1, segment < points.count {213            let end = points[segment]214            let length = distance(segmentStart, end)215            if travelled + length >= target, length > 0 {216                let t = (target - travelled) / length217                let point = segmentStart + (end - segmentStart) * t218                out[written] = point219                written += 1220                travelled = target221                segmentStart = point222                target += step223            } else {224                travelled += length225                segmentStart = end226                segment += 1227            }228        }229        let last = points[points.count - 1]230        while written < count {231            out[written] = last232            written += 1233        }234    }235236    /// `bonus` is the context bonus of a folded word (bigram table); it is only asked for the shortlist.237    func decode(path: [SIMD2<Double>], lexicon: Lexicon, limit: Int, bonus: (String) -> Float) -> [GlideCandidate] {238        guard limit > 0, keyCount >= 2, path.count >= 2, !source.isEmpty else { return [] }239        // Finite points only, in key-width units, consecutive duplicates dropped.240        var raw: [SIMD2<Float>] = []241        raw.reserveCapacity(min(path.count, 2048))242        let stride = max(1, path.count / 2048)243        for index in Swift.stride(from: 0, to: path.count, by: stride) {244            let point = path[index]245            guard point.x.isFinite, point.y.isFinite else { continue }246            let scaled = SIMD2(Float(point.x * scale), Float(point.y * scale))247            if let last = raw.last, Self.distance(last, scaled) < 0.02 { continue }248            raw.append(scaled)249        }250        if let end = path.last, end.x.isFinite, end.y.isFinite, stride > 1 {251            raw.append(SIMD2(Float(end.x * scale), Float(end.y * scale)))252        }253        guard raw.count >= 2 else { return [] }254        // Light smoothing: touch samples jitter, the intended trace does not.255        var points = raw256        if raw.count >= 5 {257            for index in 1..<(raw.count - 1) {258                points[index] = (raw[index - 1] + raw[index] * 2 + raw[index + 1]) * 0.25259            }260        }261        var total: Float = 0262        for index in 1..<points.count { total += Self.distance(points[index - 1], points[index]) }263        guard total >= Self.minimumPathLength else { return [] }264265        let count = Self.sampleCount266        var sampled = [SIMD2<Float>](repeating: .zero, count: count)267        points.withUnsafeBufferPointer { source in268            sampled.withUnsafeMutableBufferPointer { Self.resample(source, total: total, into: $0) }269        }270        let first = points[0], last = points[points.count - 1]271        var starts: [(key: Int, distance: Float)] = []272        var ends: [(key: Int, distance: Float)] = []273        for key in 0..<keyCount {274            let ds = Self.distance(centers[key], first), de = Self.distance(centers[key], last)275            if ds <= Self.endpointRadius { starts.append((key, ds)) }276            if de <= Self.endpointRadius { ends.append((key, de)) }277        }278        guard !starts.isEmpty, !ends.isEmpty else { return [] }279280        struct Scored { var template: Int32; var score: Float }281        var best: [Scored] = []282        best.reserveCapacity(Self.shortlist + 1)283        var worst = -Float.infinity284        var ideal = [SIMD2<Float>](repeating: .zero, count: count)285        var polyline = [SIMD2<Float>](repeating: .zero, count: Lexicon.maxKeyLength)286        var visited = 0287        let lengthSlack = 1.0 + 0.3 * total288        let invCount = 1 / Float(count)289290        for start in starts {291            for end in ends {292                let endpointCost = Self.endpointWeight * (start.distance * start.distance + end.distance * end.distance)293                for template in buckets[start.key * keyCount + end.key] {294                    visited += 1295                    if visited & 1023 == 0, Task.isCancelled { return [] }296                    let index = Int(template)297                    let length = idealLength[index]298                    let gap = abs(length - total)299                    if gap > max(lengthSlack, 0.3 * length + 1) { continue }300                    let id = source[index]301                    let frequency = id >= 0 ? lexicon.logFrequency[Int(id)] : userWords[Int(-1 - id)].logFrequency302                    let fixed = frequency - endpointCost - Self.lengthWeight * gap * gap / max(total, 1)303                    // Even a perfect shape could not enter the shortlist.304                    if best.count == Self.shortlist, fixed <= worst { continue }305                    let lower = Int(sequenceStart[index]), upper = Int(sequenceStart[index + 1])306                    for offset in lower..<upper { polyline[offset - lower] = centers[Int(sequenceBytes[offset])] }307                    polyline.withUnsafeBufferPointer { source in308                        ideal.withUnsafeMutableBufferPointer {309                            Self.resample(UnsafeBufferPointer(rebasing: source[0..<(upper - lower)]), total: length, into: $0)310                        }311                    }312                    var sum: Float = 0313                    let budget = best.count == Self.shortlist ? (fixed - worst) / Self.shapeWeight * Float(count) : Float.infinity314                    var sample = 0315                    while sample < count {316                        let d = ideal[sample] - sampled[sample]317                        sum += d.x * d.x + d.y * d.y318                        if sum > budget { break }319                        sample += 1320                    }321                    if sample < count { continue }322                    let score = fixed - Self.shapeWeight * sum * invCount323                    var position = best.count324                    while position > 0, best[position - 1].score < score { position -= 1 }325                    best.insert(Scored(template: template, score: score), at: position)326                    if best.count > Self.shortlist { best.removeLast() }327                    if best.count == Self.shortlist { worst = best[best.count - 1].score }328                }329            }330        }331332        // Context, deduplication (a word can be reached through its base and its dedicated-key trace), display forms.333        var seen: [String: Int] = [:]334        var ranked: [(word: String, score: Float, profane: Bool)] = []335        for entry in best {336            let id = source[Int(entry.template)]337            let word = id >= 0 ? lexicon.words[Int(id)] : userWords[Int(-1 - id)].display338            let folded = TextFolding.fold(word)339            let score = entry.score + bonus(folded)340            if let existing = seen[word] {341                if score > ranked[existing].score { ranked[existing].score = score }342                continue343            }344            seen[word] = ranked.count345            ranked.append((word, score, Profanity.folded.contains(folded)))346        }347        // A glide is committed without confirmation: a profanity is offered as an alternative, never picked first348        // while another reading exists.349        ranked.sort {350            if $0.profane != $1.profane { return !$0.profane }351            return $0.score == $1.score ? $0.word < $1.word : $0.score > $1.score352        }353        return ranked.prefix(limit).map { GlideCandidate(word: $0.word, score: Double($0.score)) }354    }355}356
Files main
Menu

Theme