Cotton code
88 lines · 4.3 KB · SwiftRaw
// THE LETTER READER (owner, 3 Nov 2026: "the model is the letter reader"): a// small network trained on real hands (UJIpenchars2 and HWRT,// `scripts/ink/train.py`) reads a group of strokes as one of 62// symbols, a–z, A–Z, then 0–9 (owner, 3 Nov 2026: "I also want to include// having numbers"). On the 62 writers it never saw (2,592 letters, 544// digits) it reads a letter among the letters 94.3% of the time, case-folded,// as the letters-only model it replaced did, where the templates before it// read 41.2%; a digit among the digits 99.3%; among all 36, as a column of// mixed text reads them, 92.7% and 90.4% (0/o, 9/q, 1/l). Letters turned 20°// either way read 91.5%, 35° 80.7%. It was trained turned too,// within ±15° before the input's normalisation (`train.py --rotation 15`,// owner, 3 Nov 2026: "if I write C at an angle it classifies as other// things").//// It ships in the app (`Resources/Ink/`): the Core ML package this reads, and// the same weights as TFLite for Android. It is compiled on first use and// loaded once, off the main thread when the ink ground appears// (`InkReader.prepare`). It reads what the core hands it: the group's 64// samples, encoded by the core to the contract it was trained on// (`cotton_core::ink::input`, the twin of `scripts/ink/ink_input.py`), and// answers its 62 probabilities, a–z, A–Z, 0–9; folding them to the 36 the// deck narrows by, and which of them a surface takes, is the core's.import CoreMLimport Foundationfinal class InkModel: @unchecked Sendable {    private let url: URL    // Loaded once, under the lock; MLModel's predictions are safe from any    // thread and the model never changes once loaded.    private let lock = NSLock()    private var loaded: MLModel?    /// How many probabilities the model answers.    static let classes = 62    /// The model at `url`, a `.mlpackage` (compiled on first use) or a    /// compiled `.mlmodelc`.    init(contentsOf url: URL) {        self.url = url    }    /// The model this build ships.    static let shipped: InkModel = {        guard let url = CottonUIResources.bundle?.url(forResource: "ink-classifier", withExtension: "mlpackage", subdirectory: "Ink")        else { fatalError("Ink/ink-classifier.mlpackage is missing from CottonUI's resources") }        return InkModel(contentsOf: url)    }()    /// The model compiled and loaded, once: the first read waits for it.    @discardableResult    func load() -> MLModel {        lock.lock()        defer { lock.unlock() }        if let loaded { return loaded }        do {            let compiled = url.pathExtension == "mlmodelc" ? url : try MLModel.compileModel(at: url)            let configuration = MLModelConfiguration()            configuration.computeUnits = .cpuOnly            let model = try MLModel(contentsOf: compiled, configuration: configuration)            loaded = model            return model        } catch {            fatalError("\(url.lastPathComponent) does not load: \(error)")        }    }    /// The model's 62 probabilities for a group the core encoded: `points`    /// its samples [x, y, pen_up], `strokes` how many strokes it holds.    func classify(points: [[Double]], strokes: Double) -> [Double] {        do {            let input = try MLMultiArray(shape: [1, NSNumber(value: points.count), 3], dataType: .float32)            let samples = input.dataPointer.assumingMemoryBound(to: Float32.self)            let strides = input.strides.map(\.intValue)            for (i, point) in points.enumerated() {                for j in 0..<min(3, point.count) { samples[i * strides[1] + j * strides[2]] = Float32(point[j]) }            }            let strokeCount = try MLMultiArray(shape: [1, 1], dataType: .float32)            strokeCount[0] = NSNumber(value: Float32(strokes))            let output = try load().prediction(from: MLDictionaryFeatureProvider(dictionary: ["points": input, "stroke_count": strokeCount]))            guard let probabilities = output.featureValue(for: "probabilities")?.multiArrayValue, probabilities.count == Self.classes            else { fatalError("the ink model answered no \(Self.classes) probabilities") }            return (0..<probabilities.count).map { probabilities[$0].doubleValue }        } catch {            fatalError("the ink model did not read: \(error)")        }    }}