hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 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 | "(?<![\\p{L}\\p{N}])" + NSRegularExpression.escapedPattern(for: p.trimmingCharacters(in: .whitespaces)) + "(?![\\p{L}\\p{N}])" |
| 79 | } |
| 80 | |
| 81 | static func apply(_ raw: String, _ set: DictationSettings) -> 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[..<r.lowerBound] |
| 95 | let cut = before.lastIndex(where: { ".!?\n".contains($0) }).map { before.index(after: $0) } ?? before.startIndex |
| 96 | let head = String(s[..<cut]).trimmingCharacters(in: .whitespaces) |
| 97 | let tail = String(s[r.upperBound...]) |
| 98 | s = head.isEmpty ? tail : head + " " + tail |
| 99 | } |
| 100 | // Hesitation sounds, wherever they are. |
| 101 | s = sub(s, "(?<![\\p{L}\\p{N}])(um+|uh+|uhm+|erm+|hmm+)(?![\\p{L}\\p{N}])[,.]?\\s*", "") |
| 102 | // Fillers set off by commas. |
| 103 | s = sub(s, ",\\s*(you know|i mean|like|sort of|kind of)\\s*,", ",") |
| 104 | s = sub(s, "(^|(?<=[.!?]\\s))(you know|i mean),\\s*", "$1") |
| 105 | // Throat-clearing at the very start: "Okay so", "So", "And", "Yeah so", "All right so". |
| 106 | if s.split(whereSeparator: \.isWhitespace).count >= 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, "(?<![\\p{L}\\p{N}'])(the|a|an|to|of|and|in|on|i|is|it|we|you|for|with|my|so|but)[, ]+\\1(?![\\p{L}\\p{N}'])", "$1") |
| 112 | // Spoken shortcuts written out. |
| 113 | for (a, b) in [("gonna", "going to"), ("gotta", "got to"), ("wanna", "want to")] { |
| 114 | s = sub(s, "(?<![\\p{L}\\p{N}])" + a + "(?![\\p{L}\\p{N}])", b) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // Spoken layout commands work at every cleanup level. |
| 119 | s = sub(s, "[,.]?\\s*" + phrase("new paragraph") + "[,.]?\\s*", "\n\n") |
| 120 | s = sub(s, "[,.]?\\s*" + phrase("new line") + "[,.]?\\s*", "\n") |
| 121 | |
| 122 | // Snippets: say the cue, get the saved text. |
| 123 | for sn in set.snippets.sorted(by: { $0.say.count > $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<String> = ["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*(?<![\\p{L}\\p{N}])press enter[.!]?\\s*$") |
| 160 | guard let m = r.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)), let range = Range(m.range, in: s) else { return (s, false) } |
| 161 | return (String(s[..<range.lowerBound]), true) |
| 162 | } |
| 163 | } |