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/Cleanup.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 / Cleanup.swift` 163 lines · 10104 bytes Raw Blame History 1 import Foundation 2 3 /// Dictation settings and the user's own words, stored as JSON at ~/Library/Application Support/Hop/dictation.json. 4 struct DictationSettings: Codable { 5 struct Fix: Codable, Hashable, Identifiable { var id: String { heard.lowercased() }; var heard: String; var write: String } 6 struct Snippet: Codable, Hashable, Identifiable { var id: String { say.lowercased() }; var say: String; var insert: String } 7 8 /// Off on a fresh install: turning it on is what lets macOS fetch Apple's speech model (once, from Apple). 9 var enabled = false 10 /// Keeps another dictation app that listens on the same key (Wispr Flow) closed, so one press is one dictation. 11 /// Off unless the user switches it on (Voice screen) or sets it here. 12 var takeOverFromWispr = false 13 /// When true, Hop switches `takeOverFromWispr` on by itself once, after proving the microphone works. Off by default. 14 var autoTakeOverFromWispr = false 15 /// The one-time microphone check has passed. It never runs a second time. 16 var autoSwitched = false 17 var sounds = true 18 var muteAudioWhileDictating = true 19 var cleanup = "light" // "off" = exactly what was heard, "light" = fillers and slips removed 20 var speakReplies = true // read the model's answer aloud when the question was spoken 21 var words: [String] = [] // names and terms to listen for 22 var fixes: [Fix] = [] // heard -> write 23 var snippets: [Snippet] = [] // say -> insert 24 /// Learn spellings from the user's own corrections of a dictation (Sources/Learn.swift). On by default; nothing 25 /// leaves the Mac, and the Voice screen lists every learned fix with an undo. 26 var learnFromFixes = true 27 var learning: [FixLearner.Candidate] = [] // seen once, waiting for a second time 28 var learned: [FixLearner.Learned] = [] // added by Hop, newest first 29 var rejected: [String] = [] // "heard→write" pairs the user undid; never learned again 30 31 init() {} 32 init(from d: Decoder) throws { 33 let c = try d.container(keyedBy: CodingKeys.self) 34 enabled = try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? false 35 takeOverFromWispr = try c.decodeIfPresent(Bool.self, forKey: .takeOverFromWispr) ?? false 36 autoTakeOverFromWispr = try c.decodeIfPresent(Bool.self, forKey: .autoTakeOverFromWispr) ?? false 37 autoSwitched = try c.decodeIfPresent(Bool.self, forKey: .autoSwitched) ?? false 38 sounds = try c.decodeIfPresent(Bool.self, forKey: .sounds) ?? true 39 muteAudioWhileDictating = try c.decodeIfPresent(Bool.self, forKey: .muteAudioWhileDictating) ?? true 40 cleanup = try c.decodeIfPresent(String.self, forKey: .cleanup) ?? "light" 41 speakReplies = try c.decodeIfPresent(Bool.self, forKey: .speakReplies) ?? true 42 words = try c.decodeIfPresent([String].self, forKey: .words) ?? [] 43 fixes = try c.decodeIfPresent([Fix].self, forKey: .fixes) ?? [] 44 snippets = try c.decodeIfPresent([Snippet].self, forKey: .snippets) ?? [] 45 learnFromFixes = try c.decodeIfPresent(Bool.self, forKey: .learnFromFixes) ?? true 46 learning = try c.decodeIfPresent([FixLearner.Candidate].self, forKey: .learning) ?? [] 47 learned = try c.decodeIfPresent([FixLearner.Learned].self, forKey: .learned) ?? [] 48 rejected = try c.decodeIfPresent([String].self, forKey: .rejected) ?? [] 49 } 50 51 static var url: URL { HopConfig.dir.appendingPathComponent("dictation.json") } 52 static func load() -> DictationSettings { 53 guard FileManager.default.fileExists(atPath: url.path) else { return DictationSettings() } 54 guard let d = try? Data(contentsOf: url) else { SettingsFile.keepBroken(url, nil, why: "the file cannot be opened"); return DictationSettings() } 55 do { return try JSONDecoder().decode(DictationSettings.self, from: d) } 56 catch { SettingsFile.keepBroken(url, d, why: SettingsFile.why(error)); return DictationSettings() } // the file stays as it is 57 } 58 func save() { 59 guard !SettingsFile.isBroken(Self.url) else { return } // never over a file Hop could not read 60 let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] 61 if let d = try? enc.encode(self) { 62 try? d.write(to: Self.url, options: .atomic) 63 try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: Self.url.path) 64 } 65 } 66 } 67 68 /// Turns what was heard into what should be typed. Rules only: instant, on this Mac, and it never invents words. 69 /// The rules come from measuring 6,000 real dictations: in 58% nothing but punctuation changes, and the rest is 70 /// almost all fillers, "gonna", repeated words and personal names. 71 enum Cleanup { 72 private static func rx(_ p: String) -> NSRegularExpression { try! NSRegularExpression(pattern: p, options: [.caseInsensitive]) } 73 private static func sub(_ s: String, _ p: String, _ t: String) -> String { 74 rx(p).stringByReplacingMatches(in: s, range: NSRange(s.startIndex..., in: s), withTemplate: t) 75 } 76 /// A phrase as a whole word or words, any case. 77 private static func phrase(_ p: String) -> String { 78 "(? String { 82 var s = raw.replacingOccurrences(of: "\u{00a0}", with: " ").trimmingCharacters(in: .whitespacesAndNewlines) 83 guard !s.isEmpty else { return "" } 84 85 // Personal fixes first, longest first, so "Omega knees" wins over "Omega". 86 for f in set.fixes.sorted(by: { $0.heard.count > $1.heard.count }) where !f.heard.trimmingCharacters(in: .whitespaces).isEmpty { 87 s = sub(s, phrase(f.heard), NSRegularExpression.escapedTemplate(for: f.write)) 88 } 89 90 if set.cleanup != "off" { 91 // "scratch that": drop what was just said (back to the previous sentence end). 92 while let m = rx("[,.!?]?\\s*" + phrase("scratch that") + "[,.!?]?\\s*").firstMatch(in: s, range: NSRange(s.startIndex..., in: s)), 93 let r = Range(m.range, in: s) { 94 let before = s[..= 4 { 107 s = sub(s, "^(?:(?:okay|ok|alright|all right|yeah|yep|well)[, ]+)?(?:so|and)[, ]+(?=\\S)", "") 108 s = sub(s, "^(?:okay|ok|alright|all right)[,.]\\s+(?=\\S)", "") 109 } 110 // Stutters on small words: "the the", "I I", "to to". 111 s = sub(s, "(? $1.say.count }) where !sn.say.trimmingCharacters(in: .whitespaces).isEmpty { 124 s = sub(s, phrase(sn.say) + "[.]?", NSRegularExpression.escapedTemplate(for: sn.insert)) 125 } 126 127 // Tidy up what the removals left behind. 128 s = sub(s, "[ \\t]{2,}", " ") 129 s = sub(s, "[ \\t]+([,.!?;:])", "$1") 130 s = sub(s, ",(\\s*,)+", ",") 131 s = sub(s, "(^|\\n)[,;:]\\s*", "$1") 132 s = sub(s, "[ \\t]+\\n", "\n") 133 s = s.trimmingCharacters(in: .whitespaces) 134 return capitalizeSentences(s) 135 } 136 137 /// First letter of the text and of each sentence, without touching words that start lowercase on purpose (npm, vllm). 138 private static func capitalizeSentences(_ s: String) -> String { 139 var out = "", up = true 140 var word = "" 141 func flush() { 142 guard !word.isEmpty else { return } 143 if up, let f = word.first, f.isLowercase, !keepLower.contains(word.lowercased()) { out += f.uppercased() + word.dropFirst() } else { out += word } 144 up = false; word = "" 145 } 146 for ch in s { 147 if ch.isLetter || ch.isNumber || ch == "'" || ch == "’" { word.append(ch); continue } 148 flush() 149 out.append(ch) 150 if ".!?\n".contains(ch) { up = true } 151 } 152 flush() 153 return out 154 } 155 private static let keepLower: Set = ["npm", "vllm", "systemd", "omc", "git", "ssh", "sudo", "curl", "iphone", "ios", "macos", "ebay"] 156 157 /// True when the dictation ends with the spoken command "press enter"; also returns the text without it. 158 static func stripPressEnter(_ s: String) -> (text: String, enter: Bool) { 159 let r = rx("[,.]?\\s*(?