Voxley / app · voxley.si / Sources / Voxley / Library.swift
| 1 | import Foundation |
| 2 | |
| 3 | struct Transcript: Codable, Identifiable, Sendable { |
| 4 | var id = UUID() |
| 5 | var date = Date() |
| 6 | var original: String |
| 7 | var text: String |
| 8 | var source: String |
| 9 | var mode: WritingMode |
| 10 | } |
| 11 | |
| 12 | enum WritingMode: String, Codable, CaseIterable, Identifiable, Sendable { |
| 13 | case verbatim = "Verbatim" |
| 14 | case clean = "Clean up" |
| 15 | case notes = "Notes" |
| 16 | case email = "Email" |
| 17 | |
| 18 | var id: Self { self } |
| 19 | |
| 20 | var instruction: String { |
| 21 | switch self { |
| 22 | case .verbatim: "" |
| 23 | case .clean: "Remove obvious filler, fix punctuation and casing, and preserve the original meaning and voice." |
| 24 | case .notes: "Turn the dictation into concise notes. Use bullets where helpful. Preserve all facts, names, and action items." |
| 25 | case .email: "Format the dictation as a clear email body. Keep the tone and facts; do not invent a subject, greeting, or signature." |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | struct WordReplacement: Codable, Identifiable, Sendable { |
| 31 | var id = UUID() |
| 32 | var spoken = "" |
| 33 | var written = "" |
| 34 | } |
| 35 | |
| 36 | struct Preferences: Codable, Sendable { |
| 37 | static let vocabularyLimit = 100 |
| 38 | |
| 39 | var locale = "en-US" |
| 40 | var mode = WritingMode.verbatim |
| 41 | var shortcutKey = Shortcut.controlShiftSpace |
| 42 | var retainHistory = true |
| 43 | var vocabulary = "" |
| 44 | var replacements: [WordReplacement] = [] |
| 45 | var appModes: [String: WritingMode] = [:] |
| 46 | // Optional so libraries and backups saved before Refine keep decoding. |
| 47 | var refineShortcut: Shortcut? |
| 48 | var refineDisabled: Bool? |
| 49 | |
| 50 | /// The second shortcut that opens the Refine window instead of pasting. |
| 51 | var refineShortcutKey: Shortcut { |
| 52 | get { refineShortcut ?? .refineDefault } |
| 53 | set { refineShortcut = newValue } |
| 54 | } |
| 55 | |
| 56 | var refineEnabled: Bool { |
| 57 | get { refineDisabled != true } |
| 58 | set { refineDisabled = newValue ? nil : true } |
| 59 | } |
| 60 | |
| 61 | var vocabularyEntries: [String] { |
| 62 | var seen = Set<String>() |
| 63 | return vocabulary.split(whereSeparator: \.isNewline) |
| 64 | .map { $0.trimmingCharacters(in: .whitespaces) } |
| 65 | .filter { !$0.isEmpty && seen.insert(WordList.key(for: $0)).inserted } |
| 66 | } |
| 67 | |
| 68 | var contextWords: [String] { Array(vocabularyEntries.prefix(Self.vocabularyLimit)) } |
| 69 | |
| 70 | mutating func importVocabulary(_ text: String) throws -> Int { |
| 71 | let existing = vocabularyEntries |
| 72 | var seen = Set(existing.map(WordList.key)) |
| 73 | let entries = try WordList.parse(text) |
| 74 | guard !entries.isEmpty else { throw WordList.ImportError.empty } |
| 75 | let additions = entries.filter { seen.insert(WordList.key(for: $0)).inserted } |
| 76 | guard !additions.isEmpty else { return 0 } |
| 77 | let available = max(0, Self.vocabularyLimit - existing.count) |
| 78 | guard additions.count <= available else { |
| 79 | throw WordList.ImportError.overLimit(newEntries: additions.count, available: available) |
| 80 | } |
| 81 | if !vocabulary.isEmpty, vocabulary.last?.isNewline != true { vocabulary += "\n" } |
| 82 | vocabulary += additions.joined(separator: "\n") |
| 83 | return additions.count |
| 84 | } |
| 85 | |
| 86 | func applyingReplacements(to input: String) -> String { |
| 87 | replacements.reduce(input) { result, rule in |
| 88 | let word = rule.spoken.trimmingCharacters(in: .whitespacesAndNewlines) |
| 89 | guard !word.isEmpty else { return result } |
| 90 | let pattern = "(?<![\\p{L}\\p{N}_])" + NSRegularExpression.escapedPattern(for: word) |
| 91 | + "(?![\\p{L}\\p{N}_])" |
| 92 | guard let expression = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { |
| 93 | return result |
| 94 | } |
| 95 | return expression.stringByReplacingMatches( |
| 96 | in: result, |
| 97 | range: NSRange(result.startIndex..., in: result), |
| 98 | withTemplate: NSRegularExpression.escapedTemplate(for: rule.written) |
| 99 | ) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | struct Library: Codable, Sendable { |
| 105 | static let currentVersion = 1 |
| 106 | var version = currentVersion |
| 107 | var preferences = Preferences() |
| 108 | var history: [Transcript] = [] |
| 109 | |
| 110 | static func read(_ url: URL) throws -> Library { |
| 111 | let data = try Data(contentsOf: url) |
| 112 | let library = try JSONDecoder().decode(Library.self, from: data) |
| 113 | guard library.version == currentVersion else { throw VoxleyError.backupVersion } |
| 114 | return library |
| 115 | } |
| 116 | |
| 117 | func write(_ url: URL) throws { |
| 118 | let encoder = JSONEncoder() |
| 119 | encoder.outputFormatting = [.prettyPrinted, .sortedKeys] |
| 120 | try encoder.encode(self).write(to: url, options: .atomic) |
| 121 | } |
| 122 | |
| 123 | mutating func restore(_ backup: Library) { |
| 124 | preferences = backup.preferences |
| 125 | var seen = Set(history.map(\.id)) |
| 126 | history.append(contentsOf: backup.history.filter { seen.insert($0.id).inserted }) |
| 127 | history.sort { $0.date > $1.date } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | enum VoxleyError: LocalizedError { |
| 132 | case backupVersion, microphone, microphoneInput, speechUnavailable, unsupportedLocale, emptyAudio, noSpeech |
| 133 | case audioOverrun |
| 134 | |
| 135 | var errorDescription: String? { |
| 136 | switch self { |
| 137 | case .backupVersion: "This backup was created by a different version of Voxley." |
| 138 | case .microphone: "Allow Voxley in System Settings → Privacy & Security → Microphone to dictate." |
| 139 | case .microphoneInput: "Voxley could not start the microphone. Check your input device in Sound settings." |
| 140 | case .speechUnavailable: "Apple Speech transcription is unavailable on this Mac." |
| 141 | case .unsupportedLocale: "Apple Speech does not support that dictation language on this Mac." |
| 142 | case .emptyAudio: "No audio was captured. Hold the shortcut a little longer and try again." |
| 143 | case .noSpeech: "Apple Speech did not detect any words." |
| 144 | case .audioOverrun: "The speech model could not keep up with the microphone." |
| 145 | } |
| 146 | } |
| 147 | } |