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
fix(dictionary): preserve possessives and verify approved audio learning
altic-devbe5e2a65a2b9
diff --git a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swiftindex f68333c4..0312fe3a 100644--- a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift+++ b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift@@ -35,15 +35,21 @@ final class AutomaticDictionaryTrainingSession: ObservableObject {var onSuccess: (() -> Void)?private let asr: ASRService+ private let audioLearning: DictionaryAudioLearningServiceprivate var stopRequestedDuringStart = falseprivate var didStartAudioCapture = falseprivate var discardCurrentCapture = falseprivate var isCancelled = falseprivate var stopTask: Task<Void, Never>?- init(candidate: AutomaticDictionaryCorrectionCandidate, asr: ASRService) {+ init(+ candidate: AutomaticDictionaryCorrectionCandidate,+ asr: ASRService,+ audioLearning: DictionaryAudioLearningService = .shared+ ) {self.candidate = candidateself.asr = asr+ self.audioLearning = audioLearninglet replacement = CustomDictionaryTrainingMerge.normalizedReplacement(candidate.correctedText)let savedVariants = SettingsStore.shared.customDictionaryEntries@@ -362,7 +368,7 @@ final class AutomaticDictionaryTrainingSession: ObservableObject {$0.replacement.caseInsensitiveCompare(self.intendedText) == .orderedSame}) {// Scheduled work runs after this synchronous text save returns.- DictionaryAudioLearningService.shared.learn(+ self.audioLearning.learn(entry: entry, evidenceID: self.candidate.id, evidence: evidence)}diff --git a/Sources/Fluid/Services/DictionaryPronunciationDecision.swift b/Sources/Fluid/Services/DictionaryPronunciationDecision.swiftindex 26ec8a98..ca19ab43 100644--- a/Sources/Fluid/Services/DictionaryPronunciationDecision.swift+++ b/Sources/Fluid/Services/DictionaryPronunciationDecision.swift@@ -12,6 +12,28 @@ enum DictionaryPronunciationDecision {return score >= (knownVariant ? 0.70 : 0.85)}+ /// A new spoken possessive is still the enrolled name. Preserve its grammatical ending,+ /// unless a recorded correction explicitly taught a possessive-to-nonpossessive replacement.+ static func labelPreservingPossessive(+ _ label: String, heardText: String, profile: PronunciationDictionaryProfile+ ) -> String {+ guard profile.hasOriginalAudio,+ let last = label.last, last.isLetter || last.isNumber,+ let suffix = self.possessiveSuffix(heardText),+ self.possessiveSuffix(label) == nil,+ !profile.enrollments.contains(where: {+ $0.observedText.map { self.possessiveSuffix($0) != nil } ?? false+ })+ else { return label }+ return label + suffix+ }++ private static func possessiveSuffix(_ text: String) -> String? {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines.union(.punctuationCharacters))+ guard trimmed.lowercased().hasSuffix("'s") || trimmed.lowercased().hasSuffix("’s") else { return nil }+ return String(trimmed.suffix(2))+ }+private static func normalized(_ text: String) -> String {text.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).joined(separator: " ")}diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swiftindex 96eeaea6..55824b9a 100644--- a/Sources/Fluid/Services/FluidAudioProvider.swift+++ b/Sources/Fluid/Services/FluidAudioProvider.swift@@ -881,14 +881,18 @@ final class FluidAudioProvider: TranscriptionProvider {)guard !indices.isEmpty else { continue }let profile = profiles[match.prototypeIndex]+ var correctedLabel = labelif profile.hasOriginalAudio {guard profile.label.caseInsensitiveCompare(label) == .orderedSame else { continue }let heard = indices.map { words[$0].text }.joined(separator: " ")guard DictionaryPronunciationDecision.accepts(score: match.score, heardText: heard, profile: profile) else { continue }+ correctedLabel = DictionaryPronunciationDecision.labelPreservingPossessive(+ label, heardText: heard, profile: profile+ )}- candidates.append(Candidate(label: label, score: match.score, wordIndices: indices))+ candidates.append(Candidate(label: correctedLabel, score: match.score, wordIndices: indices))}var leaders: [Int: [(label: String, score: Float)]] = [:]diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swiftindex 5d272084..ac1677e8 100644--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift@@ -3520,3 +3520,73 @@ extension DictationE2ETests {}#endif}++extension DictationE2ETests {+ #if arch(arm64)+ func testOriginalPronunciationKeepsNewPossessiveEnding() {+ let id = UUID()+ let sample = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: "parakeet-v3", originalAudioID: UUID(), observedText: "jensen")+ var profile = PronunciationDictionaryProfile(dictionaryEntryID: id, label: "Jensen", modelKey: sample.modelKey, hiddenSize: 2, enrollments: [sample])+ for spoken in ["Jensen's", "Jensen’s"] {+ let result = ASRResult(text: spoken + " project", confidence: 1, duration: 1, processingTime: 0, tokenTimings: [+ TokenTiming(token: "▁" + spoken, tokenId: 1, startTime: 0, endTime: 0.48, confidence: 1),+ TokenTiming(token: "▁project", tokenId: 2, startTime: 0.6, endTime: 0.9, confidence: 1),+ ])+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [.init(prototypeIndex: 0, score: 0.8835, frameRange: 0..<6)], profiles: [profile], labels: [id: "Jensen"]), result.text)+ }+ XCTAssertEqual(DictionaryPronunciationDecision.labelPreservingPossessive("Jensen's", heardText: "Jensen's", profile: profile), "Jensen's")+ XCTAssertEqual(DictionaryPronunciationDecision.labelPreservingPossessive("Jensen", heardText: "Jensen", profile: profile), "Jensen")+ profile.enrollments[0].observedText = "Jensen's"+ XCTAssertEqual(DictionaryPronunciationDecision.labelPreservingPossessive("Jensen", heardText: "Jensen's", profile: profile), "Jensen", "An explicitly taught removal keeps its intended meaning")+ }++ func testApprovedCorrectionLearnsOriginalRealAudioThroughExistingSession() async throws {+ let environment = ProcessInfo.processInfo.environment+ guard let path = environment["FLUIDVOICE_PRONUNCIATION_AUDIO"], let modelPath = environment["FLUIDAUDIO_PARAKEET_MODEL_DIR"] else {+ throw XCTSkip("Set the public speech fixture and Parakeet model paths")+ }+ let defaults = UserDefaults.standard+ let previousEntries = defaults.object(forKey: self.customDictionaryEntriesKey)+ defer {+ if let previousEntries { defaults.set(previousEntries, forKey: self.customDictionaryEntriesKey) }+ else { defaults.removeObject(forKey: self.customDictionaryEntriesKey) }+ ASRService.invalidateDictionaryCache()+ }+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: folder) }+ let store = PronunciationDictionaryStore(fileURL: folder.appendingPathComponent("profiles.json"))+ let samples = Array(try AudioConverter().resampleAudioFile(path: path).prefix(160000))+ let models = try await AsrModels.load(from: URL(fileURLWithPath: modelPath), version: .v3)+ let manager = AsrManager(config: ASRConfig(tdtConfig: TdtConfig(blankId: AsrModelVersion.v3.blankId), encoderHiddenSize: 1024))+ try await manager.initialize(models: models)+ let transcription = try await manager.transcribe(samples, source: .microphone)+ await manager.cleanup()+ let words = WordAudioChunkExtractor.words(from: transcription.tokenTimings ?? [])+ let word = try XCTUnwrap(words.first { $0.text.count >= 5 && $0.startTime < 2 && $0.endTime - $0.startTime >= 0.24 })+ let delivered = words.map(\.text).joined(separator: " ")+ let oldRange = (delivered as NSString).range(of: word.text)+ let intended = "PersonalName"+ let edited = (delivered as NSString).replacingCharacters(in: oldRange, with: intended)+ var candidate = try XCTUnwrap(AutomaticDictionaryCorrectionDetector.candidate(before: delivered, after: edited, insertedRange: NSRange(location: 0, length: (delivered as NSString).length), allowsInsertionAtEnd: true))+ let recording = try XCTUnwrap(DictionaryLearningRecording(alignment: .init(modelKey: "parakeet-v3", words: words.map { .init(text: $0.text, start: $0.startTime, end: $0.endTime) }), samples: samples))+ candidate.audioEvidence = try DictionaryLearningAlignmentResolver.resolve(recording: recording, deliveredTextBeforeEdit: delivered, selectedUTF16Range: try XCTUnwrap(candidate.sourceUTF16Range), observedText: candidate.heardText)+ let worker = DictionaryAudioLearningService(store: store, canProcess: { true })+ let session = AutomaticDictionaryTrainingSession(candidate: candidate, asr: AppServices.shared.asr, audioLearning: worker)+ let before = await store.allProfiles()+ XCTAssertTrue(before.isEmpty, "Detection alone cannot activate acoustic learning")+ session.addOnlyCorrection()+ XCTAssertEqual(session.screen, .success)+ let entry = try XCTUnwrap(SettingsStore.shared.customDictionaryEntries.first { $0.replacement == intended })+ XCTAssertTrue(entry.triggers.contains(candidate.heardText.lowercased()))+ for _ in 0..<1000 where worker.pendingCount > 0 { try await Task.sleep(for: .milliseconds(10)) }+ XCTAssertEqual(worker.pendingCount, 0)+ let learned = await store.allProfiles()+ XCTAssertEqual(learned.count, 1)+ XCTAssertEqual(learned.first?.dictionaryEntryID, entry.id)+ XCTAssertEqual(learned.first?.label, intended)+ XCTAssertEqual(learned.first?.enrollments.first?.sourceRecordingID, recording.id)+ XCTAssertEqual(learned.first?.enrollments.first?.observedText, candidate.heardText)+ XCTAssertEqual(learned.first?.enrollments.count, 1)+ }+ #endif+}diff --git a/docs/design/original-audio-learning-implementation.md b/docs/design/original-audio-learning-implementation.mdindex 5dccb64f..0b695e90 100644--- a/docs/design/original-audio-learning-implementation.md+++ b/docs/design/original-audio-learning-implementation.md@@ -38,3 +38,14 @@ Validation status: scoped service lint is clean. Full-source format and strict l## Composition regression follow-upA verified failure showed that `fluid -> Fluid Voice` expanded an already-correct acoustic output into `Fluid Voice Voice`. The text matcher now protects completed occurrences of a rule's own output when that output contains a partial trigger. Ordinary rules retain the existing fast path. Tests cover independent uncorrected occurrences, capitalization, word boundaries, literal replacement text, and a combined sentence where text-only and acoustic-only each miss a different occurrence. This is deterministic composition proof, not a new field-accuracy claim. All 65 affected app tests passed, and the signed private FI build succeeded.+++## Approved-path and same-speaker follow-up++The production correction detector, original-occurrence resolver, existing Add Only session, background encoder and isolated durable store now run together in a real-audio integration test. Detection alone creates no pronunciation profile; approval saves the text rule and then exactly one linked enrollment. Dependency injection leaves the existing UI call unchanged. All 67 affected app tests passed together with no failures or skipped tests.++A separate real 60-second speech experiment enrolled the first occurrence and excluded its entire 14.88-second window from subsequent searches. Later NVIDIA and AI occurrences scored 0.877 and 0.914. A later Jensen occurrence scored 0.779, showing that the 0.85 novel-variant threshold can still miss useful matches; the known text fallback remains necessary. A broad, poorly aligned NVIDIA span scored 0.754 and correctly failed the novel-variant threshold. These labels are ASR-derived, not independent human ground truth, so this is diagnostic evidence rather than word-error-rate proof.++The experiment also found a concrete false edit: Jensen's scored 0.884 against Jensen and could lose its possessive. Original-audio matching now preserves straight or curly apostrophe possessives unless an approved observed variant explicitly taught their removal. Existing possessive labels are not doubled. This is a narrow English possessive safeguard, not a general inflection model. Tests cover both preservation and explicit removal.++Raw experiment: scratch/original-audio-learning/evaluation/personal-trials.json and Sources/PersonalProof/main.swift. No thresholds were relaxed from this small sample.