Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/Learn.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / Learn.swift` 230 lines · 15788 bytes Raw Blame History 1 import AppKit 2 3 /// Dictation learns from the user's own corrections, on this Mac. 4 /// After Hop types a dictation into another app, it reads that same text field again a little later (through the 5 /// accessibility API Hop already uses to paste). Where a word or a short phrase of the dictated text was replaced by 6 /// something that sounds alike, it is a mishearing: Hop counts it, and from the second time (the first time for a 7 /// new name that is not in the system dictionary) it writes the correction itself. Rewording is not learned: the 8 /// change must be at most 3 words, spelled alike, inside the dictated text, and not half of it. Password fields are 9 /// never read. Field contents stay in memory; only the learned pair is saved, in dictation.json. 10 enum FixLearner { 11 /// A pair seen once, waiting for a second sighting. 12 struct Candidate: Codable, Hashable { var heard: String; var write: String; var seen: Int } 13 /// A pair Hop now writes by itself, kept so the Voice screen can undo it. 14 struct Learned: Codable, Hashable, Identifiable { 15 var id: String { heard.lowercased() } 16 var heard: String; var write: String; var date: Date; var addedWord: Bool 17 } 18 19 /// The other limits of a fix (3 words replaced, 4 typed, half alike) are in the Omega code: Omega/hopcore.om. 20 static let maxFieldChars = 200_000 21 22 /// The words of a text without the punctuation around them ("Hello," and "hello" differ only in case). 23 static func words(_ s: String) -> [String] { OmegaText.words(s) } 24 25 /// `corrections` on a background thread, so a long field never holds up Hop's window or the next dictation. 26 static func correctionsInBackground(dictated: String, before: String, after: String) -> Task<[(heard: String, write: String)], Never> { 27 Task.detached(priority: .utility) { corrections(dictated: dictated, before: before, after: after) } 28 } 29 30 /// How alike two spellings are, 0 to 1, on letters and digits only, ignoring case. The edits are counted by 31 /// Omega code (`Omega/hopcore.om`, fn alike). 32 static func likeness(_ a: String, _ b: String) -> Double { OmegaText.likeness(a, b) } 33 34 /// The mishearings the user fixed: `before` is the field right after Hop typed `dictated`, `after` the same field 35 /// later. Returns nothing when the dictation cannot be found, or when more than half of it changed (a rewrite). 36 /// Found by Omega code (`Omega/hopcore.om`, fn wdiff and fn pick): at most 3 words replaced, by a run of at 37 /// most 4 typed words that is at least half alike. 38 static func corrections(dictated: String, before: String, after: String) -> [(heard: String, write: String)] { 39 OmegaText.corrections(dictated: dictated, before: before, after: after) 40 } 41 42 /// A name the system dictionary does not know, written with a capital ("Gandi", "GrokBot"). The spell checker skips 43 /// words in capitals only ("ORCID"), so those count as ordinary words and are learned the second time. 44 @MainActor static func isNewName(_ s: String) -> Bool { 45 guard s.contains(where: \.isUppercase) else { return false } 46 return misspelled(s) 47 } 48 /// English, like the speech recogniser (en-US), whatever spelling language the Mac is set to. 49 @MainActor private static func misspelled(_ s: String) -> Bool { 50 var count = 0 51 return NSSpellChecker.shared.checkSpelling(of: s, startingAt: 0, language: "en", wrap: false, 52 inSpellDocumentWithTag: 0, wordCount: &count).location != NSNotFound 53 } 54 /// Endings that make another form of the same word. Any other ending is a different word the recogniser 55 /// split or misheard ("Forge Joe" -> "Forgejo", "Vrexal" -> "Vrexalbot") and may be learned. 56 static let inflections: Set = ["s", "es", "ed", "d", "ing", "er", "ers", "ly"] 57 /// Another form of the same word, not another spelling: a possessive, contraction, plural or compound ("Zenodo" 58 /// -> "Zenodo's", "Zenodo is" -> "Zenodo's", "GrokBot" -> "GrokBots", "GrokBots" -> "GrokBot's", "Zenodo" -> 59 /// "Zenodo-based", "non-Zenodo" or "Zenodo.org", and back). These depend on the sentence, so they are never fixes. 60 /// A change of spaces or capitals only ("Hop bot" -> "Hopbot", "grokbot" -> "GrokBot") is a fix, and so is an 61 /// apostrophe that makes an ordinary word ("dont" -> "don't"), judged by `isKnownWords`. 62 static func isOtherForm(heard: String, write: String, isKnownWords: (String) -> Bool = { _ in false }) -> Bool { 63 func letters(_ s: String) -> String { s.lowercased().filter { $0.isLetter || $0.isNumber } } 64 let h = letters(heard), w = letters(write) 65 guard !h.isEmpty, !w.isEmpty else { return false } 66 // Possessive and contraction endings ("Zenodo's", "bots'", "it'll", "don't"); an apostrophe inside a name 67 // ("O'Connor") is part of its spelling and does not count. 68 let apostrophes: (String) -> Int = { s in 69 s.lowercased().replacingOccurrences(of: "\u{2019}", with: "'").split(separator: " ").filter { word in 70 ["'s", "s'", "'ll", "'d", "'re", "'ve", "'m", "'t"].contains { word.hasSuffix($0) } 71 }.count 72 } 73 // "dont" -> "don't": the apostrophe makes an ordinary lower-case word out of one that is not. 74 let makesOrdinaryWord = !write.contains(where: \.isUppercase) && isKnownWords(write) && !isKnownWords(heard) 75 if h != w { 76 let (short, long) = h.count < w.count ? (h, w) : (w, h) 77 if long.hasPrefix(short), inflections.contains(String(long.dropFirst(short.count))) { return true } 78 } else if apostrophes(heard) != apostrophes(write), !makesOrdinaryWord { return true } 79 // A respelling with a possessive or contraction added or removed in the same edit ("Zendoto" -> "Zenodo's", 80 // "Hop bot is" -> "Hopbot's", "Zendoto's" -> "Zenodo"): the ending depends on the sentence, so the pair as a 81 // whole is not a fix. 82 if apostrophes(write) != apostrophes(heard), !makesOrdinaryWord { return true } 83 func split(_ s: String) -> [String] { s.lowercased().split(separator: " ").map(String.init) } 84 let hw = split(heard), ww = split(write) 85 // "Zenodo is" -> "Zenodo's", "Zenodo's" -> "Zenodo", "it is" -> "it's": the part before an apostrophe is a 86 // word on the other side. 87 func stems(_ ws: [String]) -> [String] { 88 ws.compactMap { w in 89 guard let q = w.firstIndex(where: { $0 == "'" || $0 == "\u{2019}" }), q != w.startIndex else { return nil } 90 return String(w[.. = ["-", ".", "/"] 96 func parts(_ ws: [String]) -> [String] { 97 ws.filter { $0.contains(where: joiners.contains) }.flatMap { $0.split(whereSeparator: joiners.contains).map(String.init) } 98 } 99 return parts(ww).contains(where: hw.contains) || parts(hw).contains(where: ww.contains) 100 } 101 102 /// Ordinary words heard next to a misheard one, which the edit changed or dropped ("Zendoto is" -> "Zenodo", 103 /// "ocid then" -> "ORCID Then", "ocid then" -> "ORCID than"). Only the misheard part is a mishearing; the rest is 104 /// wording or grammar that depends on the sentence. Every dictionary word of a heard phrase must survive as the 105 /// same written word, in its own case, or merged into a written name ("Hop bot" -> "Hopbot", "grock bot" -> 106 /// "GrokBot", "Forge Joe" -> "Forgejo" keep theirs). And every ordinary word written must have been heard: a 107 /// written dictionary word that was not ("than", "their", "too", "TOO", "thereof") is a different word, however 108 /// alike it is spelled and wherever its letters also appear in the name ("Zentoto to" -> "Zenoto too"). That holds 109 /// for one heard word too when it was written as a name plus an ordinary word ("Zentoto" -> "Zenoto too"); a split 110 /// into ordinary words alone ("alot" -> "a lot") is still a respelling. 111 static func changesOrdinaryWords(heard: String, write: String, isKnownWords: (String) -> Bool) -> Bool { 112 let hw = words(heard) 113 let ww = words(write) 114 // An ordinary word is a dictionary word written in lower case, with only its first letter capital, or all in 115 // capitals ("TOO"); a name with capitals inside ("GrokBot", "O'Connor") is not one. 116 func ordinary(_ w: String) -> Bool { (w.dropFirst() == w.dropFirst().lowercased() || w == w.uppercased()) && isKnownWords(w.lowercased()) } 117 let heardLower = Set(hw.map { $0.lowercased() }) 118 let unheard = ww.contains { ordinary($0) && !heardLower.contains($0.lowercased()) } 119 if unheard && (hw.count > 1 || ww.contains { !isKnownWords($0.lowercased()) }) { return true } 120 guard hw.count > 1 else { return false } 121 // Written names a heard word may have merged into: not a dictionary word even in lower case (a name the 122 // spell checker has learned with its capitals, such as "GrokBot", still counts as a name). 123 let names = ww.filter { !isKnownWords($0.lowercased()) }.map { Array($0.lowercased().filter { $0.isLetter || $0.isNumber }) } 124 for word in hw where isKnownWords(word) { 125 let lw = word.lowercased() 126 if ww.contains(where: { $0.lowercased() == lw && $0 != word }) { return true } // "then" -> "Then" 127 if ww.contains(word) { continue } // kept as it was 128 // Kept inside a written name, perhaps slightly respelled ("joe" in "forgejo", "bot" in "hopbot"): some 129 // stretch of the name's letters about the word's length reads like it. 130 let n = lw.count 131 var kept = false 132 for name in names where !kept { 133 for len in max(1, n - 1)...(n + 1) where len <= name.count && !kept { 134 for start in 0...(name.count - len) where likeness(lw, String(name[start..<(start + len)])) >= 0.6 { kept = true; break } 135 } 136 } 137 if !kept { return true } 138 } 139 return false 140 } 141 142 /// A new name is learned at the first sighting only when what was written is the bare name: with a plural or 143 /// other inflection ending, or joined to something ("Zenodos", "Zenodo.io"), it may depend on the sentence, so 144 /// it waits for the same fix a second time, as an ordinary word does. 145 static func isBareName(heard: String, write: String) -> Bool { 146 if write.contains(where: { "-./_".contains($0) }), !heard.contains(where: { "-./_".contains($0) }) { return false } 147 let w = write.lowercased(), h = heard.lowercased() 148 for end in inflections where w.hasSuffix(end) && !h.hasSuffix(end) && w.count > end.count + 2 { return false } 149 return true 150 } 151 152 // MARK: Reading the field Hop typed into 153 154 /// The focused text element of the app in front, unless it is a password field or has no readable text value. 155 static func focusedField() -> AXUIElement? { 156 guard AXIsProcessTrusted() else { return nil } 157 let system = AXUIElementCreateSystemWide() 158 var focused: CFTypeRef? 159 guard AXUIElementCopyAttributeValue(system, kAXFocusedUIElementAttribute as CFString, &focused) == .success, 160 let f = focused, CFGetTypeID(f) == AXUIElementGetTypeID() else { return nil } 161 let el = f as! AXUIElement 162 AXUIElementSetMessagingTimeout(el, 0.25) // kept with the element for the later reads too 163 if isSecure(el) { return nil } 164 return value(el) == nil ? nil : el 165 } 166 static func isSecure(_ el: AXUIElement) -> Bool { 167 func attr(_ name: String) -> String? { 168 var v: CFTypeRef? 169 return AXUIElementCopyAttributeValue(el, name as CFString, &v) == .success ? v as? String : nil 170 } 171 return attr(kAXSubroleAttribute) == kAXSecureTextFieldSubrole || attr(kAXRoleAttribute) == kAXSecureTextFieldSubrole 172 } 173 /// The element's text, if it has one of a size worth reading. A password field is never read, whenever it is asked. 174 static func value(_ el: AXUIElement) -> String? { 175 if isSecure(el) { return nil } 176 var v: CFTypeRef? 177 guard AXUIElementCopyAttributeValue(el, kAXValueAttribute as CFString, &v) == .success, let s = v as? String, 178 s.utf16.count <= maxFieldChars else { return nil } 179 return s 180 } 181 /// True when the system dictionary knows every word ("there", "then", "a", "Paris"). Such a word written another 182 /// way is grammar or wording that depends on the sentence, never a mishearing to fix everywhere. 183 @MainActor static func isKnownWords(_ s: String) -> Bool { !misspelled(s) } 184 } 185 186 extension DictationSettings { 187 /// Counts each pair and turns it into a fix from the second sighting, or at once for a new name. 188 /// A pair the user undid once is never learned again; a fix the user already has is left alone. 189 /// Returns what was learned this time. 190 @discardableResult 191 mutating func learn(_ pairs: [(heard: String, write: String)], now: Date = Date(), isNewName: (String) -> Bool, 192 isKnownWords: (String) -> Bool) -> [FixLearner.Learned] { 193 var learnedNow: [FixLearner.Learned] = [] 194 for (heard, write) in pairs { 195 let key = heard.lowercased() + "→" + write 196 guard !rejected.contains(key), !fixes.contains(where: { $0.id == heard.lowercased() }), 197 !FixLearner.isOtherForm(heard: heard, write: write, isKnownWords: isKnownWords), // "Zenodo" -> "Zenodo's" 198 !FixLearner.changesOrdinaryWords(heard: heard, write: write, isKnownWords: isKnownWords) else { continue } 199 var seen = 1 200 if let k = learning.firstIndex(where: { $0.heard.lowercased() == heard.lowercased() && $0.write == write }) { 201 seen = learning[k].seen + 1; learning.remove(at: k) 202 } 203 let name = isNewName(write) && FixLearner.isBareName(heard: heard, write: write) 204 // A fix is applied to every later dictation, so it must never rewrite a correctly spelled ordinary word 205 // ("a" -> "an", "then" -> "than", "there" -> "their", "its" -> "it's", "then" -> "Then"): learn only when 206 // what was heard is not a dictionary word, or what was written is a new name. 207 guard name || !isKnownWords(heard) else { continue } 208 guard seen >= 2 || name else { 209 learning.insert(.init(heard: heard, write: write, seen: seen), at: 0) 210 if learning.count > 200 { learning.removeLast(learning.count - 200) } 211 continue 212 } 213 fixes.append(.init(heard: heard, write: write)) 214 let addWord = name && !words.contains(write) 215 if addWord { words.append(write) } 216 let l = FixLearner.Learned(heard: heard, write: write, date: now, addedWord: addWord) 217 learned.insert(l, at: 0); learnedNow.append(l) 218 } 219 return learnedNow 220 } 221 222 /// Takes a learned fix back out, with the word it added, and remembers not to learn it again. 223 mutating func undoLearned(_ l: FixLearner.Learned) { 224 fixes.removeAll { $0.id == l.id && $0.write == l.write } 225 if l.addedWord { words.removeAll { $0 == l.write } } 226 learned.removeAll { $0 == l } 227 let key = l.heard.lowercased() + "→" + l.write 228 if !rejected.contains(key) { rejected.append(key) } 229 } 230 }