Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Add custom dictionary import and export

altic-dev23d273458a88
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 6b21b482..b250dbd2 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -2833,16 +2833,16 @@ final class ASRService: ObservableObject {
// MARK: - Custom Dictionary (Cached Regex)
/// Cache for compiled custom dictionary regexes.
- /// Key: trigger word, Value: (compiled regex, replacement text)
+ /// Key: trigger word, Value: (compiled regex, escaped replacement template)
/// Cleared when dictionary entries change.
- private static var cachedDictionaryPatterns: [(regex: NSRegularExpression, replacement: String)] = []
+ private static var cachedDictionaryPatterns: [(regex: NSRegularExpression, template: String)] = []
private static var dictionaryCacheNeedsRebuild: Bool = true
/// Rebuilds the regex cache if dictionary has changed.
/// Called lazily on first apply after settings change.
private static func rebuildDictionaryCache() {
let entries = SettingsStore.shared.customDictionaryEntries
- var patterns: [(regex: NSRegularExpression, replacement: String)] = []
+ var patterns: [(regex: NSRegularExpression, template: String)] = []
for entry in entries {
for trigger in entry.triggers {
@@ -2854,7 +2854,7 @@ final class ASRService: ObservableObject {
options: .caseInsensitive
) else { continue }
- patterns.append((regex: regex, replacement: entry.replacement))
+ patterns.append((regex: regex, template: NSRegularExpression.escapedTemplate(for: entry.replacement)))
}
}
@@ -2892,7 +2892,7 @@ final class ASRService: ObservableObject {
result = pattern.regex.stringByReplacingMatches(
in: result,
range: NSRange(result.startIndex..., in: result),
- withTemplate: pattern.replacement
+ withTemplate: pattern.template
)
}
diff --git a/Sources/Fluid/Services/DictionaryTransferService.swift b/Sources/Fluid/Services/DictionaryTransferService.swift
new file mode 100644
index 00000000..0fa9b83c
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryTransferService.swift
@@ -0,0 +1,377 @@
+import Foundation
+
+struct DictionaryTransferReplacement: Codable, Equatable {
+ let from: [String]
+ let to: String
+
+ init(from: [String], to: String) {
+ self.from = from
+ self.to = to
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ if container.contains(.from) {
+ self.from = try Self.decodeStringList(from: container, key: .from)
+ } else if container.contains(.triggers) {
+ self.from = try Self.decodeStringList(from: container, key: .triggers)
+ } else {
+ throw DecodingError.keyNotFound(
+ CodingKeys.from,
+ DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected from or triggers.")
+ )
+ }
+
+ self.to = try container.decodeIfPresent(String.self, forKey: .to)
+ ?? container.decode(String.self, forKey: .replacement)
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(self.from, forKey: .from)
+ try container.encode(self.to, forKey: .to)
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case from
+ case to
+ case triggers
+ case replacement
+ }
+
+ private static func decodeStringList(
+ from container: KeyedDecodingContainer<CodingKeys>,
+ key: CodingKeys
+ ) throws -> [String] {
+ if let values = try? container.decodeIfPresent([String].self, forKey: key) {
+ return values
+ }
+ if let value = try? container.decodeIfPresent(String.self, forKey: key) {
+ return [value]
+ }
+ if try container.decodeNil(forKey: key) {
+ return []
+ }
+ var codingPath = container.codingPath
+ codingPath.append(key)
+ throw DecodingError.typeMismatch(
+ [String].self,
+ DecodingError.Context(codingPath: codingPath, debugDescription: "Expected a string or list of strings.")
+ )
+ }
+}
+
+struct DictionaryTransferDocument: Codable, Equatable {
+ let replacements: [DictionaryTransferReplacement]
+ let customWords: [String]
+
+ init(replacements: [DictionaryTransferReplacement], customWords: [String]) {
+ self.replacements = replacements
+ self.customWords = customWords
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ let replacements = try Self.decodeReplacements(from: container)
+ let customWords = try Self.decodeCustomWords(from: container)
+
+ guard replacements.found || customWords.found else {
+ throw DecodingError.dataCorrupted(
+ DecodingError.Context(
+ codingPath: decoder.codingPath,
+ debugDescription: "Expected replacements, customWords, terms, or API items/entries."
+ )
+ )
+ }
+
+ self.replacements = replacements.values
+ self.customWords = customWords.values
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(self.replacements, forKey: .replacements)
+ try container.encode(self.customWords, forKey: .customWords)
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case replacements
+ case customWords
+ case terms
+ case items
+ case entries
+ }
+
+ private static func decodeReplacements(
+ from container: KeyedDecodingContainer<CodingKeys>
+ ) throws -> (found: Bool, values: [DictionaryTransferReplacement]) {
+ if container.contains(.replacements) {
+ return try (true, container.decode([DictionaryTransferReplacement].self, forKey: .replacements))
+ }
+ if container.contains(.items),
+ let replacements = try? container.decode([DictionaryTransferReplacement].self, forKey: .items)
+ {
+ return (true, replacements)
+ }
+ if container.contains(.entries),
+ let replacements = try? container.decode([DictionaryTransferReplacement].self, forKey: .entries)
+ {
+ return (true, replacements)
+ }
+ return (false, [])
+ }
+
+ private static func decodeCustomWords(
+ from container: KeyedDecodingContainer<CodingKeys>
+ ) throws -> (found: Bool, values: [String]) {
+ let customWords = try Self.decodeCustomWordValues(from: container, key: .customWords)
+ if customWords.found {
+ return customWords
+ }
+ let terms = try Self.decodeCustomWordValues(from: container, key: .terms)
+ if terms.found {
+ return terms
+ }
+ if container.contains(.items),
+ let items = try? Self.decodeCustomWordValues(from: container, key: .items),
+ items.found
+ {
+ return items
+ }
+ if container.contains(.entries),
+ let entries = try? Self.decodeCustomWordValues(from: container, key: .entries),
+ entries.found
+ {
+ return entries
+ }
+ return (false, [])
+ }
+
+ private static func decodeCustomWordValues(
+ from container: KeyedDecodingContainer<CodingKeys>,
+ key: CodingKeys
+ ) throws -> (found: Bool, values: [String]) {
+ guard container.contains(key) else { return (false, []) }
+ return try (true, container.decode([DictionaryTransferCustomWord].self, forKey: key).map(\.text))
+ }
+}
+
+private struct DictionaryTransferCustomWord: Decodable {
+ let text: String
+
+ init(from decoder: Decoder) throws {
+ if let text = try? decoder.singleValueContainer().decode(String.self) {
+ self.text = text
+ return
+ }
+
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.text = try container.decode(String.self, forKey: .text)
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case text
+ }
+}
+
+enum DictionaryTransferImportMode {
+ case merge
+ case replace
+}
+
+struct DictionaryTransferState {
+ let replacements: [SettingsStore.CustomDictionaryEntry]
+ let customWords: [ParakeetVocabularyStore.VocabularyConfig.Term]
+}
+
+struct DictionaryTransferSummary {
+ let replacementCount: Int
+ let customWordCount: Int
+}
+
+enum DictionaryTransferServiceError: LocalizedError {
+ case invalidJSON
+
+ var errorDescription: String? {
+ switch self {
+ case .invalidJSON:
+ return "The selected file is not a valid FluidVoice dictionary file."
+ }
+ }
+}
+
+@MainActor
+final class DictionaryTransferService {
+ static let shared = DictionaryTransferService()
+
+ private static let importedCustomWordWeight: Float = 10.0
+ private static let maxCustomWords = 256
+
+ private init() {}
+
+ func makeExportDocument() throws -> DictionaryTransferDocument {
+ try DictionaryTransferDocument(
+ replacements: SettingsStore.shared.customDictionaryEntries.compactMap(Self.exportReplacement(from:)),
+ customWords: Self.normalizedUniqueStrings(
+ ParakeetVocabularyStore.shared.loadUserBoostTerms().map(\.text),
+ lowercased: false
+ )
+ )
+ }
+
+ func encode(_ document: DictionaryTransferDocument) throws -> Data {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ return try encoder.encode(Self.normalizedDocument(document))
+ }
+
+ func decode(_ data: Data) throws -> DictionaryTransferDocument {
+ do {
+ let document = try JSONDecoder().decode(DictionaryTransferDocument.self, from: data)
+ return Self.normalizedDocument(document)
+ } catch {
+ throw DictionaryTransferServiceError.invalidJSON
+ }
+ }
+
+ @discardableResult
+ func restore(_ document: DictionaryTransferDocument, mode: DictionaryTransferImportMode) throws -> DictionaryTransferSummary {
+ let state = try Self.importState(
+ document: document,
+ mode: mode,
+ currentReplacements: SettingsStore.shared.customDictionaryEntries,
+ currentCustomWords: ParakeetVocabularyStore.shared.loadUserBoostTerms()
+ )
+
+ try ParakeetVocabularyStore.shared.saveUserBoostTerms(state.customWords)
+ SettingsStore.shared.customDictionaryEntries = state.replacements
+ ASRService.invalidateDictionaryCache()
+ NotificationCenter.default.post(name: .parakeetVocabularyDidChange, object: nil)
+
+ return DictionaryTransferSummary(
+ replacementCount: state.replacements.count,
+ customWordCount: state.customWords.count
+ )
+ }
+
+ func suggestedFilename(for date: Date = Date()) -> String {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyy-MM-dd_HH-mm"
+ return "FluidVoice_Dictionary_\(formatter.string(from: date)).json"
+ }
+
+ static func importState(
+ document: DictionaryTransferDocument,
+ mode: DictionaryTransferImportMode,
+ currentReplacements: [SettingsStore.CustomDictionaryEntry],
+ currentCustomWords: [ParakeetVocabularyStore.VocabularyConfig.Term]
+ ) throws -> DictionaryTransferState {
+ let normalizedDocument = self.normalizedDocument(document)
+ var replacements = mode == .replace ? [] : currentReplacements
+ for replacement in normalizedDocument.replacements {
+ guard let entry = self.storeReplacement(from: replacement) else { continue }
+ self.upsert(entry, into: &replacements)
+ }
+
+ var customWords = mode == .replace ? [] : currentCustomWords
+ for word in normalizedDocument.customWords {
+ guard customWords.count < self.maxCustomWords else { break }
+ if customWords.contains(where: { $0.text.caseInsensitiveCompare(word) == .orderedSame }) {
+ continue
+ }
+ customWords.append(
+ ParakeetVocabularyStore.VocabularyConfig.Term(
+ text: word,
+ weight: self.importedCustomWordWeight,
+ aliases: []
+ )
+ )
+ }
+
+ return DictionaryTransferState(replacements: replacements, customWords: customWords)
+ }
+
+ private static func normalizedDocument(_ document: DictionaryTransferDocument) -> DictionaryTransferDocument {
+ DictionaryTransferDocument(
+ replacements: document.replacements.compactMap(self.exportReplacement(from:)),
+ customWords: self.normalizedUniqueStrings(document.customWords, lowercased: false)
+ )
+ }
+
+ private static func exportReplacement(from entry: SettingsStore.CustomDictionaryEntry) -> DictionaryTransferReplacement? {
+ let from = self.normalizedUniqueStrings(entry.triggers, lowercased: true)
+ let to = entry.replacement.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !from.isEmpty, !to.isEmpty else { return nil }
+ return DictionaryTransferReplacement(from: from, to: to)
+ }
+
+ private static func exportReplacement(from replacement: DictionaryTransferReplacement) -> DictionaryTransferReplacement? {
+ let from = self.normalizedUniqueStrings(replacement.from, lowercased: true)
+ let to = replacement.to.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !from.isEmpty, !to.isEmpty else { return nil }
+ return DictionaryTransferReplacement(from: from, to: to)
+ }
+
+ private static func storeReplacement(
+ from replacement: DictionaryTransferReplacement
+ ) -> SettingsStore.CustomDictionaryEntry? {
+ let from = self.normalizedUniqueStrings(replacement.from, lowercased: true)
+ let to = replacement.to.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !from.isEmpty, !to.isEmpty else { return nil }
+ return SettingsStore.CustomDictionaryEntry(triggers: from, replacement: to)
+ }
+
+ private static func upsert(
+ _ entry: SettingsStore.CustomDictionaryEntry,
+ into entries: inout [SettingsStore.CustomDictionaryEntry]
+ ) {
+ let matchingIndex = entries.firstIndex {
+ $0.replacement.caseInsensitiveCompare(entry.replacement) == .orderedSame
+ }
+ let replacementID = matchingIndex.map { entries[$0].id } ?? entry.id
+ let replacementText = matchingIndex.map { entries[$0].replacement } ?? entry.replacement
+ let previousTriggers = matchingIndex.map { entries[$0].triggers } ?? []
+ let combinedTriggers = self.normalizedUniqueStrings(previousTriggers + entry.triggers, lowercased: true)
+ let triggerKeys = Set(combinedTriggers.map { $0.lowercased() })
+
+ entries.removeAll {
+ $0.replacement.caseInsensitiveCompare(entry.replacement) == .orderedSame
+ }
+
+ entries = entries.compactMap { existing in
+ let remainingTriggers = existing.triggers.filter { !triggerKeys.contains($0.lowercased()) }
+ guard !remainingTriggers.isEmpty else { return nil }
+ return SettingsStore.CustomDictionaryEntry(
+ id: existing.id,
+ triggers: remainingTriggers,
+ replacement: existing.replacement
+ )
+ }
+
+ entries.append(
+ SettingsStore.CustomDictionaryEntry(
+ id: replacementID,
+ triggers: combinedTriggers,
+ replacement: replacementText
+ )
+ )
+ }
+
+ private static func normalizedUniqueStrings(_ values: [String], lowercased: Bool) -> [String] {
+ var seen: Set<String> = []
+ var result: [String] = []
+ result.reserveCapacity(values.count)
+
+ for value in values {
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { continue }
+ let output = lowercased ? trimmed.lowercased() : trimmed
+ let key = output.lowercased()
+ guard !seen.contains(key) else { continue }
+ seen.insert(key)
+ result.append(output)
+ }
+
+ return result
+ }
+}
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index 14e93ede..4a8c49f2 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -6,7 +6,9 @@
// Created: 2025-12-21
//
+import AppKit
import SwiftUI
+import UniformTypeIdentifiers
struct CustomDictionaryView: View {
@Environment(\.theme) private var theme
@@ -80,13 +82,31 @@ struct CustomDictionaryView: View {
private var pageHeader: some View {
VStack(alignment: .leading, spacing: 8) {
- HStack {
- Image(systemName: "text.book.closed.fill")
- .font(.title2)
- .foregroundStyle(self.theme.palette.accent)
- Text("Custom Dictionary")
- .font(.title2)
- .fontWeight(.semibold)
+ HStack(alignment: .center, spacing: 12) {
+ HStack {
+ Image(systemName: "text.book.closed.fill")
+ .font(.title2)
+ .foregroundStyle(self.theme.palette.accent)
+ Text("Custom Dictionary")
+ .font(.title2)
+ .fontWeight(.semibold)
+ }
+
+ Spacer(minLength: 16)
+
+ HStack(spacing: 8) {
+ Button(action: self.exportDictionary) {
+ Label("Export", systemImage: "square.and.arrow.up")
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+
+ Button(action: self.importDictionary) {
+ Label("Import", systemImage: "square.and.arrow.down")
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ }
}
Text("Fix recurring transcription mistakes with Instant Replacement, or add Custom Words for names and product terms.")
@@ -461,6 +481,94 @@ struct CustomDictionaryView: View {
}
}
+ private func exportDictionary() {
+ do {
+ let panel = NSSavePanel()
+ panel.canCreateDirectories = true
+ panel.allowedContentTypes = [.json]
+ panel.nameFieldStringValue = DictionaryTransferService.shared.suggestedFilename()
+
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+
+ let document = try DictionaryTransferService.shared.makeExportDocument()
+ let data = try DictionaryTransferService.shared.encode(document)
+ try data.write(to: url, options: .atomic)
+
+ self.presentInfoAlert(
+ title: "Dictionary Exported",
+ message: "Saved \(document.replacements.count) replacement rules and \(document.customWords.count) custom words."
+ )
+ } catch {
+ self.presentErrorAlert(title: "Dictionary Export Failed", message: error.localizedDescription)
+ }
+ }
+
+ private func importDictionary() {
+ do {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = false
+ panel.canChooseFiles = true
+ panel.allowsMultipleSelection = false
+ panel.allowedContentTypes = [.json]
+
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+
+ let data = try Data(contentsOf: url)
+ let document = try DictionaryTransferService.shared.decode(data)
+ guard let mode = self.confirmDictionaryImport(document) else { return }
+
+ let summary = try DictionaryTransferService.shared.restore(document, mode: mode)
+ self.entries = SettingsStore.shared.customDictionaryEntries
+ self.loadBoostTerms()
+
+ self.presentInfoAlert(
+ title: "Dictionary Imported",
+ message: "Now using \(summary.replacementCount) replacement rules and \(summary.customWordCount) custom words."
+ )
+ } catch {
+ self.presentErrorAlert(title: "Dictionary Import Failed", message: error.localizedDescription)
+ }
+ }
+
+ private func confirmDictionaryImport(_ document: DictionaryTransferDocument) -> DictionaryTransferImportMode? {
+ let confirm = NSAlert()
+ confirm.messageText = "Import this dictionary?"
+ confirm.informativeText = """
+ Found \(document.replacements.count) replacement rules and \(document.customWords.count) custom words.
+
+ Merge adds them to your current dictionary. Replace clears the current dictionary first.
+ """
+ confirm.alertStyle = .warning
+ confirm.addButton(withTitle: "Merge")
+ confirm.addButton(withTitle: "Replace")
+ confirm.addButton(withTitle: "Cancel")
+
+ switch confirm.runModal() {
+ case .alertFirstButtonReturn:
+ return .merge
+ case .alertSecondButtonReturn:
+ return .replace
+ default:
+ return nil
+ }
+ }
+
+ private func presentInfoAlert(title: String, message: String) {
+ let alert = NSAlert()
+ alert.messageText = title
+ alert.informativeText = message
+ alert.alertStyle = .informational
+ alert.runModal()
+ }
+
+ private func presentErrorAlert(title: String, message: String) {
+ let alert = NSAlert()
+ alert.messageText = title
+ alert.informativeText = message
+ alert.alertStyle = .critical
+ alert.runModal()
+ }
+
private func deleteBoostTerm(at index: Int) {
guard self.boostTerms.indices.contains(index) else { return }
self.boostTerms.remove(at: index)
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index 3f97b50a..87f45ec0 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -18,6 +18,7 @@ final class DictationE2ETests: XCTestCase {
private let selectedProviderIDKey = "SelectedProviderID"
private let availableModelsByProviderKey = "AvailableModelsByProvider"
private let selectedModelByProviderKey = "SelectedModelByProvider"
+ private let customDictionaryEntriesKey = "CustomDictionaryEntries"
private let commandModeLinkedToGlobalKey = "CommandModeLinkedToGlobal"
private let commandModeSelectedProviderIDKey = "CommandModeSelectedProviderID"
private let commandModeSelectedModelKey = "CommandModeSelectedModel"
@@ -68,6 +69,264 @@ final class DictationE2ETests: XCTestCase {
}
}
+ func testDictionaryTransferDocument_encodesSimpleUserFormat() throws {
+ let document = DictionaryTransferDocument(
+ replacements: [
+ DictionaryTransferReplacement(from: ["fluid voice", "fluid boys"], to: "FluidVoice"),
+ ],
+ customWords: ["FluidVoice", "GEMBA-E"]
+ )
+
+ let data = try DictionaryTransferService.shared.encode(document)
+ let json = String(data: data, encoding: .utf8) ?? ""
+ let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ let replacements = try XCTUnwrap(root["replacements"] as? [[String: Any]])
+ let firstReplacement = try XCTUnwrap(replacements.first)
+
+ XCTAssertEqual(firstReplacement["from"] as? [String], ["fluid voice", "fluid boys"])
+ XCTAssertEqual(firstReplacement["to"] as? String, "FluidVoice")
+ XCTAssertEqual(root["customWords"] as? [String], ["FluidVoice", "GEMBA-E"])
+ XCTAssertFalse(json.contains("\"triggers\""))
+ XCTAssertFalse(json.contains("\"replacement\""))
+ XCTAssertFalse(json.contains("\"aliases\""))
+ }
+
+ func testDictionaryTransferImport_replaceMapsSimpleFormatToStores() throws {
+ let document = DictionaryTransferDocument(
+ replacements: [
+ DictionaryTransferReplacement(from: [" Fluid Voice ", "FLUID BOYS", ""], to: " FluidVoice "),
+ ],
+ customWords: [" FluidVoice ", "fluidvoice", " Barath "]
+ )
+ let existingReplacement = SettingsStore.CustomDictionaryEntry(triggers: ["old"], replacement: "Old")
+ let existingWord = ParakeetVocabularyStore.VocabularyConfig.Term(text: "OldWord", weight: 13.0)
+
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [existingReplacement],
+ currentCustomWords: [existingWord]
+ )
+
+ XCTAssertEqual(state.replacements.count, 1)
+ XCTAssertEqual(state.replacements.first?.triggers, ["fluid voice", "fluid boys"])
+ XCTAssertEqual(state.replacements.first?.replacement, "FluidVoice")
+ XCTAssertEqual(state.customWords.map(\.text), ["FluidVoice", "Barath"])
+ XCTAssertEqual(state.customWords.map(\.weight), [10.0, 10.0])
+ }
+
+ func testDictionaryTransferImport_mergeDedupesAndMovesDuplicateTriggers() throws {
+ let oldReplacement = SettingsStore.CustomDictionaryEntry(
+ triggers: ["fluid voice", "old trigger"],
+ replacement: "Old"
+ )
+ let existingReplacement = SettingsStore.CustomDictionaryEntry(
+ triggers: ["fluid boys"],
+ replacement: "FluidVoice"
+ )
+ let existingWord = ParakeetVocabularyStore.VocabularyConfig.Term(
+ text: "Barath",
+ weight: 13.0,
+ aliases: ["barath w"]
+ )
+ let document = DictionaryTransferDocument(
+ replacements: [
+ DictionaryTransferReplacement(from: ["fluid voice", "fluid boys"], to: "FluidVoice"),
+ ],
+ customWords: ["barath", "GEMBA-E"]
+ )
+
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .merge,
+ currentReplacements: [oldReplacement, existingReplacement],
+ currentCustomWords: [existingWord]
+ )
+
+ let fluidVoiceEntry = try XCTUnwrap(state.replacements.first { $0.replacement == "FluidVoice" })
+ let oldEntry = try XCTUnwrap(state.replacements.first { $0.replacement == "Old" })
+ let barathTerm = try XCTUnwrap(state.customWords.first { $0.text == "Barath" })
+ let gembaeTerm = try XCTUnwrap(state.customWords.first { $0.text == "GEMBA-E" })
+
+ XCTAssertEqual(Set(fluidVoiceEntry.triggers), Set(["fluid voice", "fluid boys"]))
+ XCTAssertEqual(oldEntry.triggers, ["old trigger"])
+ XCTAssertEqual(barathTerm.weight, 13.0)
+ XCTAssertEqual(barathTerm.aliases, ["barath w"])
+ XCTAssertEqual(gembaeTerm.weight, 10.0)
+ }
+
+ func testDictionaryTransferImport_acceptsAppStyleReplacementKeysAndSingleFromValue() throws {
+ let json = """
+ {
+ "replacements": [
+ {
+ "from": "fluid voice",
+ "to": "FluidVoice"
+ },
+ {
+ "triggers": ["gemba e"],
+ "replacement": "GEMBA-E"
+ }
+ ]
+ }
+ """
+
+ let document = try DictionaryTransferService.shared.decode(Data(json.utf8))
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [],
+ currentCustomWords: []
+ )
+
+ XCTAssertEqual(state.replacements.map(\.triggers), [["fluid voice"], ["gemba e"]])
+ XCTAssertEqual(state.replacements.map(\.replacement), ["FluidVoice", "GEMBA-E"])
+ }
+
+ func testDictionaryTransferImport_acceptsLocalAPIReplacementItemsResponse() throws {
+ let json = """
+ {
+ "count": 1,
+ "items": [
+ {
+ "triggers": ["fluid voice"],
+ "replacement": "FluidVoice"
+ }
+ ]
+ }
+ """
+
+ let document = try DictionaryTransferService.shared.decode(Data(json.utf8))
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [],
+ currentCustomWords: []
+ )
+
+ XCTAssertEqual(state.replacements.first?.triggers, ["fluid voice"])
+ XCTAssertEqual(state.replacements.first?.replacement, "FluidVoice")
+ XCTAssertEqual(state.customWords.count, 0)
+ }
+
+ func testDictionaryTransferImportFeedsActualReplacementPath() throws {
+ defer { ASRService.invalidateDictionaryCache() }
+ let document = DictionaryTransferDocument(
+ replacements: [
+ DictionaryTransferReplacement(from: ["fluid voice"], to: "FluidVoice"),
+ ],
+ customWords: []
+ )
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [],
+ currentCustomWords: []
+ )
+
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ SettingsStore.shared.customDictionaryEntries = state.replacements
+ ASRService.invalidateDictionaryCache()
+
+ XCTAssertEqual(
+ ASRService.applyCustomDictionary("I use fluid voice daily."),
+ "I use FluidVoice daily."
+ )
+ }
+ }
+
+ func testCustomDictionaryReplacementTreatsReplacementTextLiterally() {
+ defer { ASRService.invalidateDictionaryCache() }
+ let entry = SettingsStore.CustomDictionaryEntry(
+ triggers: ["dollar path"],
+ replacement: #"$5 \path"#
+ )
+
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ SettingsStore.shared.customDictionaryEntries = [entry]
+ ASRService.invalidateDictionaryCache()
+
+ XCTAssertEqual(
+ ASRService.applyCustomDictionary("Use dollar path now."),
+ #"Use $5 \path now."#
+ )
+ }
+ }
+
+ func testDictionaryTransferImport_rejectsInvalidReplacementTriggerType() {
+ let json = """
+ {
+ "replacements": [
+ {
+ "from": 42,
+ "to": "FluidVoice"
+ }
+ ]
+ }
+ """
+
+ XCTAssertThrowsError(try DictionaryTransferService.shared.decode(Data(json.utf8)))
+ }
+
+ func testDictionaryTransferImport_acceptsParakeetVocabularyTermsFile() throws {
+ let json = """
+ {
+ "alpha": 2.8,
+ "terms": [
+ {
+ "text": "FluidVoice",
+ "aliases": ["fluid voice"],
+ "weight": 10.0
+ },
+ {
+ "text": "GEMBA-E"
+ }
+ ]
+ }
+ """
+
+ let document = try DictionaryTransferService.shared.decode(Data(json.utf8))
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [],
+ currentCustomWords: []
+ )
+
+ XCTAssertEqual(state.replacements.count, 0)
+ XCTAssertEqual(state.customWords.map(\.text), ["FluidVoice", "GEMBA-E"])
+ XCTAssertEqual(state.customWords.map(\.weight), [10.0, 10.0])
+ }
+
+ func testDictionaryTransferImport_acceptsLocalAPICustomWordsResponse() throws {
+ let json = """
+ {
+ "count": 2,
+ "items": [
+ {
+ "text": "FluidVoice",
+ "weight": 10.0,
+ "aliases": ["fluid voice"]
+ },
+ {
+ "text": "Barath"
+ }
+ ]
+ }
+ """
+
+ let document = try DictionaryTransferService.shared.decode(Data(json.utf8))
+ let state = try DictionaryTransferService.importState(
+ document: document,
+ mode: .replace,
+ currentReplacements: [],
+ currentCustomWords: []
+ )
+
+ XCTAssertEqual(state.replacements.count, 0)
+ XCTAssertEqual(state.customWords.map(\.text), ["FluidVoice", "Barath"])
+ }
+
func testDictationEndToEnd_whisperTiny_transcribesFixture() async throws {
// Arrange
SettingsStore.shared.shareAnonymousAnalytics = false