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
feat(dictionary): add pronunciation matching
altic-dev6d7e5d0d3800
diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 85916ad3..59615266 100644--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -34,7 +34,7 @@"location" : "https://github.com/altic-dev/FluidAudio.git","state" : {"branch" : "B/cohere-coreml-asr",- "revision" : "72625bbccf9f6c797a540a1f1cb66a4cb60753eb"+ "revision" : "edee7154e66d2196be896580c6c26ff81c2c528e"}},{diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex b8e3b54d..2bb02d5d 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -3967,6 +3967,14 @@ final class SettingsStore: ObservableObject {}}+ var pronunciationMatchingEnabled: Bool {+ get { self.defaults.object(forKey: Keys.pronunciationMatchingEnabled) as? Bool ?? false }+ set {+ objectWillChange.send()+ self.defaults.set(newValue, forKey: Keys.pronunciationMatchingEnabled)+ }+ }+/// Custom dictionary entries for word replacementvar customDictionaryEntries: [CustomDictionaryEntry] {get {@@ -4841,6 +4849,7 @@ private extension SettingsStore {static let customDictionaryEntries = "CustomDictionaryEntries"static let automaticDictionaryLearningEnabled = "AutomaticDictionaryLearningEnabled"static let vocabularyBoostingEnabled = "VocabularyBoostingEnabled"+ static let pronunciationMatchingEnabled = "PronunciationMatchingEnabled"// Transcription Provider (ASR)static let selectedTranscriptionProvider = "SelectedTranscriptionProvider"diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex aea270fb..60a777b6 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -87,6 +87,7 @@ final class ASRService: ObservableObject {@Published var downloadingModelId: String? = nil // Tracks which model is currently being downloaded@Published private(set) var isCancellingModelDownload: Bool = false@Published private(set) var isDictionaryTrainingCaptureActive: Bool = false+ private(set) var lastDictionaryTrainingResult: ASRTranscriptionResult?private var isStarting: Bool = false // Guard against re-entrant start() callsprivate var hasCompletedFirstTranscription: Bool = false // Track if model has warmed up with first transcription@@ -1345,6 +1346,9 @@ final class ASRService: ObservableObject {forDictionaryTraining: Bool = false) async -> String {DebugLogger.shared.info("🛑 STOP() called - beginning shutdown sequence", source: "ASRService")+ if forDictionaryTraining || self.isDictionaryTrainingCaptureActive {+ self.lastDictionaryTrainingResult = nil+ }self.lastCompletedAudioSnapshot = nillet stopStartedAt = Date().timeIntervalSince1970self.benchmarkLog("stop_start ageMs=\(self.elapsedMilliseconds(since: self.benchmarkRecordingStartedAt)) bufferedSamples=\(self.audioBuffer.count)")@@ -1494,6 +1498,7 @@ final class ASRService: ObservableObject {result = try await self.transcriptionExecutor.run { [provider] intry await provider.transcribeDictionaryTraining(pcm)}+ self.lastDictionaryTrainingResult = resultfinalSource = "dictionaryTraining"} else {result = try await self.transcriptionExecutor.run { [provider] indiff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swiftindex 32ad31a3..890e1ee9 100644--- a/Sources/Fluid/Services/FluidAudioProvider.swift+++ b/Sources/Fluid/Services/FluidAudioProvider.swift@@ -22,6 +22,7 @@ final class FluidAudioProvider: TranscriptionProvider {private(set) var isWordBoostingActive: Bool = falseprivate(set) var boostedVocabularyTermsCount: Int = 0private var boostedTermLookup: [String] = []+ private var pronunciationModelKey = ""/// Optional model override - if set, uses this model instead of the global setting./// Used for downloading specific models without changing the active selection.@@ -39,6 +40,7 @@ final class FluidAudioProvider: TranscriptionProvider {let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModellet asrModelVersion: AsrModelVersion = selectedModel == .parakeetTDTv2 ? .v2 : .v3let modelVersion = selectedModel == .parakeetTDTv2 ? "v2" : "v3"+ self.pronunciationModelKey = "parakeet-\(modelVersion)"let cacheDirectory = AsrModels.defaultCacheDirectory().deletingLastPathComponent()let modelCacheDirectory = AsrModels.defaultCacheDirectory(for: asrModelVersion)DebugLogger.shared.info(@@ -200,7 +202,31 @@ final class FluidAudioProvider: TranscriptionProvider {}func transcribeDictionaryTraining(_ samples: [Float]) async throws -> ASRTranscriptionResult {- try await self.transcribeStreaming(samples)+ guard let manager = self.streamingAsrManager else {+ throw NSError(+ domain: "FluidAudioProvider",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "ASR manager not initialized"]+ )+ }+ let shouldCapture = SettingsStore.shared.pronunciationMatchingEnabled+ await manager.setPronunciationCustomizationEnabled(shouldCapture)+ do {+ let result = try await manager.transcribe(samples, source: AudioSource.microphone)+ let features = await manager.consumePronunciationEncoderFeatures()+ await manager.setPronunciationCustomizationEnabled(false)+ return ASRTranscriptionResult(+ text: result.text,+ confidence: result.confidence,+ pronunciationEnrollment: shouldCapture+ ? self.makeEnrollment(result: result, features: features)+ : nil+ )+ } catch {+ _ = await manager.consumePronunciationEncoderFeatures()+ await manager.setPronunciationCustomizationEnabled(false)+ throw error+ }}func transcribeFinal(_ samples: [Float]) async throws -> ASRTranscriptionResult {@@ -216,9 +242,9 @@ final class FluidAudioProvider: TranscriptionProvider {// manager so the user still gets a transcription (just without CTC rescoring).do {let startedAt = Date().timeIntervalSince1970- let result = try await manager.transcribe(samples, source: AudioSource.microphone)+ let result = try await self.transcribeFinalResult(samples, manager: manager)self.logFinalBenchmark(samples: samples, text: result.text, startedAt: startedAt, usedFallback: false)- return ASRTranscriptionResult(text: result.text, confidence: result.confidence)+ return result} catch {guard let fallback = self.streamingAsrManager, fallback !== manager else {throw error@@ -228,10 +254,144 @@ final class FluidAudioProvider: TranscriptionProvider {source: "FluidAudioProvider")let startedAt = Date().timeIntervalSince1970- let result = try await fallback.transcribe(samples, source: AudioSource.microphone)+ let result = try await self.transcribeFinalResult(samples, manager: fallback)self.logFinalBenchmark(samples: samples, text: result.text, startedAt: startedAt, usedFallback: true)- return ASRTranscriptionResult(text: result.text, confidence: result.confidence)+ return result+ }+ }++ private func transcribeFinalResult(_ samples: [Float], manager: AsrManager) async throws -> ASRTranscriptionResult {+ let matchingEnabled = SettingsStore.shared.pronunciationMatchingEnabled && samples.count <= 16_000 * 15+ let dictionaryLabels = Dictionary(+ uniqueKeysWithValues: SettingsStore.shared.customDictionaryEntries.map { ($0.id, $0.replacement) }+ )+ let profiles: [PronunciationDictionaryProfile]+ if matchingEnabled {+ let storedProfiles = await PronunciationDictionaryStore.shared.profiles(+ modelKey: self.pronunciationModelKey+ )+ profiles = storedProfiles.compactMap { storedProfile in+ guard storedProfile.enrollments.count >= 3,+ let currentLabel = dictionaryLabels[storedProfile.dictionaryEntryID]+ else { return nil }+ var profile = storedProfile+ profile.label = currentLabel+ return profile+ }+ } else {+ profiles = []+ }+ await manager.setPronunciationCustomizationEnabled(!profiles.isEmpty)+ do {+ let result = try await manager.transcribe(samples, source: AudioSource.microphone)+ let features = await manager.consumePronunciationEncoderFeatures()+ await manager.setPronunciationCustomizationEnabled(false)+ guard let features, !profiles.isEmpty else {+ return ASRTranscriptionResult(text: result.text, confidence: result.confidence)+ }+ let startedAt = Date().timeIntervalSince1970+ let corrected = self.applyPronunciationMatches(result: result, features: features, profiles: profiles)+ let elapsedMs = Int(((Date().timeIntervalSince1970 - startedAt) * 1000).rounded())+ DebugLogger.shared.info(+ "PRONUNCIATION_MATCH profiles=\(profiles.count) elapsedMs=\(elapsedMs) changed=\(corrected != result.text)",+ source: "PronunciationMatching"+ )+ return ASRTranscriptionResult(text: corrected, confidence: result.confidence)+ } catch {+ _ = await manager.consumePronunciationEncoderFeatures()+ await manager.setPronunciationCustomizationEnabled(false)+ throw error+ }+ }++ private func makeEnrollment(+ result: ASRResult,+ features: EncoderFeatureSequence?+ ) -> PronunciationEnrollmentCapture? {+ guard let features,+ let timings = result.tokenTimings,+ let first = timings.first,+ let last = timings.last+ else { return nil }+ let start = max(0, Int(floor(first.startTime / features.frameDuration)))+ let end = min(features.frameCount, Int(ceil(last.endTime / features.frameDuration)))+ guard start < end,+ let embedding = PronunciationEmbeddingMatcher.embedding(from: features, frameRange: start..<end)+ else { return nil }+ return PronunciationEnrollmentCapture(+ values: embedding.values,+ sourceFrameCount: embedding.sourceFrameCount,+ modelKey: self.pronunciationModelKey+ )+ }++ private func applyPronunciationMatches(+ result: ASRResult,+ features: EncoderFeatureSequence,+ profiles: [PronunciationDictionaryProfile]+ ) -> String {+ guard let timings = result.tokenTimings else { return result.text }+ let words = WordAudioChunkExtractor.words(from: timings)+ guard !words.isEmpty else { return result.text }++ let usableProfiles = profiles.compactMap { profile -> (PronunciationDictionaryProfile, PronunciationEmbedding)? in+ let embeddings = profile.enrollments.map {+ PronunciationEmbedding(values: $0.values, sourceFrameCount: $0.sourceFrameCount)+ }+ guard profile.hiddenSize == features.hiddenSize,+ let prototype = PronunciationEmbeddingMatcher.prototype(from: embeddings)+ else { return nil }+ return (profile, prototype)+ }+ let matches = PronunciationEmbeddingMatcher.bestMatches(+ prototypes: usableProfiles.map { $0.1 },+ in: features+ )++ struct Candidate {+ let label: String+ let score: Float+ let wordIndices: [Int]+ }+ var candidates: [Candidate] = []+ for (index, match) in matches.enumerated() {+ guard let match, match.score >= PronunciationCustomizationDefaults.acceptanceThreshold else { continue }+ let startTime = Double(match.frameRange.lowerBound) * features.frameDuration+ let endTime = Double(match.frameRange.upperBound) * features.frameDuration+ let indices = WordAudioChunkExtractor.substantiallyOverlappingWordIndices(+ in: words,+ startTime: startTime,+ endTime: endTime+ )+ guard !indices.isEmpty else { continue }+ candidates.append(Candidate(label: usableProfiles[index].0.label, score: match.score, wordIndices: indices))+ }++ var claimed = Set<Int>()+ var accepted: [Candidate] = []+ for candidate in candidates.sorted(by: { $0.score > $1.score }) {+ guard candidate.wordIndices.allSatisfy({ !claimed.contains($0) }) else { continue }+ accepted.append(candidate)+ claimed.formUnion(candidate.wordIndices)+ DebugLogger.shared.info(+ "PRONUNCIATION_HIT score=\(String(format: "%.3f", candidate.score)) words=\(candidate.wordIndices)",+ source: "PronunciationMatching"+ )+ }+ guard !accepted.isEmpty else { return result.text }++ let replacementByStart = Dictionary(uniqueKeysWithValues: accepted.compactMap { candidate in+ candidate.wordIndices.first.map { ($0, candidate) }+ })+ var output: [String] = []+ for index in words.indices {+ if let candidate = replacementByStart[index] {+ output.append(candidate.label)+ } else if !claimed.contains(index) {+ output.append(words[index].text)+ }}+ return output.joined(separator: " ")}private func logFinalBenchmark(diff --git a/Sources/Fluid/Services/PronunciationDictionaryStore.swift b/Sources/Fluid/Services/PronunciationDictionaryStore.swiftnew file mode 100644index 00000000..0f77057f--- /dev/null+++ b/Sources/Fluid/Services/PronunciationDictionaryStore.swift@@ -0,0 +1,120 @@+import Foundation++struct PronunciationEnrollmentCapture: Codable, Sendable {+ let values: [Float]+ let sourceFrameCount: Int+ let modelKey: String+}++struct PronunciationDictionaryProfile: Codable, Identifiable, Sendable {+ let dictionaryEntryID: UUID+ var label: String+ let modelKey: String+ let hiddenSize: Int+ var enrollments: [PronunciationEnrollmentCapture]++ var id: String { "\(self.dictionaryEntryID.uuidString):\(self.modelKey)" }+}++actor PronunciationDictionaryStore {+ static let shared = PronunciationDictionaryStore()++ private struct Document: Codable {+ let version: Int+ var profiles: [PronunciationDictionaryProfile]+ }++ private let fileURL: URL+ private var document: Document?++ init(fileManager: FileManager = .default) {+ let baseURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")+ let appURL = baseURL.appendingPathComponent("FluidVoice", isDirectory: true)+ self.fileURL = appURL.appendingPathComponent("pronunciation-dictionary-v1.json")+ }++ func profiles(modelKey: String) -> [PronunciationDictionaryProfile] {+ self.loadIfNeeded()+ return self.document?.profiles.filter { $0.modelKey == modelKey } ?? []+ }++ func enrollmentCount(dictionaryEntryID: UUID, modelKey: String) -> Int {+ self.loadIfNeeded()+ return self.document?.profiles.first {+ $0.dictionaryEntryID == dictionaryEntryID && $0.modelKey == modelKey+ }?.enrollments.count ?? 0+ }++ func upsert(+ dictionaryEntryID: UUID,+ label: String,+ modelKey: String,+ enrollments: [PronunciationEnrollmentCapture]+ ) throws {+ guard let first = enrollments.first, !first.values.isEmpty else { return }+ guard enrollments.allSatisfy({ $0.modelKey == modelKey && $0.values.count == first.values.count }) else {+ throw CocoaError(.fileWriteInapplicableStringEncoding)+ }+ self.loadIfNeeded()+ var profiles = self.document?.profiles ?? []+ let profile = PronunciationDictionaryProfile(+ dictionaryEntryID: dictionaryEntryID,+ label: label,+ modelKey: modelKey,+ hiddenSize: first.values.count,+ enrollments: Array(enrollments.suffix(10))+ )+ if let index = profiles.firstIndex(where: {+ $0.dictionaryEntryID == dictionaryEntryID && $0.modelKey == modelKey+ }) {+ profiles[index] = profile+ } else {+ profiles.append(profile)+ }+ try self.persist(Document(version: 1, profiles: profiles))+ }++ func updateLabel(dictionaryEntryID: UUID, label: String) throws {+ self.loadIfNeeded()+ var profiles = self.document?.profiles ?? []+ var changed = false+ for index in profiles.indices where profiles[index].dictionaryEntryID == dictionaryEntryID {+ profiles[index].label = label+ changed = true+ }+ if changed {+ try self.persist(Document(version: 1, profiles: profiles))+ }+ }++ func delete(dictionaryEntryID: UUID) throws {+ self.loadIfNeeded()+ var profiles = self.document?.profiles ?? []+ profiles.removeAll { $0.dictionaryEntryID == dictionaryEntryID }+ try self.persist(Document(version: 1, profiles: profiles))+ }++ private func loadIfNeeded() {+ guard self.document == nil else { return }+ guard let data = try? Data(contentsOf: self.fileURL),+ let decoded = try? JSONDecoder().decode(Document.self, from: data),+ decoded.version == 1+ else {+ self.document = Document(version: 1, profiles: [])+ return+ }+ self.document = decoded+ }++ private func persist(_ updated: Document) throws {+ try FileManager.default.createDirectory(+ at: self.fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ try encoder.encode(updated).write(to: self.fileURL, options: .atomic)+ self.document = updated+ }+}diff --git a/Sources/Fluid/Services/TranscriptionProvider.swift b/Sources/Fluid/Services/TranscriptionProvider.swiftindex d098f2dd..b8cf47e8 100644--- a/Sources/Fluid/Services/TranscriptionProvider.swift+++ b/Sources/Fluid/Services/TranscriptionProvider.swift@@ -46,10 +46,16 @@ final class ModelPreparationProgressRelay: @unchecked Sendable {struct ASRTranscriptionResult {let text: Stringlet confidence: Float+ let pronunciationEnrollment: PronunciationEnrollmentCapture?- init(text: String, confidence: Float = 1.0) {+ init(+ text: String,+ confidence: Float = 1.0,+ pronunciationEnrollment: PronunciationEnrollmentCapture? = nil+ ) {self.text = textself.confidence = confidence+ self.pronunciationEnrollment = pronunciationEnrollment}}diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swiftindex c178ffa5..576ef89e 100644--- a/Sources/Fluid/UI/CustomDictionaryView.swift+++ b/Sources/Fluid/UI/CustomDictionaryView.swift@@ -33,6 +33,8 @@ struct CustomDictionaryView: View {@State private var trainingReplacement = ""@State private var trainingVariants: [String] = []+ @State private var pronunciationMatchingEnabled = SettingsStore.shared.pronunciationMatchingEnabled+ @State private var trainingPronunciationEnrollments: [PronunciationEnrollmentCapture] = []@State private var trainingSampleCount = 0@State private var lastTrainingOutput = ""@State private var lastTrainingOutputIsCovered = false@@ -86,13 +88,23 @@ struct CustomDictionaryView: View {}private var trainingFinalOutputIsReady: Bool {- !self.trainingAlreadyCorrectWithoutReplacement &&+ if self.pronunciationMatchingEnabled {+ return !self.trainingAlreadyCorrectWithoutReplacement &&+ self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount+ }+ return !self.trainingAlreadyCorrectWithoutReplacement &&self.trainingOutputIsCovered &&self.consecutiveCoveredCaptures >= CustomDictionaryTrainingMerge.readyCoveredCount}private var trainingAlreadyCorrectWithoutReplacement: Bool {- self.trainingVariants.isEmpty &&+ if self.pronunciationMatchingEnabled {+ return self.trainingVariants.isEmpty &&+ !self.lastTrainingOutput.isEmpty &&+ self.lastTrainingOutput.caseInsensitiveCompare(self.normalizedTrainingReplacement) == .orderedSame &&+ self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount+ }+ return self.trainingVariants.isEmpty &&self.trainingOutputIsCovered &&!self.lastTrainingOutput.isEmpty &&self.lastTrainingOutput.caseInsensitiveCompare(self.normalizedTrainingReplacement) == .orderedSame &&@@ -100,6 +112,9 @@ struct CustomDictionaryView: View {}private var trainingReadinessProgress: Int {+ if self.pronunciationMatchingEnabled {+ return min(self.trainingPronunciationEnrollments.count, CustomDictionaryTrainingMerge.readyCoveredCount)+ }guard !self.trainingAlreadyCorrectWithoutReplacement else {return CustomDictionaryTrainingMerge.readyCoveredCount}@@ -108,7 +123,10 @@ struct CustomDictionaryView: View {}private var trainingOutputIsCovered: Bool {- self.lastTrainingOutputIsCovered+ if self.pronunciationMatchingEnabled {+ return !self.trainingPronunciationEnrollments.isEmpty+ }+ return self.lastTrainingOutputIsCovered}private var trainingFinalOutputText: String {@@ -135,20 +153,12 @@ struct CustomDictionaryView: View {private var canAddTrainedReplacement: Bool {!self.normalizedTrainingReplacement.isEmpty &&- !self.trainingVariants.isEmpty &&+ (!self.trainingVariants.isEmpty || !self.trainingPronunciationEnrollments.isEmpty) &&!self.isTrainingRecording &&!self.isTrainingProcessing &&self.trainingFinalOutputIsReady}- private var trainedReplacementButtonTitle: String {- self.trainingAlreadyCorrectWithoutReplacement ? "No Replacement Needed" : "Add Replacement"- }-- private var shouldEmphasizeTrainedReplacementButton: Bool {- self.trainingFinalOutputIsReady && self.canAddTrainedReplacement- }-private var shouldPulseTrainedReplacementButton: Bool {self.shouldEmphasizeTrainedReplacementButton &&!self.isTrainedReplacementButtonHovered &&@@ -247,6 +257,12 @@ struct CustomDictionaryView: View {if let index = self.entries.firstIndex(where: { $0.id == updatedEntry.id }) {self.entries[index] = updatedEntryself.saveEntries()+ Task {+ try? await PronunciationDictionaryStore.shared.updateLabel(+ dictionaryEntryID: updatedEntry.id,+ label: updatedEntry.replacement+ )+ }}}}@@ -254,6 +270,7 @@ struct CustomDictionaryView: View {self.entries = SettingsStore.shared.customDictionaryEntriesself.loadBoostTerms()self.automaticDictionaryLearningEnabled = SettingsStore.shared.automaticDictionaryLearningEnabled+ self.pronunciationMatchingEnabled = SettingsStore.shared.pronunciationMatchingEnabledself.punctuationAutoConvertEnabled = SettingsStore.shared.autoConvertPunctuationEnabled}.onReceive(NotificationCenter.default.publisher(for: .parakeetVocabularyDidChange)) { _ in@@ -457,7 +474,7 @@ struct CustomDictionaryView: View {Spacer(minLength: 0)Button {- self.addTrainedReplacement()+ Task { await self.addTrainedReplacement() }} label: {Label(self.trainedReplacementButtonTitle,@@ -606,13 +623,53 @@ struct CustomDictionaryView: View {private var trainingRecorderPanel: some View {VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {- Text("Teach FluidVoice your pronunciation")- .font(self.theme.typography.bodySmallStrong)+ HStack(alignment: .top, spacing: self.theme.metrics.spacing.md) {+ VStack(alignment: .leading, spacing: 3) {+ Text("Teach FluidVoice your pronunciation")+ .font(self.theme.typography.bodySmallStrong)++ Text(+ self.pronunciationMatchingEnabled+ ? "Learns from 3 recordings and matches your pronunciation before text replacement."+ : "Off uses the current text-only replacement. Turn on to learn how you pronounce this word."+ )+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ .fixedSize(horizontal: false, vertical: true)+ }- if self.trainingFinalOutputIsReady {- Label("FluidVoice got it right 3 times in a row.", systemImage: "checkmark.circle.fill")+ Spacer()++ VStack(alignment: .trailing, spacing: 3) {+ Text("Voice matching")+ .font(self.theme.typography.captionStrong)+ .foregroundStyle(self.theme.palette.primaryText)++ Toggle("Voice matching", isOn: self.$pronunciationMatchingEnabled)+ .labelsHidden()+ .toggleStyle(.switch)+ .tint(self.theme.palette.accent)+ .disabled(self.isTrainingRecording || self.isTrainingProcessing)+ .onChange(of: self.pronunciationMatchingEnabled) { _, enabled in+ self.handlePronunciationMatchingChange(enabled: enabled)+ }+ .help("Experimental: match your saved pronunciation before text replacements")+ }+ }++ if self.trainingAlreadyCorrectWithoutReplacement {+ Label("Already recognized correctly", systemImage: "checkmark.circle.fill").font(self.theme.typography.captionStrong).foregroundStyle(self.theme.palette.accent)+ } else if self.trainingFinalOutputIsReady {+ Label(+ self.pronunciationMatchingEnabled+ ? "Voice profile captured 3 times."+ : "FluidVoice got it right 3 times in a row.",+ systemImage: "checkmark.circle.fill"+ )+ .font(self.theme.typography.captionStrong)+ .foregroundStyle(self.theme.palette.accent)} else {VStack(alignment: .leading, spacing: 7) {self.trainingInstruction(number: 1, text: "Press Start once.")@@ -670,26 +727,15 @@ struct CustomDictionaryView: View {private var trainingReadinessCaption: String {if self.trainingAlreadyCorrectWithoutReplacement {- return "Already correct. No replacement is needed."+ return "No dictionary entry was added."}if self.trainingFinalOutputIsReady {return "Ready. Add Replacement is unlocked."}let remaining = max(0, CustomDictionaryTrainingMerge.readyCoveredCount - self.trainingReadinessProgress)- return "\(remaining) correct \(remaining == 1 ? "try" : "tries") to unlock Add Replacement."- }-- private func trainingInstruction(number: Int, text: String) -> some View {- HStack(alignment: .firstTextBaseline, spacing: 8) {- Text("\(number)")- .font(self.theme.typography.captionStrong)- .foregroundStyle(self.theme.palette.accent)- .frame(width: 16, alignment: .center)-- Text(text)- .font(self.theme.typography.caption)- .foregroundStyle(self.theme.palette.secondaryText)- }+ return self.pronunciationMatchingEnabled+ ? "\(remaining) voice \(remaining == 1 ? "sample" : "samples") to unlock Add Replacement."+ : "\(remaining) correct \(remaining == 1 ? "try" : "tries") to unlock Add Replacement."}private var trainingHeardSection: some View {@@ -1823,6 +1869,11 @@ struct CustomDictionaryView: View {let transcript = await self.asr.stop(forDictionaryTraining: true)self.isTrainingProcessing = false+ if self.pronunciationMatchingEnabled,+ let enrollment = self.asr.lastDictionaryTrainingResult?.pronunciationEnrollment+ {+ self.trainingPronunciationEnrollments.append(enrollment)+ }self.addTrainingVariant(from: transcript)await self.continueAutomaticTrainingIfNeeded()}@@ -1851,6 +1902,13 @@ struct CustomDictionaryView: View {}private func addTrainingVariant(from transcript: String) {+ if self.pronunciationMatchingEnabled,+ self.asr.lastDictionaryTrainingResult?.pronunciationEnrollment == nil+ {+ self.trainingHasError = true+ self.trainingStatusMessage = "Couldn't capture a voice profile. Try again with one clear word."+ return+ }guard let detected = CustomDictionaryTrainingMerge.normalizedTrigger(transcript) else {self.lastTrainingOutput = ""self.lastTrainingOutputIsCovered = false@@ -1913,8 +1971,9 @@ struct CustomDictionaryView: View {}}- private func addTrainedReplacement() {+ private func addTrainedReplacement() async {guard self.canAddTrainedReplacement else { return }+ self.isTrainingProcessing = truelet replacementText = self.normalizedTrainingReplacementlet updatesExisting = self.entries.contains {$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame@@ -1924,6 +1983,29 @@ struct CustomDictionaryView: View {replacement: replacementText,triggers: self.trainingVariants)+ let entry = self.entries.first {+ $0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame+ }+ let enrollments = self.trainingPronunciationEnrollments+ if self.pronunciationMatchingEnabled, let entry, let modelKey = enrollments.first?.modelKey {+ do {+ try await PronunciationDictionaryStore.shared.upsert(+ dictionaryEntryID: entry.id,+ label: replacementText,+ modelKey: modelKey,+ enrollments: enrollments+ )+ } catch {+ self.isTrainingProcessing = false+ self.trainingHasError = true+ self.trainingStatusMessage = "Couldn't save the voice profile. Try again."+ DebugLogger.shared.error(+ "Failed to save pronunciation profile: \(error.localizedDescription)",+ source: "PronunciationMatching"+ )+ return+ }+ }self.saveEntries()self.resetTraining()self.showReplacementConfirmation(@@ -1962,6 +2044,7 @@ struct CustomDictionaryView: View {DictionaryTrainingEndpointMonitor.shared.stop()self.trainingReplacement = ""self.trainingVariants = []+ self.trainingPronunciationEnrollments = []self.trainingSampleCount = 0self.lastTrainingOutput = ""self.lastTrainingOutputIsCovered = false@@ -1981,6 +2064,7 @@ struct CustomDictionaryView: View {guard oldKey != newKey else { return }self.trainingVariants = self.existingTrainingVariants(for: newValue)+ self.trainingPronunciationEnrollments = []self.trainingSampleCount = 0self.lastTrainingOutput = ""self.lastTrainingOutputIsCovered = false@@ -2168,6 +2252,9 @@ struct CustomDictionaryView: View {private func deleteEntry(_ entry: SettingsStore.CustomDictionaryEntry) {self.entries.removeAll { $0.id == entry.id }self.saveEntries()+ Task {+ try? await PronunciationDictionaryStore.shared.delete(dictionaryEntryID: entry.id)+ }}/// Returns all existing trigger words for duplicate detection@@ -2190,6 +2277,41 @@ struct CustomDictionaryView: View {}}+private extension CustomDictionaryView {+ var trainedReplacementButtonTitle: String {+ self.trainingAlreadyCorrectWithoutReplacement ? "Nothing to Save" : "Add Replacement"+ }++ var shouldEmphasizeTrainedReplacementButton: Bool {+ self.trainingFinalOutputIsReady && self.canAddTrainedReplacement+ }++ func trainingInstruction(number: Int, text: String) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ Text("\(number)")+ .font(self.theme.typography.captionStrong)+ .foregroundStyle(self.theme.palette.accent)+ .frame(width: 16, alignment: .center)++ Text(text)+ .font(self.theme.typography.caption)+ .foregroundStyle(self.theme.palette.secondaryText)+ }+ }++ func handlePronunciationMatchingChange(enabled: Bool) {+ SettingsStore.shared.pronunciationMatchingEnabled = enabled+ self.isAutomaticTrainingEnabled = false+ DictionaryTrainingEndpointMonitor.shared.stop()+ self.trainingVariants = self.existingTrainingVariants(for: self.trainingReplacement)+ self.trainingPronunciationEnrollments = []+ self.resetTrainingVerificationAttempts()+ self.trainingStatusMessage = self.normalizedTrainingReplacement.isEmpty+ ? "Type the correct text."+ : ""+ }+}+private enum DictionaryComposerMode: CaseIterable, Identifiable {case traincase manual