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

feat(dictionary): learn pronunciation from approved original audio

altic-dev68408b45897b
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 53304f05..1dfe609f 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -1294,7 +1294,7 @@
repositoryURL = "https://github.com/altic-dev/FluidAudio.git";
requirement = {
kind = revision;
- revision = 97ed23265098a78a09378659063d52dee908f9e0;
+ revision = 9725fb6c4c6884afd785f7d470ef1195d0a8ac17;
};
};
7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */ = {
diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 1df3e653..096df987 100644
--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -33,7 +33,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/altic-dev/FluidAudio.git",
"state" : {
- "revision" : "97ed23265098a78a09378659063d52dee908f9e0"
+ "revision" : "9725fb6c4c6884afd785f7d470ef1195d0a8ac17"
}
},
{
diff --git a/Package.swift b/Package.swift
index 14ab7e6f..c08a5044 100644
--- a/Package.swift
+++ b/Package.swift
@@ -11,7 +11,7 @@ let package = Package(
dependencies: [
.package(path: "Vendor/WebRTCAudioProcessing"),
.package(url: "https://github.com/mxcl/AppUpdater.git", from: "1.0.0"),
- .package(url: "https://github.com/altic-dev/FluidAudio.git", revision: "97ed23265098a78a09378659063d52dee908f9e0"),
+ .package(url: "https://github.com/altic-dev/FluidAudio.git", revision: "9725fb6c4c6884afd785f7d470ef1195d0a8ac17"),
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),
.package(url: "https://github.com/altic-dev/DynamicNotchKit.git", branch: "main"),
.package(url: "https://github.com/altic-dev/transcribe-cpp-swift.git", exact: "0.1.2"),
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 430eb017..aeacd5b0 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -2962,6 +2962,7 @@ struct ContentView: View {
self.appBench("asr_stop_return elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - asrStopStartedAt) * 1000).rounded()))")
self.completeDictationStopSnapshot(&stopSnapshot)
let audioSnapshot = self.asr.consumeLastCompletedAudioSnapshot()
+ let dictionaryLearningRecording = self.asr.consumeDictionaryLearningRecording()
let transcriptionDurationMilliseconds = self.asr.consumeLastFinalTranscriptionDurationMs()
DebugLogger.shared.info(
"Stop transcription result | chars=\(transcribedText.count) | empty=\(transcribedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)",
@@ -3345,7 +3346,8 @@ struct ContentView: View {
if didTypeExternally, !spokenSendAllowed {
AutomaticDictionaryCorrectionTracker.shared.beginObservingInsertion(
finalOutputPlan.plainText,
- targetPID: typingTarget.pid
+ targetPID: typingTarget.pid,
+ learningRecording: dictionaryLearningRecording
)
self.appBench("dictionary_tracking_scheduled afterDeliveryUI=true")
}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 700ca302..11582e1f 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -644,6 +644,7 @@ final class ASRService: ObservableObject {
func acquireExclusiveActivity(_ activity: ASRExclusiveActivity) throws -> ASRActivityLease {
guard let activeActivityLease = self.activeActivityLease else {
+ DictionaryAudioLearningService.shared.cancelForRecording()
let lease = ASRActivityLease(id: UUID(), activity: activity)
self.activeActivityLease = lease
self.activeExclusiveActivity = activity
@@ -665,6 +666,7 @@ final class ASRService: ObservableObject {
#endif
self.activeActivityLease = nil
self.activeExclusiveActivity = nil
+ DictionaryAudioLearningService.shared.activityDidEnd()
guard self.providerResetPending else { return }
self.providerResetPending = false
@@ -1906,6 +1908,8 @@ final class ASRService: ObservableObject {
// during long sessions where reallocation occurs frequently.
private let audioBuffer = ThreadSafeAudioBuffer()
private var lastCompletedAudioSnapshot: DictationAudioSnapshot?
+ private var lastDictionaryLearningRecording: DictionaryLearningRecording?
+ private var dictionaryLearningExpiryTask: Task<Void, Never>?
// Streaming transcription state (no VAD)
private let streamingTaskLifecycle = StreamingTaskLifecycle()
@@ -1947,6 +1951,35 @@ final class ASRService: ObservableObject {
private var lastAudioLevelSentAt: TimeInterval = 0
+ private func retainDictionaryLearningRecording(_ recording: DictionaryLearningRecording?) {
+ self.dictionaryLearningExpiryTask?.cancel()
+ self.dictionaryLearningExpiryTask = nil
+ self.lastDictionaryLearningRecording = recording
+ guard let id = recording?.id else { return }
+ self.dictionaryLearningExpiryTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .seconds(DictionaryLearningRecording.lifetime))
+ guard !Task.isCancelled, let self, self.lastDictionaryLearningRecording?.id == id else { return }
+ self.lastDictionaryLearningRecording = nil
+ self.dictionaryLearningExpiryTask = nil
+ }
+ }
+
+ func originalAudioEnrollment(_ evidence: DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture {
+ try Task.checkCancellation()
+ guard self.activeExclusiveActivity == nil else { throw CancellationError() }
+ #if arch(arm64)
+ if let provider = self.fluidAudioProvider,
+ let capture = try await provider.originalAudioEnrollment(evidence)
+ { return capture }
+ #endif
+ return try await OriginalAudioEmbeddingExtractor.extract(evidence)
+ }
+
+ func consumeDictionaryLearningRecording() -> DictionaryLearningRecording? {
+ defer { self.retainDictionaryLearningRecording(nil) }
+ return self.lastDictionaryLearningRecording
+ }
+
func consumeLastCompletedAudioSnapshot() -> DictationAudioSnapshot? {
let snapshot = self.lastCompletedAudioSnapshot
self.lastCompletedAudioSnapshot = nil
@@ -2567,6 +2600,7 @@ final class ASRService: ObservableObject {
DebugLogger.shared.warning("START() blocked - \(message)", source: "ASRService")
return .failed
}
+ self.retainDictionaryLearningRecording(nil)
self.audioCaptureStartGeneration &+= 1
let startGeneration = self.audioCaptureStartGeneration
self.isStarting = true
@@ -3200,6 +3234,7 @@ final class ASRService: ObservableObject {
self.lastDictionaryTrainingResult = nil
}
self.lastCompletedAudioSnapshot = nil
+ self.retainDictionaryLearningRecording(nil)
let stopStartedAt = Date().timeIntervalSince1970
let traceStartedAt = ProcessInfo.processInfo.systemUptime
var tracePreviousAt = traceStartedAt
@@ -3519,6 +3554,12 @@ final class ASRService: ObservableObject {
}
// Do not update self.finalText here to avoid instant binding insert in playground
+ if !useDictionaryTrainingPath, SettingsStore.shared.automaticDictionaryLearningEnabled,
+ let alignment = result.dictionaryLearningAlignment
+ {
+ self.retainDictionaryLearningRecording(DictionaryLearningRecording(alignment: alignment, samples: capturedPCM))
+ }
+
let textWithoutFillers = ASRService.removeFillerWords(result.text)
let dictionaryText = useDictionaryTrainingPath
? textWithoutFillers
diff --git a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
index 7ed8dfb2..42f16405 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
@@ -6,6 +6,13 @@ struct AutomaticDictionaryCorrectionCandidate: Equatable, Identifiable {
let id = UUID()
let heardText: String
let correctedText: String
+ var sourceUTF16Range: NSRange?
+ var audioEvidence: DictionaryLearningAudioEvidence?
+
+ static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.id == rhs.id && lhs.heardText == rhs.heardText && lhs.correctedText == rhs.correctedText
+ && lhs.sourceUTF16Range == rhs.sourceUTF16Range
+ }
}
struct AutomaticDictionaryTextChange: Equatable {
@@ -115,7 +122,8 @@ enum AutomaticDictionaryCorrectionDetector {
return AutomaticDictionaryCorrectionCandidate(
heardText: heard,
- correctedText: corrected
+ correctedText: corrected,
+ sourceUTF16Range: NSRange(location: oldTokenRange.location - insertedRange.location, length: oldTokenRange.length)
)
}
@@ -401,6 +409,7 @@ final class AutomaticDictionaryCorrectionTracker {
let pid: pid_t
let observesSelectionChanges: Bool
let observesFocusChanges: Bool
+ let learningRecording: DictionaryLearningRecording?
var lastValue: String
var insertedRange: NSRange
var pendingCorrection: PendingCorrection?
@@ -418,10 +427,14 @@ final class AutomaticDictionaryCorrectionTracker {
private var verificationTask: Task<Void, Never>?
private var timeoutTask: Task<Void, Never>?
private var debounceTask: Task<Void, Never>?
+ private var evidencePreparationTask: Task<Void, Never>?
+ private var suggestionGeneration = UUID()
private init() {}
- func beginObservingInsertion(_ insertedText: String, targetPID: pid_t?) {
+ func beginObservingInsertion(
+ _ insertedText: String, targetPID: pid_t?, learningRecording: DictionaryLearningRecording? = nil
+ ) {
self.cancel()
guard SettingsStore.shared.automaticDictionaryLearningEnabled,
!insertedText.isEmpty
@@ -442,7 +455,7 @@ final class AutomaticDictionaryCorrectionTracker {
)
guard !Task.isCancelled, let self else { return }
if let seed {
- self.installObserver(for: seed)
+ self.installObserver(for: seed, learningRecording: learningRecording)
return
}
}
@@ -450,6 +463,9 @@ final class AutomaticDictionaryCorrectionTracker {
}
func cancel() {
+ self.suggestionGeneration = UUID()
+ self.evidencePreparationTask?.cancel()
+ self.evidencePreparationTask = nil
self.verificationTask?.cancel()
self.verificationTask = nil
self.timeoutTask?.cancel()
@@ -629,7 +645,7 @@ final class AutomaticDictionaryCorrectionTracker {
)
}
- private func installObserver(for seed: InsertionSeed) {
+ private func installObserver(for seed: InsertionSeed, learningRecording: DictionaryLearningRecording?) {
self.verificationTask = nil
var createdObserver: AXObserver?
let createResult = AXObserverCreate(seed.pid, automaticDictionaryAXObserverCallback, &createdObserver)
@@ -665,6 +681,7 @@ final class AutomaticDictionaryCorrectionTracker {
pid: seed.pid,
observesSelectionChanges: selectionResult == .success,
observesFocusChanges: focusResult == .success,
+ learningRecording: learningRecording,
lastValue: seed.expectedValue,
insertedRange: seed.insertedRange,
pendingCorrection: nil
@@ -701,6 +718,18 @@ final class AutomaticDictionaryCorrectionTracker {
insertedRange: pending.insertedRange,
allowsInsertionAtEnd: true
)
+ var context: DictionaryLearningCorrectionContext?
+ if let recording = self.session?.learningRecording, let range = candidate?.sourceUTF16Range {
+ let before = pending.beforeValue as NSString
+ let insertion = pending.insertedRange
+ if insertion.location >= 0, insertion.location <= before.length,
+ insertion.length >= 0, insertion.length <= before.length - insertion.location
+ {
+ context = DictionaryLearningCorrectionContext(
+ recording: recording, deliveredTextBeforeEdit: before.substring(with: insertion), selectedUTF16Range: range
+ )
+ }
+ }
self.stopObservation()
guard let candidate,
@@ -717,9 +746,31 @@ final class AutomaticDictionaryCorrectionTracker {
return
}
- AutomaticDictionarySuggestionPolicy.shared.markShown(candidate)
- DictionaryCorrectionOverlayController.shared.show(candidate: candidate) { outcome in
- AutomaticDictionarySuggestionPolicy.shared.record(outcome, for: candidate)
+ let generation = self.suggestionGeneration
+ self.evidencePreparationTask = Task { @MainActor [weak self, context] in
+ let observedText = candidate.heardText
+ let evidence = await Task.detached(priority: .utility) {
+ guard let context else { return DictionaryLearningAudioEvidence?.none }
+ return try? DictionaryLearningAlignmentResolver.resolve(
+ recording: context.recording,
+ deliveredTextBeforeEdit: context.deliveredTextBeforeEdit,
+ selectedUTF16Range: context.selectedUTF16Range,
+ observedText: observedText
+ )
+ }.value
+ guard !Task.isCancelled, let self, self.suggestionGeneration == generation,
+ SettingsStore.shared.automaticDictionaryLearningEnabled,
+ !SettingsStore.shared.shouldShowOnboarding,
+ !self.isAlreadySaved(candidate), !AppServices.shared.asr.isRunning,
+ !DictionaryCorrectionOverlayController.shared.isPresented
+ else { return }
+ var prepared = candidate
+ prepared.audioEvidence = evidence
+ self.evidencePreparationTask = nil
+ AutomaticDictionarySuggestionPolicy.shared.markShown(prepared)
+ DictionaryCorrectionOverlayController.shared.show(candidate: prepared) { outcome in
+ AutomaticDictionarySuggestionPolicy.shared.record(outcome, for: prepared)
+ }
}
}
diff --git a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
index f96b1ad5..f68333c4 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
@@ -358,6 +358,14 @@ final class AutomaticDictionaryTrainingSession: ObservableObject {
replacement: self.intendedText,
triggers: triggers
)
+ if let evidence = self.candidate.audioEvidence, let entry = mergedEntries.first(where: {
+ $0.replacement.caseInsensitiveCompare(self.intendedText) == .orderedSame
+ }) {
+ // Scheduled work runs after this synchronous text save returns.
+ DictionaryAudioLearningService.shared.learn(
+ entry: entry, evidenceID: self.candidate.id, evidence: evidence
+ )
+ }
guard mergedEntries != currentEntries else {
self.completeSave(title: "Already in Dictionary")
return
diff --git a/Sources/Fluid/Services/DictionaryAudioLearningService.swift b/Sources/Fluid/Services/DictionaryAudioLearningService.swift
new file mode 100644
index 00000000..8d85d207
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryAudioLearningService.swift
@@ -0,0 +1,185 @@
+#if arch(arm64)
+import FluidAudio
+#endif
+import Foundation
+
+/// Existing correction UI owns approval. This service owns only the optional background evidence.
+@MainActor
+final class DictionaryAudioLearningService {
+ static let shared = DictionaryAudioLearningService()
+ typealias Extractor = @Sendable (DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture
+
+ private struct Request {
+ let entry: SettingsStore.CustomDictionaryEntry
+ let evidenceID: UUID
+ let evidence: DictionaryLearningAudioEvidence
+ let expiresAt: Date
+ }
+
+ private let store: PronunciationDictionaryStore
+ private let extract: Extractor
+ private let lifetime: TimeInterval
+ private let canProcess: @MainActor () -> Bool
+ private let isCurrent: @MainActor (SettingsStore.CustomDictionaryEntry) -> Bool
+ private var queue: [Request] = []
+ private var task: Task<Void, Never>?
+ private var expiryTask: Task<Void, Never>?
+ var pendingCount: Int { self.queue.count }
+
+ init(
+ store: PronunciationDictionaryStore = .shared,
+ lifetime: TimeInterval = 120,
+ extract: @escaping Extractor = { evidence in
+ try await AppServices.shared.asr.originalAudioEnrollment(evidence)
+ },
+ canProcess: @escaping @MainActor () -> Bool = {
+ SettingsStore.shared.automaticDictionaryLearningEnabled && AppServices.shared.asr.activeExclusiveActivity == nil
+ },
+ isCurrent: @escaping @MainActor (SettingsStore.CustomDictionaryEntry) -> Bool = {
+ SettingsStore.shared.customDictionaryEntries.contains($0)
+ }
+ ) {
+ self.store = store
+ self.lifetime = min(120, max(0, lifetime))
+ self.extract = extract
+ self.canProcess = canProcess
+ self.isCurrent = isCurrent
+ }
+
+ /// Cancel encoder work immediately when audio activity starts. Retry the same bounded request when it ends.
+ func cancelForRecording() { self.task?.cancel() }
+ func activityDidEnd() { self.drain() }
+
+ func learn(
+ entry: SettingsStore.CustomDictionaryEntry,
+ evidenceID: UUID,
+ evidence: DictionaryLearningAudioEvidence
+ ) {
+ guard !evidence.samples.isEmpty, evidence.samples.count <= 238_080 else { return }
+ guard !self.queue.contains(where: { $0.evidenceID == evidenceID }) else { return }
+ self.pruneExpired()
+ // Four short clips bound queued PCM to less than 4 MB. The text correction is already independent.
+ guard self.queue.count < 4 else {
+ DebugLogger.shared.warning(
+ "Audio learning queue full; text correction retained",
+ source: "DictionaryLearning"
+ )
+ return
+ }
+ self.queue.append(Request(
+ entry: entry,
+ evidenceID: evidenceID,
+ evidence: evidence,
+ expiresAt: Date().addingTimeInterval(self.lifetime)
+ ))
+ self.drain()
+ self.scheduleExpiry()
+ }
+
+ private func drain() {
+ self.pruneExpired()
+ guard self.task == nil, self.canProcess(), let request = self.queue.first else { return }
+ self.task = Task(priority: .utility) { [weak self] in
+ guard let self else { return }
+ var retry = false
+ defer {
+ if !retry { self.queue.removeAll { $0.evidenceID == request.evidenceID } }
+ self.task = nil
+ self.drain()
+ self.scheduleExpiry()
+ }
+ guard self.isCurrent(request.entry) else { return }
+ do {
+ let revision = await self.store.revision(for: request.entry.id)
+ let capture = try await self.extract(request.evidence)
+ try Task.checkCancellation()
+ guard request.expiresAt > Date(), self.isCurrent(request.entry) else { return }
+ let inserted = try await self.store.learnOriginalAudio(
+ entryID: request.entry.id,
+ label: request.entry.replacement,
+ evidenceID: request.evidenceID,
+ evidence: request.evidence,
+ capture: capture,
+ expectedRevision: revision
+ )
+ // An edit can happen while awaiting the store actor. Roll back only this event.
+ if Task.isCancelled || !self.isCurrent(request.entry) {
+ if inserted { try await self.store.removeOriginalAudio(evidenceID: request.evidenceID) }
+ retry = Task.isCancelled && request.expiresAt > Date()
+ return
+ }
+ DebugLogger.shared.info(
+ "Original pronunciation evidence saved",
+ source: "DictionaryLearning"
+ )
+ } catch is CancellationError {
+ retry = request.expiresAt > Date()
+ } catch {
+ DebugLogger.shared.warning(
+ "Original pronunciation evidence was not saved: \(error.localizedDescription)",
+ source: "DictionaryLearning"
+ )
+ }
+ }
+ }
+
+ private func pruneExpired() {
+ if let first = self.queue.first, first.expiresAt <= Date() { self.task?.cancel() }
+ self.queue.removeAll { $0.expiresAt <= Date() }
+ }
+
+ private func scheduleExpiry() {
+ self.expiryTask?.cancel()
+ guard let expiry = self.queue.map(\.expiresAt).min() else { self.expiryTask = nil; return }
+ let delay = max(0, expiry.timeIntervalSinceNow)
+ self.expiryTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .seconds(delay))
+ guard !Task.isCancelled else { return }
+ self?.pruneExpired()
+ self?.drain()
+ self?.scheduleExpiry()
+ }
+ }
+}
+
+actor OriginalAudioEmbeddingExtractor {
+ @concurrent static func extract(_ evidence: DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture {
+ try Task.checkCancellation()
+ #if arch(arm64)
+ let version: AsrModelVersion
+ switch evidence.modelKey {
+ case "parakeet-v2": version = .v2
+ case "parakeet-v3": version = .v3
+ default: throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ }
+ let models = try await AsrModels.load(
+ from: AsrModels.defaultCacheDirectory(for: version),
+ version: version
+ )
+ try Task.checkCancellation()
+ let manager = AsrManager(config: ASRConfig(
+ tdtConfig: TdtConfig(blankId: version.blankId),
+ encoderHiddenSize: 1024
+ ))
+ do {
+ try await manager.initialize(models: models)
+ let embedding = try await manager.pronunciationEmbedding(
+ audioSamples: evidence.samples,
+ focalSampleRange: evidence.focalSampleRange
+ )
+ await manager.cleanup()
+ try Task.checkCancellation()
+ return PronunciationEnrollmentCapture(
+ values: embedding.values,
+ sourceFrameCount: embedding.sourceFrameCount,
+ modelKey: evidence.modelKey
+ )
+ } catch {
+ await manager.cleanup()
+ throw error
+ }
+ #else
+ throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ #endif
+ }
+}
diff --git a/Sources/Fluid/Services/DictionaryLearningEvidence.swift b/Sources/Fluid/Services/DictionaryLearningEvidence.swift
new file mode 100644
index 00000000..37014fcd
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryLearningEvidence.swift
@@ -0,0 +1,228 @@
+import Foundation
+
+/// Alignment always describes the original ASR output, before dictionary rules or AI rewriting.
+nonisolated struct DictionaryLearningAlignment: Sendable {
+ let modelKey: String
+ let words: [ASRWordTiming]
+}
+
+/// Short-lived ownership of original PCM, independent from the consume-once history snapshot.
+nonisolated struct DictionaryLearningRecording: Sendable {
+ static let sampleRate = 16_000
+ static let maximumSamples = sampleRate * 60 * 15
+ static let lifetime: TimeInterval = 120
+
+ let id: UUID
+ let expiresAt: Date
+ let alignment: DictionaryLearningAlignment
+ let samples: [Float]
+
+ init?(
+ id: UUID = UUID(),
+ alignment: DictionaryLearningAlignment,
+ samples: [Float],
+ now: Date = Date()
+ ) {
+ guard !samples.isEmpty, samples.count <= Self.maximumSamples,
+ !alignment.words.isEmpty, !alignment.modelKey.isEmpty
+ else { return nil }
+ self.id = id
+ self.expiresAt = now.addingTimeInterval(Self.lifetime)
+ self.alignment = alignment
+ self.samples = samples
+ }
+}
+
+/// Immutable link from an observed text edit to the recording delivered to that field.
+nonisolated struct DictionaryLearningCorrectionContext: Sendable {
+ let recording: DictionaryLearningRecording
+ let deliveredTextBeforeEdit: String
+ let selectedUTF16Range: NSRange
+}
+
+/// The bounded original context and exact focal occurrence used for one pronunciation example.
+nonisolated struct DictionaryLearningAudioEvidence: Sendable {
+ let recordingID: UUID
+ let modelKey: String
+ let observedText: String
+ let sourceWordRange: Range<Int>
+ let sourceSampleRange: Range<Int>
+ let focalSampleRange: Range<Int>
+ let samples: [Float]
+}
+
+nonisolated enum DictionaryLearningAlignmentError: Error, Equatable {
+ case expired
+ case invalidSelection
+ case ambiguousSource
+ case invalidTiming
+}
+
+/// Resolves a selected correction back to the spoken occurrence; never selects a word by spelling alone.
+nonisolated enum DictionaryLearningAlignmentResolver {
+ private struct Token {
+ let text: String
+ let range: NSRange
+ }
+
+ private static let tokenizer = try? NSRegularExpression(pattern: #"[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*"#)
+ private static let contextTokenLimit = 8
+ private static let maximumContextSamples = 238_080
+
+ static func resolve(
+ recording: DictionaryLearningRecording,
+ deliveredTextBeforeEdit: String,
+ selectedUTF16Range: NSRange,
+ observedText: String,
+ now: Date = Date()
+ ) throws -> DictionaryLearningAudioEvidence {
+ guard now < recording.expiresAt else { throw DictionaryLearningAlignmentError.expired }
+ let length = (deliveredTextBeforeEdit as NSString).length
+ guard selectedUTF16Range.location >= 0, selectedUTF16Range.location <= length,
+ selectedUTF16Range.length > 0, selectedUTF16Range.length <= length - selectedUTF16Range.location
+ else { throw DictionaryLearningAlignmentError.invalidSelection }
+ let delivered = self.tokens(in: deliveredTextBeforeEdit)
+ let selected = delivered.indices.filter {
+ NSIntersectionRange(delivered[$0].range, selectedUTF16Range).length > 0
+ }
+ guard let first = selected.first, let last = selected.last,
+ selected.map({ delivered[$0].text }) == self.tokens(in: observedText).map(\.text)
+ else { throw DictionaryLearningAlignmentError.invalidSelection }
+
+ var rawTokens: [String] = []
+ var wordIndices: [Int] = []
+ for (index, word) in recording.alignment.words.enumerated() {
+ let parts = self.tokens(in: word.text)
+ rawTokens.append(contentsOf: parts.map(\.text))
+ wordIndices.append(contentsOf: repeatElement(
+ index,
+ count: parts.count
+ ))
+ }
+ let sourceTokens = try self.sourceRange(
+ raw: rawTokens,
+ delivered: delivered.map(\.text),
+ selected: first..<(last + 1)
+ )
+ let wordRange = wordIndices[sourceTokens.lowerBound]..<(wordIndices[sourceTokens.upperBound - 1] + 1)
+ return try self.makeEvidence(
+ recording: recording,
+ wordRange: wordRange,
+ observedText: observedText
+ )
+ }
+
+ private static func tokens(in text: String) -> [Token] {
+ guard let tokenizer else { return [] }
+ let source = text as NSString
+ return tokenizer.matches(
+ in: text,
+ range: NSRange(
+ location: 0,
+ length: source.length
+ )
+ ).map {
+ Token(
+ text: source.substring(with: $0.range).lowercased(),
+ range: $0.range
+ )
+ }
+ }
+
+ private static func sourceRange(
+ raw: [String],
+ delivered: [String],
+ selected: Range<Int>
+ ) throws -> Range<Int> {
+ // Unchanged lexical content gives an exact ordinal mapping, including repeated words.
+ if raw == delivered { return selected }
+ let target = Array(delivered[selected])
+ guard raw.count >= target.count else { throw DictionaryLearningAlignmentError.ambiguousSource }
+ var best: Range<Int>?
+ var bestScore = 0
+ var tied = false
+ for start in 0...(raw.count - target.count) {
+ let range = start..<(start + target.count)
+ guard raw[range].elementsEqual(target) else { continue }
+ let left = self.contextMatches(
+ raw: raw,
+ delivered: delivered,
+ rawPosition: start - 1,
+ deliveredPosition: selected.lowerBound - 1,
+ direction: -1
+ )
+ let right = self.contextMatches(
+ raw: raw,
+ delivered: delivered,
+ rawPosition: range.upperBound,
+ deliveredPosition: selected.upperBound,
+ direction: 1
+ )
+ // Rewritten output needs matching anchors around the selected phrase. A lone spelling is insufficient.
+ let hasLeftBoundary = selected.lowerBound == 0 && range.lowerBound == 0
+ let hasRightBoundary = selected.upperBound == delivered.count && range.upperBound == raw.count
+ guard left > 0 || hasLeftBoundary, right > 0 || hasRightBoundary, left + right >= 2 else { continue }
+ let score = left + right
+ if score > bestScore {
+ best = range
+ bestScore = score
+ tied = false
+ } else if score == bestScore {
+ tied = true
+ }
+ }
+ guard let best, !tied else { throw DictionaryLearningAlignmentError.ambiguousSource }
+ return best
+ }
+
+ private static func contextMatches(
+ raw: [String],
+ delivered: [String],
+ rawPosition: Int,
+ deliveredPosition: Int,
+ direction: Int
+ ) -> Int {
+ var count = 0
+ var source = rawPosition
+ var destination = deliveredPosition
+ while count < Self.contextTokenLimit, raw.indices.contains(source), delivered.indices.contains(destination),
+ raw[source] == delivered[destination]
+ {
+ count += 1
+ source += direction
+ destination += direction
+ }
+ return count
+ }
+
+ private static func makeEvidence(
+ recording: DictionaryLearningRecording,
+ wordRange: Range<Int>,
+ observedText: String
+ ) throws -> DictionaryLearningAudioEvidence {
+ let words = recording.alignment.words
+ let selected = words[wordRange]
+ let duration = Double(recording.samples.count) / Double(DictionaryLearningRecording.sampleRate)
+ guard selected.allSatisfy({ $0.start.isFinite && $0.end.isFinite && $0.start >= 0 && $0.end > $0.start }),
+ zip(selected, selected.dropFirst()).allSatisfy({ $0.start <= $1.start && $0.end <= $1.end }),
+ let first = selected.first, let last = selected.last,
+ first.start < duration, last.end <= duration + 0.08
+ else { throw DictionaryLearningAlignmentError.invalidTiming }
+ let start = Int((first.start * Double(DictionaryLearningRecording.sampleRate)).rounded(.down))
+ let end = min(recording.samples.count, Int((last.end * Double(DictionaryLearningRecording.sampleRate)).rounded(.up)))
+ guard end > start else { throw DictionaryLearningAlignmentError.invalidTiming }
+ // Keep two seconds before the word, aligned to the existing encoder's 80 ms frames.
+ let contextStart = max(0, start - 2 * DictionaryLearningRecording.sampleRate) / 1280 * 1280
+ let contextEnd = min(recording.samples.count, contextStart + Self.maximumContextSamples)
+ guard end <= contextEnd else { throw DictionaryLearningAlignmentError.invalidTiming }
+ return DictionaryLearningAudioEvidence(
+ recordingID: recording.id,
+ modelKey: recording.alignment.modelKey,
+ observedText: observedText,
+ sourceWordRange: wordRange,
+ sourceSampleRange: contextStart..<contextEnd,
+ focalSampleRange: (start - contextStart)..<(end - contextStart),
+ samples: Array(recording.samples[contextStart..<contextEnd])
+ )
+ }
+}
diff --git a/Sources/Fluid/Services/DictionaryPronunciationDecision.swift b/Sources/Fluid/Services/DictionaryPronunciationDecision.swift
new file mode 100644
index 00000000..26ec8a98
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryPronunciationDecision.swift
@@ -0,0 +1,18 @@
+import Foundation
+
+/// Original corrections provide both text and acoustic evidence for the same intended spelling.
+/// These conservative thresholds are evaluated separately from the legacy three-recording preview.
+enum DictionaryPronunciationDecision {
+ static func accepts(score: Float, heardText: String, profile: PronunciationDictionaryProfile) -> Bool {
+ guard score.isFinite else { return false }
+ let heard = self.normalized(heardText)
+ let knownVariant = profile.enrollments.contains {
+ $0.observedText.map(self.normalized) == heard
+ }
+ return score >= (knownVariant ? 0.70 : 0.85)
+ }
+
+ 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.swift
index 7b4bc982..96eeaea6 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -462,6 +462,21 @@ final class FluidAudioProvider: TranscriptionProvider {
}
}
+ /// Reuse the loaded unboosted encoder; the library API owns and releases only its prepared handles.
+ func originalAudioEnrollment(_ evidence: DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture? {
+ guard self.isReady, evidence.modelKey == self.pronunciationModelKey,
+ let manager = self.streamingAsrManager else { return nil }
+ let embedding = try await manager.pronunciationEmbedding(
+ audioSamples: evidence.samples,
+ focalSampleRange: evidence.focalSampleRange
+ )
+ return PronunciationEnrollmentCapture(
+ values: embedding.values,
+ sourceFrameCount: embedding.sourceFrameCount,
+ modelKey: evidence.modelKey
+ )
+ }
+
func transcribeDictionaryTraining(_ samples: [Float]) async throws -> ASRTranscriptionResult {
guard let manager = self.streamingAsrManager else {
throw NSError(
@@ -623,7 +638,9 @@ final class FluidAudioProvider: TranscriptionProvider {
"finishMs=\(Self.milliseconds(from: appendFinishedAt, to: finishFinishedAt))",
source: "ASRBenchmark"
)
- return ASRTranscriptionResult(text: text, confidence: result.confidence)
+ return ASRTranscriptionResult(
+ text: text, confidence: result.confidence, dictionaryLearningAlignment: self.learningAlignment(for: result)
+ )
}
private static func milliseconds(from start: TimeInterval, to end: TimeInterval) -> String {
@@ -660,7 +677,7 @@ final class FluidAudioProvider: TranscriptionProvider {
guard self.effectivePronunciationMatchingEnabled else { return [] }
let labels = Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries)
let stored = await self.pronunciationStore.profiles(modelKey: self.pronunciationModelKey)
- return stored.filter { $0.enrollments.count >= 3 && labels[$0.dictionaryEntryID] != nil }
+ return stored.filter { $0.isEligibleForMatching && labels[$0.dictionaryEntryID] != nil }
}
private static func pronunciationPrototype(_ profile: PronunciationDictionaryProfile) -> PronunciationEmbedding? {
@@ -720,6 +737,13 @@ final class FluidAudioProvider: TranscriptionProvider {
}
}
+ private func learningAlignment(for result: ASRResult) -> DictionaryLearningAlignment? {
+ guard SettingsStore.shared.automaticDictionaryLearningEnabled, !self.isWordBoostingActive,
+ let timings = result.tokenTimings, !timings.isEmpty
+ else { return nil }
+ return DictionaryLearningAlignment(modelKey: self.pronunciationModelKey, words: Self.makeWordTimings(from: timings))
+ }
+
private func transcribeFinalResult(
_ samples: [Float], manager: AsrManager
) async throws -> (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool) { // swiftlint:disable:this discouraged_optional_collection
@@ -738,7 +762,7 @@ final class FluidAudioProvider: TranscriptionProvider {
modelKey: self.pronunciationModelKey
)
profiles = storedProfiles.compactMap { storedProfile in
- guard storedProfile.enrollments.count >= 3,
+ guard storedProfile.isEligibleForMatching,
let currentLabel = dictionaryLabels[storedProfile.dictionaryEntryID]
else { return nil }
var profile = storedProfile
@@ -756,7 +780,7 @@ final class FluidAudioProvider: TranscriptionProvider {
let features = await manager.consumePronunciationEncoderFeatures()
await manager.setPronunciationCustomizationEnabled(false)
guard let features, !profiles.isEmpty else {
- return (ASRTranscriptionResult(text: result.text, confidence: result.confidence), result.tokenTimings, textMayBeCorrected)
+ return (ASRTranscriptionResult(text: result.text, confidence: result.confidence, dictionaryLearningAlignment: self.learningAlignment(for: result)), result.tokenTimings, textMayBeCorrected)
}
let startedAt = Date().timeIntervalSince1970
let corrected = self.applyPronunciationMatches(result: result, features: features, profiles: profiles)
@@ -765,7 +789,7 @@ final class FluidAudioProvider: TranscriptionProvider {
"PRONUNCIATION_MATCH profiles=\(profiles.count) elapsedMs=\(elapsedMs) changed=\(corrected != result.text)",
source: "PronunciationMatching"
)
- return (ASRTranscriptionResult(text: corrected, confidence: result.confidence), result.tokenTimings, textMayBeCorrected)
+ return (ASRTranscriptionResult(text: corrected, confidence: result.confidence, dictionaryLearningAlignment: self.learningAlignment(for: result)), result.tokenTimings, textMayBeCorrected)
} catch {
_ = await manager.consumePronunciationEncoderFeatures()
await manager.setPronunciationCustomizationEnabled(false)
@@ -835,6 +859,8 @@ final class FluidAudioProvider: TranscriptionProvider {
let words = WordAudioChunkExtractor.words(from: timings)
guard !words.isEmpty else { return result.text }
+ let wordIndex = WordAudioOverlapIndex(words: words)
+
struct Candidate {
let label: String
let score: Float
@@ -849,23 +875,48 @@ final class FluidAudioProvider: TranscriptionProvider {
else { continue }
let startTime = Double(match.frameRange.lowerBound) * 0.08
let endTime = Double(match.frameRange.upperBound) * 0.08
- let indices = WordAudioChunkExtractor.substantiallyOverlappingWordIndices(
- in: words,
+ let indices = wordIndex.substantiallyOverlappingWordIndices(
startTime: startTime,
endTime: endTime
)
guard !indices.isEmpty else { continue }
+ let profile = profiles[match.prototypeIndex]
+ if 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 }
+ }
candidates.append(Candidate(label: label, score: match.score, wordIndices: indices))
}
- var claimed = Set<Int>()
- var accepted: [Candidate] = []
- for candidate in candidates.sorted(by: {
+ var leaders: [Int: [(label: String, score: Float)]] = [:]
+ let sortedCandidates = candidates.sorted {
if $0.score != $1.score { return $0.score > $1.score }
if $0.wordIndices.first != $1.wordIndices.first { return ($0.wordIndices.first ?? 0) < ($1.wordIndices.first ?? 0) }
return $0.label < $1.label
- }) {
+ }
+ // Only the two strongest distinct labels per word are needed for a confidence margin.
+ for candidate in sortedCandidates {
+ let label = candidate.label.lowercased()
+ for index in candidate.wordIndices {
+ var top = leaders[index] ?? []
+ if top.count < 2, !top.contains(where: { $0.label == label }) {
+ top.append((label, candidate.score))
+ leaders[index] = top
+ }
+ }
+ }
+ var claimed = Set<Int>()
+ var accepted: [Candidate] = []
+ for candidate in sortedCandidates {
guard candidate.wordIndices.allSatisfy({ !claimed.contains($0) }) else { continue }
+ let label = candidate.label.lowercased()
+ let ambiguous = candidate.wordIndices.contains { index in
+ (leaders[index] ?? []).contains { $0.label != label && $0.score > candidate.score - 0.05 }
+ }
+ guard !ambiguous else { continue }
accepted.append(candidate)
claimed.formUnion(candidate.wordIndices)
DebugLogger.shared.info(
diff --git a/Sources/Fluid/Services/PronunciationDictionaryStore.swift b/Sources/Fluid/Services/PronunciationDictionaryStore.swift
index 4ba56ffb..8d165921 100644
--- a/Sources/Fluid/Services/PronunciationDictionaryStore.swift
+++ b/Sources/Fluid/Services/PronunciationDictionaryStore.swift
@@ -4,6 +4,11 @@ struct PronunciationEnrollmentCapture: Codable, Equatable, Sendable {
let values: [Float]
let sourceFrameCount: Int
let modelKey: String
+ var originalAudioID: UUID?
+ var observedText: String?
+ var sourceRecordingID: UUID?
+ var sourceFocalRange: Range<Int>?
+ var extractorVersion: String?
}
struct PronunciationDictionaryProfile: Codable, Equatable, Identifiable, Sendable {
@@ -13,14 +18,24 @@ struct PronunciationDictionaryProfile: Codable, Equatable, Identifiable, Sendabl
let hiddenSize: Int
var enrollments: [PronunciationEnrollmentCapture]
+ var hasOriginalAudio: Bool { self.enrollments.contains { $0.originalAudioID != nil } }
+ var isEligibleForMatching: Bool {
+ (self.enrollments.count >= 3 || self.hasOriginalAudio) && self.enrollments.allSatisfy {
+ $0.extractorVersion == nil || $0.extractorVersion == "parakeet-encoder-mean-l2-v1"
+ }
+ }
+
var id: String { "\(self.dictionaryEntryID.uuidString):\(self.modelKey)" }
}
enum PronunciationDictionaryStoreError: LocalizedError, Equatable {
case inconsistentEnrollment
+ case staleEvidence
var errorDescription: String? {
switch self {
+ case .staleEvidence:
+ "The dictionary entry changed before audio learning finished."
case .inconsistentEnrollment:
"Pronunciation samples must use the same model and embedding size."
}
@@ -37,11 +52,19 @@ actor PronunciationDictionaryStore {
private let fileURL: URL
private var document: Document?
+ private var revisions: [UUID: UUID] = [:]
+ private var replacementGeneration = UUID()
init(fileManager: FileManager = .default) {
- let baseURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
+ let baseURL = fileManager.urls(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask
+ ).first
?? fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
- let appURL = baseURL.appendingPathComponent("FluidVoice", isDirectory: true)
+ let appURL = baseURL.appendingPathComponent(
+ "FluidVoice",
+ isDirectory: true
+ )
self.fileURL = appURL.appendingPathComponent("pronunciation-dictionary-v1.json")
}
@@ -59,7 +82,10 @@ actor PronunciationDictionaryStore {
return self.document?.profiles.filter { $0.modelKey == modelKey } ?? []
}
- func enrollmentCount(dictionaryEntryID: UUID, modelKey: String) -> Int {
+ func enrollmentCount(
+ dictionaryEntryID: UUID,
+ modelKey: String
+ ) -> Int {
self.loadIfNeeded()
return self.document?.profiles.first {
$0.dictionaryEntryID == dictionaryEntryID && $0.modelKey == modelKey
@@ -100,7 +126,10 @@ actor PronunciationDictionaryStore {
} else {
profiles.append(profile)
}
- try self.persist(Document(version: 1, profiles: profiles))
+ try self.persist(Document(
+ version: 1,
+ profiles: profiles
+ ))
}
func replaceAllProfiles(_ profiles: [PronunciationDictionaryProfile]) throws {
@@ -113,10 +142,18 @@ actor PronunciationDictionaryStore {
}) else {
throw PronunciationDictionaryStoreError.inconsistentEnrollment
}
- try self.persist(Document(version: 1, profiles: profiles))
+ try self.persist(Document(
+ version: 1,
+ profiles: profiles
+ ))
+ self.replacementGeneration = UUID()
}
- func updateLabel(dictionaryEntryID: UUID, label: String) throws {
+ func updateLabel(
+ dictionaryEntryID: UUID,
+ label: String
+ ) throws {
+ self.revisions[dictionaryEntryID] = UUID()
self.loadIfNeeded()
var profiles = self.document?.profiles ?? []
var changed = false
@@ -125,27 +162,202 @@ actor PronunciationDictionaryStore {
changed = true
}
if changed {
- try self.persist(Document(version: 1, profiles: profiles))
+ try self.persist(Document(
+ version: 1,
+ profiles: profiles
+ ))
}
}
func delete(dictionaryEntryID: UUID) throws {
+ self.revisions[dictionaryEntryID] = UUID()
self.loadIfNeeded()
var profiles = self.document?.profiles ?? []
+ let audioIDs = profiles.filter { $0.dictionaryEntryID == dictionaryEntryID }
+ .flatMap(\.enrollments).compactMap(\.originalAudioID)
profiles.removeAll { $0.dictionaryEntryID == dictionaryEntryID }
- try self.persist(Document(version: 1, profiles: profiles))
+ try self.persist(Document(
+ version: 1,
+ profiles: profiles
+ ))
+ for id in audioIDs {
+ try? FileManager.default.removeItem(at: self.audioURL(id))
+ }
+ }
+
+ struct Revision: Equatable, Sendable {
+ let entry: UUID
+ let generation: UUID
+ }
+
+ func revision(for entryID: UUID) -> Revision {
+ let revision = self.revisions[entryID] ?? UUID()
+ self.revisions[entryID] = revision
+ return Revision(
+ entry: revision,
+ generation: self.replacementGeneration
+ )
+ }
+
+ /// Audio is written first; only the atomic profile write activates it for matching.
+ /// An interrupted write can leave an inactive audio file, never a partial active enrollment.
+ @discardableResult
+ func learnOriginalAudio(
+ entryID: UUID,
+ label: String,
+ evidenceID: UUID,
+ evidence: DictionaryLearningAudioEvidence,
+ capture: PronunciationEnrollmentCapture,
+ expectedRevision: Revision
+ ) throws -> Bool {
+ guard self.revision(for: entryID) == expectedRevision else {
+ throw PronunciationDictionaryStoreError.staleEvidence
+ }
+ self.loadIfNeeded()
+ guard capture.modelKey == evidence.modelKey, !capture.values.isEmpty,
+ capture.values.allSatisfy(\.isFinite), capture.sourceFrameCount > 0,
+ !evidence.samples.isEmpty, evidence.samples.count <= 238_080,
+ evidence.samples.allSatisfy(\.isFinite),
+ evidence.focalSampleRange.lowerBound >= 0,
+ evidence.focalSampleRange.upperBound <= evidence.samples.count,
+ !evidence.focalSampleRange.isEmpty,
+ evidence.sourceSampleRange.lowerBound >= 0,
+ evidence.sourceSampleRange.upperBound <= DictionaryLearningRecording.maximumSamples,
+ evidence.sourceSampleRange.count == evidence.samples.count
+ else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let focalRange = (evidence.sourceSampleRange.lowerBound + evidence.focalSampleRange.lowerBound)..<(evidence.sourceSampleRange.lowerBound + evidence.focalSampleRange.upperBound)
+ for profile in self.document?.profiles ?? [] {
+ if profile.dictionaryEntryID == entryID, profile.label.caseInsensitiveCompare(label) != .orderedSame {
+ throw PronunciationDictionaryStoreError.staleEvidence
+ }
+ for prior in profile.enrollments {
+ let sameOccurrence = prior.sourceRecordingID == evidence.recordingID && prior.sourceFocalRange == focalRange
+ if prior.originalAudioID == evidenceID {
+ guard profile.dictionaryEntryID == entryID, profile.modelKey == capture.modelKey, sameOccurrence else {
+ throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ }
+ return false
+ }
+ if profile.dictionaryEntryID == entryID, profile.modelKey == capture.modelKey, sameOccurrence { return false }
+ }
+ }
+ let record = OriginalAudioRecord(
+ version: 1,
+ sampleRate: 16_000,
+ encoding: "float32-little-endian",
+ entryID: entryID,
+ intendedText: label,
+ evidenceID: evidenceID,
+ recordingID: evidence.recordingID,
+ modelKey: evidence.modelKey,
+ observedText: evidence.observedText,
+ sourceSampleRange: evidence.sourceSampleRange,
+ focalSampleRange: evidence.focalSampleRange,
+ sourceWordRange: evidence.sourceWordRange,
+ pcmFloat32: evidence.samples.withUnsafeBytes { Data($0) }
+ )
+ let url = self.audioURL(evidenceID)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try JSONEncoder().encode(record).write(
+ to: url,
+ options: .atomic
+ )
+ var enrolled = capture
+ enrolled.extractorVersion = "parakeet-encoder-mean-l2-v1"
+ enrolled.originalAudioID = evidenceID
+ enrolled.observedText = evidence.observedText
+ enrolled.sourceRecordingID = evidence.recordingID
+ enrolled.sourceFocalRange = focalRange
+ do {
+ try self.upsert(
+ dictionaryEntryID: entryID,
+ label: label,
+ modelKey: capture.modelKey,
+ enrollments: [enrolled]
+ )
+ } catch {
+ try? FileManager.default.removeItem(at: url)
+ throw error
+ }
+ return true
+ }
+
+ func removeOriginalAudio(evidenceID: UUID) throws {
+ self.loadIfNeeded()
+ var profiles = self.document?.profiles ?? []
+ for index in profiles.indices {
+ profiles[index].enrollments.removeAll { $0.originalAudioID == evidenceID }
+ }
+ profiles.removeAll { $0.enrollments.isEmpty }
+ try self.persist(Document(
+ version: 1,
+ profiles: profiles
+ ))
+ try? FileManager.default.removeItem(at: self.audioURL(evidenceID))
+ }
+
+ private struct OriginalAudioRecord: Codable {
+ let version: Int
+ let sampleRate: Int
+ let encoding: String
+ let entryID: UUID
+ let intendedText: String
+ let evidenceID: UUID
+ let recordingID: UUID
+ let modelKey: String
+ let observedText: String
+ let sourceSampleRange: Range<Int>
+ let focalSampleRange: Range<Int>
+ let sourceWordRange: Range<Int>
+ let pcmFloat32: Data
+ }
+
+ private func audioURL(_ id: UUID) -> URL {
+ self.fileURL.deletingLastPathComponent().appendingPathComponent(
+ "pronunciation-audio",
+ isDirectory: true
+ )
+ .appendingPathComponent(id.uuidString).appendingPathExtension("json")
}
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),
+ let decoded = try? JSONDecoder().decode(
+ Document.self,
+ from: data
+ ),
decoded.version == 1
else {
- self.document = Document(version: 1, profiles: [])
+ self.document = Document(
+ version: 1,
+ profiles: []
+ )
return
}
self.document = decoded
+ self.removeOrphanedAudio()
+ }
+
+ /// A crash before the profile commit leaves an inactive clip; discard it after loading valid metadata.
+ private func removeOrphanedAudio() {
+ let referenced = Set((self.document?.profiles ?? []).flatMap(\.enrollments).compactMap(\.originalAudioID))
+ let directory = self.audioURL(UUID()).deletingLastPathComponent()
+ guard let files = try? FileManager.default.contentsOfDirectory(
+ at: directory,
+ includingPropertiesForKeys: [.contentModificationDateKey]
+ ) else { return }
+ for file in files where file.pathExtension == "json" {
+ guard let id = UUID(uuidString: file.deletingPathExtension().lastPathComponent), !referenced.contains(id) else { continue }
+ // Another app process may be between its audio write and profile commit.
+ guard let values = try? file.resourceValues(forKeys: [.contentModificationDateKey]),
+ let modified = values.contentModificationDate, modified.timeIntervalSinceNow < -60
+ else { continue }
+ try? FileManager.default.removeItem(at: file)
+ }
}
private func persist(_ updated: Document) throws {
@@ -155,7 +367,15 @@ actor PronunciationDictionaryStore {
)
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
- try encoder.encode(updated).write(to: self.fileURL, options: .atomic)
+ try encoder.encode(updated).write(
+ to: self.fileURL,
+ options: .atomic
+ )
+ let oldIDs = Set((self.document?.profiles ?? []).flatMap(\.enrollments).compactMap(\.originalAudioID))
self.document = updated
+ let newIDs = Set(updated.profiles.flatMap(\.enrollments).compactMap(\.originalAudioID))
+ for id in oldIDs.subtracting(newIDs) {
+ try? FileManager.default.removeItem(at: self.audioURL(id))
+ }
}
}
diff --git a/Sources/Fluid/Services/TranscriptionProvider.swift b/Sources/Fluid/Services/TranscriptionProvider.swift
index 78fed611..ac322b12 100644
--- a/Sources/Fluid/Services/TranscriptionProvider.swift
+++ b/Sources/Fluid/Services/TranscriptionProvider.swift
@@ -110,15 +110,18 @@ struct ASRTranscriptionResult {
let text: String
let confidence: Float
let pronunciationEnrollment: PronunciationEnrollmentCapture?
+ let dictionaryLearningAlignment: DictionaryLearningAlignment?
init(
text: String,
confidence: Float = 1.0,
- pronunciationEnrollment: PronunciationEnrollmentCapture? = nil
+ pronunciationEnrollment: PronunciationEnrollmentCapture? = nil,
+ dictionaryLearningAlignment: DictionaryLearningAlignment? = nil
) {
self.text = text
self.confidence = confidence
self.pronunciationEnrollment = pronunciationEnrollment
+ self.dictionaryLearningAlignment = dictionaryLearningAlignment
}
}
@@ -194,8 +197,9 @@ extension TranscriptionProvider {
var supportsWordTimings: Bool { false }
func transcribeWithWordTimings(_ samples: [Float]) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {
- (try await self.transcribe(samples), [])
+ try (await self.transcribe(samples), [])
}
+
func transcribeStreaming(_ samples: [Float]) async throws -> ASRTranscriptionResult {
try await self.transcribe(samples)
}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index e392efab..506d17b2 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -3086,3 +3086,376 @@ final class SimpleUpdaterTests: XCTestCase {
XCTAssertTrue(gate.begin())
}
}
+
+extension DictationE2ETests {
+ func testDictionaryLearningSelectsCorrectRepeatedOccurrence() throws {
+ let text = "open flued voice now then open flued voice now"
+ let words = text.split(separator: " ").enumerated().map { index, token in
+ let start = Double(index < 5 ? index : index + 100)
+ return ASRWordTiming(text: String(token), start: start, end: start + 0.4)
+ }
+ // Sample IDs verify copying/offsets only; this is not a speech recognition fixture.
+ let samples = (0..<(120 * 16_000)).map { Float($0) }
+ let now = Date(timeIntervalSince1970: 1_000)
+ let recording = try XCTUnwrap(DictionaryLearningRecording(
+ alignment: DictionaryLearningAlignment(modelKey: "parakeet-v3", words: words), samples: samples, now: now
+ ))
+ let selection = (text as NSString).range(of: "flued voice", options: .backwards)
+ let evidence = try DictionaryLearningAlignmentResolver.resolve(
+ recording: recording, deliveredTextBeforeEdit: text, selectedUTF16Range: selection,
+ observedText: "flued voice", now: now
+ )
+ XCTAssertEqual(evidence.recordingID, recording.id)
+ XCTAssertEqual(evidence.sourceWordRange, 6..<8)
+ XCTAssertGreaterThan(evidence.sourceSampleRange.lowerBound, 100 * 16_000)
+ XCTAssertLessThanOrEqual(evidence.samples.count, 238_080)
+ XCTAssertEqual(evidence.samples.first, samples[evidence.sourceSampleRange.lowerBound])
+ XCTAssertEqual(evidence.sourceSampleRange.lowerBound + evidence.focalSampleRange.lowerBound, 106 * 16_000)
+ XCTAssertEqual(evidence.sourceSampleRange.lowerBound + evidence.focalSampleRange.upperBound, Int(107.4 * 16_000))
+ }
+
+ func testDictionaryLearningPreservesFormattingAndRejectsAmbiguousRewrite() throws {
+ let now = Date(timeIntervalSince1970: 1_000)
+ func receipt(_ text: String) throws -> DictionaryLearningRecording {
+ let words = text.split(separator: " ").enumerated().map { index, token in
+ ASRWordTiming(text: String(token), start: Double(index), end: Double(index) + 0.5)
+ }
+ return try XCTUnwrap(DictionaryLearningRecording(
+ alignment: DictionaryLearningAlignment(modelKey: "parakeet-v3", words: words),
+ samples: [Float](repeating: 0, count: 16_000 * 15), now: now
+ ))
+ }
+ let formatted = "Open, FLUED VOICE now."
+ let evidence = try DictionaryLearningAlignmentResolver.resolve(
+ recording: receipt("open flued voice now"), deliveredTextBeforeEdit: formatted,
+ selectedUTF16Range: (formatted as NSString).range(of: "FLUED VOICE"), observedText: "FLUED VOICE", now: now
+ )
+ XCTAssertEqual(evidence.sourceWordRange, 1..<3)
+
+ let withoutFiller = "please open flued voice now thanks"
+ let anchored = try DictionaryLearningAlignmentResolver.resolve(
+ recording: receipt("um please open flued voice now thanks"), deliveredTextBeforeEdit: withoutFiller,
+ selectedUTF16Range: (withoutFiller as NSString).range(of: "flued voice"), observedText: "flued voice", now: now
+ )
+ XCTAssertEqual(anchored.sourceWordRange, 3..<5)
+
+ let ambiguous = "please open flued voice now"
+ XCTAssertThrowsError(try DictionaryLearningAlignmentResolver.resolve(
+ recording: receipt("well open flued voice now and open flued voice now"), deliveredTextBeforeEdit: ambiguous,
+ selectedUTF16Range: (ambiguous as NSString).range(of: "flued voice"), observedText: "flued voice", now: now
+ )) { XCTAssertEqual($0 as? DictionaryLearningAlignmentError, .ambiguousSource) }
+ let rewritten = "please launch flued voice today"
+ XCTAssertThrowsError(try DictionaryLearningAlignmentResolver.resolve(
+ recording: receipt("open flued voice now"), deliveredTextBeforeEdit: rewritten,
+ selectedUTF16Range: (rewritten as NSString).range(of: "flued voice"), observedText: "flued voice", now: now
+ )) { XCTAssertEqual($0 as? DictionaryLearningAlignmentError, .ambiguousSource) }
+ }
+
+ func testDictionaryLearningRejectsExpiredAndInvalidEvidence() throws {
+ let now = Date(timeIntervalSince1970: 1_000)
+ let words = [ASRWordTiming(text: "hello", start: 0.1, end: 0.5)]
+ let recording = try XCTUnwrap(DictionaryLearningRecording(
+ alignment: DictionaryLearningAlignment(modelKey: "parakeet-v3", words: words),
+ samples: [Float](repeating: 0, count: 16_000), now: now
+ ))
+ XCTAssertThrowsError(try DictionaryLearningAlignmentResolver.resolve(
+ recording: recording, deliveredTextBeforeEdit: "hello", selectedUTF16Range: NSRange(location: 0, length: 5),
+ observedText: "hello", now: recording.expiresAt
+ )) { XCTAssertEqual($0 as? DictionaryLearningAlignmentError, .expired) }
+ XCTAssertThrowsError(try DictionaryLearningAlignmentResolver.resolve(
+ recording: recording, deliveredTextBeforeEdit: "hello", selectedUTF16Range: NSRange(location: Int.max, length: 5),
+ observedText: "hello", now: now
+ )) { XCTAssertEqual($0 as? DictionaryLearningAlignmentError, .invalidSelection) }
+ let invalid = try XCTUnwrap(DictionaryLearningRecording(
+ alignment: DictionaryLearningAlignment(modelKey: "parakeet-v3", words: [ASRWordTiming(text: "hello", start: .nan, end: 0.5)]),
+ samples: [Float](repeating: 0, count: 16_000), now: now
+ ))
+ XCTAssertThrowsError(try DictionaryLearningAlignmentResolver.resolve(
+ recording: invalid, deliveredTextBeforeEdit: "hello", selectedUTF16Range: NSRange(location: 0, length: 5),
+ observedText: "hello", now: now
+ )) { XCTAssertEqual($0 as? DictionaryLearningAlignmentError, .invalidTiming) }
+ }
+}
+
+extension DictationE2ETests {
+ func testDictionaryLearningDurabilityIdempotencyAndDeletion() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("profiles.json")
+ let store = PronunciationDictionaryStore(fileURL: url)
+ let entryID = UUID()
+ let evidenceID = UUID()
+ let evidence = DictionaryLearningAudioEvidence(
+ recordingID: UUID(), modelKey: "parakeet-v3", observedText: "flued voice",
+ sourceWordRange: 1..<3, sourceSampleRange: 0..<3200, focalSampleRange: 1280..<2560,
+ samples: Array(repeating: 0, count: 3200)
+ )
+ let capture = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 1, modelKey: "parakeet-v3")
+ let revision = await store.revision(for: entryID)
+ var inserted: [Bool] = []
+ for id in [evidenceID, evidenceID, UUID()] {
+ inserted.append(try await store.learnOriginalAudio(entryID: entryID, label: "FluidVoice", evidenceID: id, evidence: evidence, capture: capture, expectedRevision: revision))
+ }
+ XCTAssertEqual(inserted, [true, false, false], "Rollback must know whether this call actually inserted evidence")
+ do {
+ try await store.learnOriginalAudio(entryID: entryID, label: "ChangedMeaning", evidenceID: UUID(), evidence: evidence, capture: capture, expectedRevision: revision)
+ XCTFail("A reused dictionary UUID must not relabel old pronunciation evidence")
+ } catch { XCTAssertEqual(error as? PronunciationDictionaryStoreError, .staleEvidence) }
+ let conflictingEntry = UUID()
+ let conflictingRevision = await store.revision(for: conflictingEntry)
+ do {
+ try await store.learnOriginalAudio(entryID: conflictingEntry, label: "AnotherWord", evidenceID: evidenceID, evidence: evidence, capture: capture, expectedRevision: conflictingRevision)
+ XCTFail("An event UUID cannot overwrite another word's audio")
+ } catch { XCTAssertEqual(error as? PronunciationDictionaryStoreError, .inconsistentEnrollment) }
+ let loaded = await PronunciationDictionaryStore(fileURL: url).allProfiles()
+ XCTAssertEqual(loaded.count, 1)
+ XCTAssertEqual(loaded.first?.enrollments.count, 1, "Retrying one recording occurrence must not create multiple examples")
+ XCTAssertEqual(loaded.first?.enrollments.first?.observedText, "flued voice")
+ XCTAssertEqual(loaded.first?.isEligibleForMatching, true)
+ XCTAssertEqual(loaded.first?.enrollments.first?.values, capture.values)
+ let audioDirectory = directory.appendingPathComponent("pronunciation-audio")
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: audioDirectory.path).count, 1)
+ try await store.delete(dictionaryEntryID: entryID)
+ let deleted = await store.allProfiles()
+ XCTAssertTrue(deleted.isEmpty)
+ XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: audioDirectory.path).isEmpty)
+ do {
+ try await store.learnOriginalAudio(entryID: entryID, label: "FluidVoice", evidenceID: UUID(), evidence: evidence, capture: capture, expectedRevision: revision)
+ XCTFail("Late extraction must not resurrect a deleted entry")
+ } catch {
+ XCTAssertEqual(error as? PronunciationDictionaryStoreError, .staleEvidence)
+ }
+ }
+
+ func testDictionaryLearningRejectsInvalidCaptureWithoutPartialProfile() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let id = UUID()
+ let revision = await store.revision(for: id)
+ let evidence = DictionaryLearningAudioEvidence(recordingID: UUID(), modelKey: "parakeet-v3", observedText: "test", sourceWordRange: 0..<1, sourceSampleRange: 0..<1, focalSampleRange: 0..<1, samples: [0])
+ do {
+ try await store.learnOriginalAudio(entryID: id, label: "Test", evidenceID: UUID(), evidence: evidence, capture: PronunciationEnrollmentCapture(values: [.nan], sourceFrameCount: 1, modelKey: "parakeet-v3"), expectedRevision: revision)
+ XCTFail("Non-finite embeddings must never be activated")
+ } catch {
+ XCTAssertEqual(error as? PronunciationDictionaryStoreError, .inconsistentEnrollment)
+ }
+ let profiles = await store.allProfiles()
+ XCTAssertTrue(profiles.isEmpty)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: directory.path))
+ try await store.replaceAllProfiles([])
+ do {
+ try await store.learnOriginalAudio(entryID: id, label: "Test", evidenceID: UUID(), evidence: evidence, capture: PronunciationEnrollmentCapture(values: [1], sourceFrameCount: 1, modelKey: "parakeet-v3"), expectedRevision: revision)
+ XCTFail("Import must invalidate pending original-audio learning")
+ } catch { XCTAssertEqual(error as? PronunciationDictionaryStoreError, .staleEvidence) }
+ }
+
+ #if arch(arm64)
+ func testDictionaryLearningCombinedDecisionAndConflictingLabels() {
+ let id = UUID()
+ let otherID = UUID()
+ let sample = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 5, modelKey: "parakeet-v3", originalAudioID: UUID(), observedText: "fluid boys")
+ let profile = PronunciationDictionaryProfile(dictionaryEntryID: id, label: "FluidVoice", modelKey: "parakeet-v3", hiddenSize: 2, enrollments: [sample])
+ XCTAssertTrue(DictionaryPronunciationDecision.accepts(score: 0.75, heardText: "Fluid boys!", profile: profile))
+ XCTAssertFalse(DictionaryPronunciationDecision.accepts(score: 0.69, heardText: "fluid boys", profile: profile))
+ XCTAssertFalse(DictionaryPronunciationDecision.accepts(score: 0.75, heardText: "other speech", profile: profile))
+ XCTAssertTrue(DictionaryPronunciationDecision.accepts(score: 0.9, heardText: "fluid voice", profile: profile))
+ XCTAssertFalse(DictionaryPronunciationDecision.accepts(score: .nan, heardText: "fluid boys", profile: profile))
+ let result = ASRResult(text: "fluid voice", confidence: 1, duration: 1, processingTime: 0, tokenTimings: [
+ TokenTiming(token: "▁fluid", tokenId: 1, startTime: 0, endTime: 0.24, confidence: 1),
+ TokenTiming(token: "▁voice", tokenId: 2, startTime: 0.24, endTime: 0.48, confidence: 1),
+ ])
+ let match = PronunciationWindowMatch(prototypeIndex: 0, score: 0.9, frameRange: 0..<6)
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [match], profiles: [profile], labels: [id: "FluidVoice"]), "FluidVoice")
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [match], profiles: [profile], labels: [id: "ChangedMeaning"]), result.text)
+ var incompatible = profile
+ incompatible.enrollments[0].extractorVersion = "another-vector-space"
+ XCTAssertFalse(incompatible.isEligibleForMatching)
+ let other = PronunciationDictionaryProfile(dictionaryEntryID: otherID, label: "Other", modelKey: "parakeet-v3", hiddenSize: 2, enrollments: [sample])
+ let competitor = PronunciationWindowMatch(prototypeIndex: 1, score: 0.88, frameRange: 0..<6)
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [match, competitor], profiles: [profile, other], labels: [id: "FluidVoice", otherID: "Other"]), result.text)
+ }
+ #endif
+}
+
+private actor DictionaryLearningTestExtractor {
+ var calls = 0
+ let started: XCTestExpectation
+ let cancelled: XCTestExpectation
+ init(started: XCTestExpectation, cancelled: XCTestExpectation) {
+ self.started = started
+ self.cancelled = cancelled
+ }
+ func extract(_ evidence: DictionaryLearningAudioEvidence) async throws -> PronunciationEnrollmentCapture {
+ self.calls += 1
+ if self.calls == 1 {
+ self.started.fulfill()
+ do { try await Task.sleep(for: .seconds(30)) }
+ catch { self.cancelled.fulfill(); throw error }
+ }
+ return PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 1, modelKey: evidence.modelKey)
+ }
+}
+
+extension DictationE2ETests {
+ func testDictionaryLearningDefersToDictationAndRetriesOnce() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["flued"], replacement: "Fluid")
+ let evidence = DictionaryLearningAudioEvidence(recordingID: UUID(), modelKey: "parakeet-v3", observedText: "flued", sourceWordRange: 0..<1, sourceSampleRange: 0..<1280, focalSampleRange: 0..<1280, samples: Array(repeating: 0, count: 1280))
+ let started = self.expectation(description: "Background extraction started")
+ let cancelled = self.expectation(description: "Dictation cancelled background work")
+ let extractor = DictionaryLearningTestExtractor(started: started, cancelled: cancelled)
+ var idle = true
+ let service = DictionaryAudioLearningService(store: store, extract: { try await extractor.extract($0) }, canProcess: { idle }, isCurrent: { $0 == entry })
+ let eventID = UUID()
+ service.learn(entry: entry, evidenceID: eventID, evidence: evidence)
+ service.learn(entry: entry, evidenceID: eventID, evidence: evidence)
+ await self.fulfillment(of: [started], timeout: 2)
+ XCTAssertEqual(service.pendingCount, 1)
+ idle = false
+ service.cancelForRecording()
+ await self.fulfillment(of: [cancelled], timeout: 2)
+ let duringDictation = await store.allProfiles()
+ XCTAssertTrue(duringDictation.isEmpty)
+ idle = true
+ service.activityDidEnd()
+ for _ in 0..<200 where service.pendingCount > 0 { try await Task.sleep(for: .milliseconds(10)) }
+ XCTAssertEqual(service.pendingCount, 0)
+ let profiles = await store.allProfiles()
+ XCTAssertEqual(profiles.first?.enrollments.count, 1)
+ let calls = await extractor.calls
+ XCTAssertEqual(calls, 2)
+ }
+
+ func testDictionaryLearningQueueIsBoundedAndExpiresWithoutSaving() async throws {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["flued"], replacement: "Fluid")
+ let evidence = DictionaryLearningAudioEvidence(recordingID: UUID(), modelKey: "parakeet-v3", observedText: "flued", sourceWordRange: 0..<1, sourceSampleRange: 0..<1, focalSampleRange: 0..<1, samples: [0])
+ let service = DictionaryAudioLearningService(store: store, lifetime: 0.05, extract: { _ in
+ XCTFail("Busy dictation must not run the background encoder")
+ throw CancellationError()
+ }, canProcess: { false }, isCurrent: { _ in true })
+ for _ in 0..<6 { service.learn(entry: entry, evidenceID: UUID(), evidence: evidence) }
+ XCTAssertEqual(service.pendingCount, 4)
+ try await Task.sleep(for: .milliseconds(100))
+ XCTAssertEqual(service.pendingCount, 0)
+ let profiles = await store.allProfiles()
+ XCTAssertTrue(profiles.isEmpty)
+ }
+}
+
+extension DictationE2ETests {
+ #if arch(arm64)
+ func testDictionaryLearningRealAudioRoundTrip() 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 real-speech fixture and local Parakeet model path") }
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let samples = Array(try AudioConverter().resampleAudioFile(path: path).prefix(160_000))
+ 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 result = try await manager.transcribe(samples, source: .microphone)
+ let words = WordAudioChunkExtractor.words(from: result.tokenTimings ?? [])
+ let selected = try XCTUnwrap(words.first { $0.startTime < 2 && $0.endTime - $0.startTime >= 0.24 && $0.text.count >= 5 })
+ let alignment = DictionaryLearningAlignment(modelKey: "parakeet-v3", words: words.map { ASRWordTiming(text: $0.text, start: $0.startTime, end: $0.endTime) })
+ let recording = try XCTUnwrap(DictionaryLearningRecording(alignment: alignment, samples: samples))
+ let delivered = words.map(\.text).joined(separator: " ")
+ let evidence = try DictionaryLearningAlignmentResolver.resolve(recording: recording, deliveredTextBeforeEdit: delivered, selectedUTF16Range: (delivered as NSString).range(of: selected.text), observedText: selected.text)
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: [selected.text], replacement: "LearnedTarget")
+ let store = PronunciationDictionaryStore(fileURL: directory.appendingPathComponent("profiles.json"))
+ let service = DictionaryAudioLearningService(store: store, canProcess: { true }, isCurrent: { $0 == entry })
+ let started = ProcessInfo.processInfo.systemUptime
+ service.learn(entry: entry, evidenceID: UUID(), evidence: evidence)
+ for _ in 0..<1000 where service.pendingCount > 0 { try await Task.sleep(for: .milliseconds(10)) }
+ XCTAssertEqual(service.pendingCount, 0)
+ let backgroundWallMs = (ProcessInfo.processInfo.systemUptime-started)*1000
+ let profiles = await store.allProfiles()
+ let profile = try XCTUnwrap(profiles.first)
+ let capture = try XCTUnwrap(profile.enrollments.first)
+ XCTAssertEqual(capture.observedText, selected.text)
+ XCTAssertEqual(capture.sourceRecordingID, recording.id)
+ XCTAssertEqual(profile.enrollments.count, 1)
+ await manager.setPronunciationCustomizationEnabled(true)
+ let replay = try await manager.transcribe(evidence.samples, source: .microphone)
+ let captured = await manager.consumePronunciationEncoderFeatures()
+ let features = try XCTUnwrap(captured)
+ let prototype = PronunciationEmbedding(values: capture.values, sourceFrameCount: capture.sourceFrameCount)
+ let matches = PronunciationEmbeddingMatcher.allMatches(prototypes: [prototype], in: features)[0].map {
+ PronunciationWindowMatch(prototypeIndex: 0, score: $0.score, frameRange: $0.frameRange)
+ }
+ let output = FluidAudioProvider.applyPronunciationMatches(result: replay, matches: matches, profiles: profiles, labels: [entry.id: entry.replacement])
+ XCTAssertTrue(output.contains("LearnedTarget"), "The saved original example must be usable by the production matcher")
+ let provider = FluidAudioProvider(
+ modelOverride: .parakeetTDT, configureWordBoosting: false,
+ enhancementOptions: FluidAudioProviderEnhancementOptions(experimentalUnifiedFinalEnabled: false, pronunciationMatchingEnabled: false, customDictionaryEntries: []),
+ pronunciationStore: store
+ )
+ try await provider.prepare()
+ let reuseStart = ProcessInfo.processInfo.systemUptime
+ let reused = try await provider.originalAudioEnrollment(evidence)
+ XCTAssertEqual(reused?.values, capture.values, "Warm encoder reuse must preserve the exact embedding")
+ print("ORIGINAL_AUDIO_ENCODER_REUSE ms=\((ProcessInfo.processInfo.systemUptime-reuseStart)*1000)")
+ let afterReuse = try await provider.transcribeFinal(evidence.samples)
+ XCTAssertEqual(afterReuse.text, replay.text, "Background enrollment must not change later transcription")
+ print("ORIGINAL_AUDIO_ROUNDTRIP backgroundWallMs=\(backgroundWallMs) samples=\(evidence.samples.count)")
+ await manager.cleanup()
+ }
+ #endif
+}
+
+extension DictationE2ETests {
+ #if arch(arm64)
+ func testDictionaryLearningComplementaryRecoveryWithControlledASRErrors() {
+ let id = UUID()
+ let capture = PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: "parakeet-v3", originalAudioID: UUID(), observedText: "fluid boys")
+ let profile = PronunciationDictionaryProfile(dictionaryEntryID: id, label: "FluidVoice", modelKey: "parakeet-v3", hiddenSize: 2, enrollments: [capture])
+ defer { ASRService.invalidateDictionaryCache() }
+ self.withRestoredDefaults(keys: [self.customDictionaryEntriesKey]) {
+ SettingsStore.shared.customDictionaryEntries = [.init(id: id, triggers: ["fluid boys"], replacement: "FluidVoice")]
+ ASRService.invalidateDictionaryCache()
+ // Explicit fault injection checks fallback wiring, not real-speech accuracy.
+ for (text, score, expected) in [("fluid boys", Float(0.2), "FluidVoice"), ("fluent voice", Float(0.95), "FluidVoice"), ("other words", Float(0.3), "other words")] {
+ let parts = text.split(separator: " ")
+ let result = ASRResult(text: text, confidence: 1, duration: 1, processingTime: 0, tokenTimings: [
+ TokenTiming(token: "▁" + parts[0], tokenId: 1, startTime: 0, endTime: 0.24, confidence: 1),
+ TokenTiming(token: "▁" + parts[1], tokenId: 2, startTime: 0.24, endTime: 0.48, confidence: 1),
+ ])
+ let acoustic = FluidAudioProvider.applyPronunciationMatches(result: result, matches: [PronunciationWindowMatch(prototypeIndex: 0, score: score, frameRange: 0..<6)], profiles: [profile], labels: [id: "FluidVoice"])
+ XCTAssertEqual(ASRService.applyCustomDictionary(acoustic), expected)
+ if text == "fluid boys" { XCTAssertEqual(acoustic, text, "Text fallback must recover an acoustic miss") }
+ if text == "fluent voice" { XCTAssertEqual(ASRService.applyCustomDictionary(text), text, "Audio must recover a text-rule miss") }
+ }
+ }
+ }
+
+ func testDictionaryLearningReconciliationCostAtScale() {
+ let wordCount = 1200
+ let result = ASRResult(text: Array(repeating: "spoken", count: wordCount).joined(separator: " "), confidence: 1, duration: 600, processingTime: 0, tokenTimings: (0..<wordCount).map { index in
+ TokenTiming(token: "▁spoken", tokenId: 1, startTime: Double(index)*0.48, endTime: Double(index+1)*0.48, confidence: 1)
+ })
+ for count in [1, 10, 1000] {
+ let profiles = (0..<count).map { index in
+ PronunciationDictionaryProfile(dictionaryEntryID: UUID(), label: "Target\(index)", modelKey: "parakeet-v3", hiddenSize: 2, enrollments: [PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 6, modelKey: "parakeet-v3", originalAudioID: UUID(), observedText: "spoken")])
+ }
+ let labels = Dictionary(uniqueKeysWithValues: profiles.map { ($0.dictionaryEntryID, $0.label) })
+ let matches = (0..<count).map { PronunciationWindowMatch(prototypeIndex: $0, score: 0.95, frameRange: ($0*6)..<(($0+1)*6)) }
+ var durations: [Double] = []
+ for run in 0..<6 {
+ let start = ProcessInfo.processInfo.systemUptime
+ let output = FluidAudioProvider.applyPronunciationMatches(result: result, matches: matches, profiles: profiles, labels: labels)
+ let elapsed = (ProcessInfo.processInfo.systemUptime-start)*1000
+ XCTAssertTrue(output.contains("Target0"))
+ if run > 0 { durations.append(elapsed) }
+ }
+ print("LEARNING_RECONCILIATION profiles=\(count) audioSeconds=600 meanMs=\(durations.reduce(0,+)/Double(durations.count)) maxMs=\(durations.max()!)")
+ }
+ }
+ #endif
+}
diff --git a/docs/design/dictionary-learning-api.md b/docs/design/dictionary-learning-api.md
index 7b2fef1a..d8321c5f 100644
--- a/docs/design/dictionary-learning-api.md
+++ b/docs/design/dictionary-learning-api.md
@@ -1,6 +1,6 @@
# Reusable dictionary learning API
-Status: proposed contract and implementation plan, not shipped automatic learning. Reviewed against the local FluidVoice long-recording implementation and companion FluidAudio pronunciation-streaming worktree on 2026-09-19. UI entry points and automatic-add policy can be implemented independently after this contract.
+Status: broader proposed contract. The September 20 backend implementation and measured limits are documented in [original-audio-learning-implementation.md](original-audio-learning-implementation.md). The descriptions below record the September 19 baseline and future design, not the current implementation status. Reviewed against the local FluidVoice long-recording implementation and companion FluidAudio pronunciation-streaming worktree on 2026-09-19. UI entry points and automatic-add policy can be implemented independently after this contract.
## Outcome
diff --git a/docs/design/original-audio-learning-implementation.md b/docs/design/original-audio-learning-implementation.md
new file mode 100644
index 00000000..68ddbd59
--- /dev/null
+++ b/docs/design/original-audio-learning-implementation.md
@@ -0,0 +1,36 @@
+# Original-audio correction learning
+
+Implementation work, September 20, 2026. The existing correction UI now schedules original-audio learning after an approved Add Only or trained-replacement save. The broader API proposal in `dictionary-learning-api.md` remains a future contract, not a claim that every proposed migration or UI adapter is implemented.
+
+## Implemented path
+
+1. Parakeet returns original word timings separately from rewritten output. Normal dictation retains an immutable PCM receipt only when correction learning is enabled. History audio ownership is independent. Boosted output cannot supply trustworthy provenance and falls back to text-only learning.
+2. External delivery gives the correction tracker that exact receipt. The selected UTF-16 edit maps to its original occurrence; unchanged lexical content maps by ordinal, while edited text requires unique surrounding anchors. Ambiguous rewrites, invalid timing and expired evidence are rejected.
+3. The tracker crops up to 14.88 seconds of original context on a utility task before presenting the existing popup. It never searches for a same-spelled occurrence elsewhere after alignment fails.
+4. The existing approval saves the text rule immediately. `DictionaryAudioLearningService.learn(entry:evidenceID:evidence:)` schedules optional encoder-only extraction, reusing the loaded matching Parakeet encoder when available and loading the recorded model only as a fallback. This API accepts immutable evidence, not UI views or microphone controls.
+5. The bounded worker cancels when an exclusive audio activity starts and retries after it ends. Four pending clips, a 120-second deadline and one active extraction bound memory and work. Unsupported, expired, failed or over-budget work leaves the approved text correction intact. Logs never contain dictated text or audio.
+6. `PronunciationDictionaryStore.learnOriginalAudio` writes local PCM metadata before atomically activating its embedding in the profile index. It links entry/event/recording IDs, original occurrence, observed text, model and extractor version. Repeated event IDs and repeated source occurrences do not count as additional examples. A retry reports whether it inserted anything, so cancellation cannot retract an older successful event.
+7. Entry snapshots and store revisions reject stale completion. Deletion removes associated audio. Retraction removes only the corresponding example. Valid-index startup cleanup removes aged unreferenced audio left by interrupted writes. Raw clips are excluded from ordinary dictionary exports; profile backups preserve embeddings and provenance, not clip files.
+8. One original approved occurrence is eligible through the same policy used by both short and incremental dictation. Existing manual enrollment still requires three examples. No sample is copied to satisfy that count.
+
+The temporary receipt accepts recordings up to 15 minutes and expires after 120 seconds. This is a memory bound, not the model's 15-second input limit. Longer recordings currently retain text-only correction learning. Stored context clips are Float32 little-endian, 16 kHz mono. At most ten examples per profile are retained; there is no global disk quota yet.
+
+## Combining evidence
+
+Known observed variants retain their approved text fallback. Acoustic matches for original-audio profiles require cosine score 0.70 when the recognized phrase matches a known variant, or 0.85 for a new variant. These are conservative experimental thresholds, not probabilities or universally calibrated guarantees. A near tie between different intended labels within 0.05 is rejected. The two strongest labels per word are indexed so conflict checks do not compare every candidate with every other candidate. Changed intended meanings cannot reuse original-audio evidence by merely retaining the entry UUID.
+
+An initial experiment required acoustic confirmation before applying a learned text alias. Real-speech tests showed a substantial recall regression, so that design was removed. A weak acoustic score does not establish that a familiar text correction is wrong. The current combination allows either mechanism to recover a miss by the other. Global text-alias ambiguity is not solved by this change.
+
+## Evidence and limits
+
+- 62 affected app tests passed together, including the real two-minute streaming regression, real-audio save/reuse, repeated-occurrence alignment, cancellation/retry, expiry, invalid evidence, deletion, imports and conflicting matches. All eleven learning tests passed again after review, followed by focused retry/encoder-reuse and stale-meaning checks.
+- Encoder-only extraction reproduces the normal encoder's embedding exactly on the same real audio context and releases prepared handles after success/cancellation. Two XCTest cases plus eleven matcher/index tests passed.
+- Controlled ASR-error injection verifies that text recovers an acoustic miss, audio recovers an unseen text variant, and unrelated speech stays unchanged. This is wiring regression evidence, not a speech-accuracy benchmark.
+- Real FLEURS evaluation: 27 available clips, eight languages, 536 timed words. Eleven repeated targets produced 26 cross-clip trials; five longer clips were excluded. Reference-to-ASR word alignment supplies evaluation labels. Full search, using a separate context re-encode for enrollment, scored text-only 19 true/2 false substitutions, acoustic-only at 0.70 scored 3 true/1 false, and the current combination scored 19 true/2 false. There were 21 target and 547 non-target word opportunities. The combined method preserved text recall but did not beat it on this small set.
+- Most repeated targets in that set are common words, not personalized names. Speakers were not constrained to match enrollment. It cannot establish same-user accent robustness or general custom-name accuracy. More realistic held-out corrections are still required before claiming superiority or tuning the novel-variant threshold.
+- Isolated reconciliation on a ten-minute/1,200-token fixture averaged 1.42 ms for one profile, 1.46 ms for ten, and 6.50 ms for 1,000. It measures cached matches to text, not ASR/search or whole Stop latency. The real original-audio background round trip took about 120 ms, including model loading/persistence and up to 10 ms polling granularity; it is outside the delivery path. Reusing the already-loaded encoder measured 40.7 ms for the same ten-second context, returned identical vectors, and preserved the next transcription.
+- Earlier paired ten-minute streaming benchmark remains 46.109 ms off versus 62.467 ms on with 1,000 profiles, a 16.358 ms mean difference. The new end-to-end live-microphone overhead has not been remeasured. See `scratch/pronunciation-stage-profile/ON_OFF_STOP_OVERHEAD.md`.
+
+Evaluation scripts and raw outputs: `scratch/original-audio-learning/evaluation/`. They are local research artifacts, not production app assets. There is no guarantee of perfect accuracy, no new UI, no model-weight training, no enabling of vocabulary boosting, and no migration of every legacy voice-training adapter in this patch.
+
+Validation status: scoped service lint is clean. Full-source format and strict lint ran; restoring unrelated formatting left 623 pre-existing lint findings, with none on the changed tracked code lines. The signed private FI build is the local packaging check; it is not a production bridge/release gate.