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): reuse pronunciation matches across long dictations

altic-dev769c8a58c6e6
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 55aa73bb..53304f05 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 = cfabbc6cd7c603ad469cbbb5a30c1ece48db04be;
+ revision = 97ed23265098a78a09378659063d52dee908f9e0;
};
};
7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */ = {
diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 369b6f96..1df3e653 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" : "cfabbc6cd7c603ad469cbbb5a30c1ece48db04be"
+ "revision" : "97ed23265098a78a09378659063d52dee908f9e0"
}
},
{
diff --git a/Package.swift b/Package.swift
index 98713feb..14ab7e6f 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: "cfabbc6cd7c603ad469cbbb5a30c1ece48db04be"),
+ .package(url: "https://github.com/altic-dev/FluidAudio.git", revision: "97ed23265098a78a09378659063d52dee908f9e0"),
.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/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index f51e4772..7b4bc982 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -100,6 +100,13 @@ final class FluidAudioProvider: TranscriptionProvider {
private var latestStreamingPreviewFinishedAt: TimeInterval?
private var incrementalSession: ParakeetIncrementalSession?
private var incrementalAcceptedSampleCount = 0
+ private var recordingGeneration = UUID()
+ private var incrementalPronunciationProfiles: [PronunciationDictionaryProfile] = []
+
+ private var usesIncrementalDictation: Bool {
+ self.effectiveExperimentalUnifiedFinalEnabled || self.effectivePronunciationMatchingEnabled
+ }
+
private(set) var isReady: Bool = false
private(set) var isWordBoostingActive: Bool = false
private(set) var boostedVocabularyTermsCount: Int = 0
@@ -116,16 +123,19 @@ final class FluidAudioProvider: TranscriptionProvider {
/// Explicitly pinned enhancement options for offline/baseline runs. Precedence for each
/// effective getter: fixed meeting policy, then this, then live `SettingsStore`.
private let enhancementOptions: FluidAudioProviderEnhancementOptions?
+ private let pronunciationStore: PronunciationDictionaryStore
init(
modelOverride: SettingsStore.SpeechModel? = nil,
configureWordBoosting: Bool = true,
- enhancementOptions: FluidAudioProviderEnhancementOptions? = nil
+ enhancementOptions: FluidAudioProviderEnhancementOptions? = nil,
+ pronunciationStore: PronunciationDictionaryStore = .shared
) {
self.modelOverride = modelOverride
self.configureWordBoosting = configureWordBoosting
self.meetingOptions = nil
self.enhancementOptions = enhancementOptions
+ self.pronunciationStore = pronunciationStore
}
/// Opt-in meeting post-processing provider. The model is pinned immutably and every
@@ -138,6 +148,7 @@ final class FluidAudioProvider: TranscriptionProvider {
self.configureWordBoosting = false
self.meetingOptions = options
self.enhancementOptions = nil
+ self.pronunciationStore = .shared
}
private var effectiveExperimentalUnifiedFinalEnabled: Bool {
@@ -294,8 +305,8 @@ final class FluidAudioProvider: TranscriptionProvider {
self.latestStreamingPreviewText = ""
self.latestStreamingPreviewSampleCount = 0
self.latestStreamingPreviewFinishedAt = nil
- self.incrementalSession = nil
- self.incrementalAcceptedSampleCount = 0
+ self.recordingGeneration = UUID()
+ self.resetIncrementalSession()
try Task.checkCancellation()
self.isReady = true
@@ -314,8 +325,8 @@ final class FluidAudioProvider: TranscriptionProvider {
self.latestStreamingPreviewText = ""
self.latestStreamingPreviewSampleCount = 0
self.latestStreamingPreviewFinishedAt = nil
- self.incrementalSession = nil
- self.incrementalAcceptedSampleCount = 0
+ self.recordingGeneration = UUID()
+ self.resetIncrementalSession()
}
func transcribeStreaming(_ samples: [Float]) async throws -> ASRTranscriptionResult {
@@ -327,9 +338,10 @@ final class FluidAudioProvider: TranscriptionProvider {
)
}
+ let generation = self.recordingGeneration
let startedAt = Date().timeIntervalSince1970
let result: ASRResult
- if self.effectiveExperimentalUnifiedFinalEnabled,
+ if self.usesIncrementalDictation,
samples.count > Self.incrementalChunkingThresholdSamples,
let incrementalManager = self.finalAsrManager ?? self.streamingAsrManager
{
@@ -339,7 +351,8 @@ final class FluidAudioProvider: TranscriptionProvider {
manager: incrementalManager
)
} catch {
- self.resetIncrementalSession()
+ if self.recordingGeneration == generation { self.resetIncrementalSession() }
+ try self.requireCurrentRecording(generation)
if Task.isCancelled || error is CancellationError {
throw CancellationError()
}
@@ -350,13 +363,14 @@ final class FluidAudioProvider: TranscriptionProvider {
result = try await fullPreviewManager.transcribe(samples, source: AudioSource.microphone)
}
} else {
- if !self.effectiveExperimentalUnifiedFinalEnabled
+ if !self.usesIncrementalDictation
|| samples.count < self.incrementalAcceptedSampleCount
{
self.resetIncrementalSession()
}
result = try await fullPreviewManager.transcribe(samples, source: AudioSource.microphone)
}
+ try self.requireCurrentRecording(generation)
let text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
self.latestStreamingPreviewText = text
self.latestStreamingPreviewSampleCount = samples.count
@@ -380,7 +394,7 @@ final class FluidAudioProvider: TranscriptionProvider {
/// growing recording on every live-preview tick.
func incrementalPreviewDeltaStart(totalSampleCount: Int) -> Int? {
Self.incrementalPreviewDeltaRange(
- enabled: self.effectiveExperimentalUnifiedFinalEnabled,
+ enabled: self.usesIncrementalDictation,
hasSession: self.incrementalSession != nil,
acceptedSampleCount: self.incrementalAcceptedSampleCount,
totalSampleCount: totalSampleCount
@@ -408,6 +422,7 @@ final class FluidAudioProvider: TranscriptionProvider {
_ newSamples: [Float],
totalSampleCount: Int
) async throws -> ASRTranscriptionResult {
+ let generation = self.recordingGeneration
guard let session = self.incrementalSession,
self.incrementalAcceptedSampleCount + newSamples.count == totalSampleCount
else {
@@ -422,8 +437,10 @@ final class FluidAudioProvider: TranscriptionProvider {
let startedAt = Date().timeIntervalSince1970
do {
try await session.append(newSamples)
+ try self.requireCurrentRecording(generation)
self.incrementalAcceptedSampleCount = totalSampleCount
let result = try await session.preview()
+ try self.requireCurrentRecording(generation)
let text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
self.latestStreamingPreviewText = text
self.latestStreamingPreviewSampleCount = totalSampleCount
@@ -436,7 +453,8 @@ final class FluidAudioProvider: TranscriptionProvider {
)
return ASRTranscriptionResult(text: result.text, confidence: result.confidence)
} catch {
- self.resetIncrementalSession()
+ if self.recordingGeneration == generation { self.resetIncrementalSession() }
+ try self.requireCurrentRecording(generation)
if Task.isCancelled || error is CancellationError {
throw CancellationError()
}
@@ -473,9 +491,10 @@ final class FluidAudioProvider: TranscriptionProvider {
}
func transcribeFinal(_ samples: [Float]) async throws -> ASRTranscriptionResult {
+ let generation = self.recordingGeneration
defer {
let resetStartedAt = ProcessInfo.processInfo.systemUptime
- self.resetIncrementalSession()
+ if self.recordingGeneration == generation { self.resetIncrementalSession() }
let resetFinishedAt = ProcessInfo.processInfo.systemUptime
DebugLogger.shared.debug(
"ASR_BENCH t=\(resetFinishedAt) incremental_reset_done elapsedMs=\((resetFinishedAt - resetStartedAt) * 1000)",
@@ -490,13 +509,14 @@ final class FluidAudioProvider: TranscriptionProvider {
)
}
- if self.effectiveExperimentalUnifiedFinalEnabled,
+ if self.usesIncrementalDictation,
samples.count > Self.incrementalChunkingThresholdSamples,
self.incrementalSession != nil
{
do {
let startedAt = Date().timeIntervalSince1970
let result = try await self.transcribeIncrementalFinal(samples)
+ try self.requireCurrentRecording(generation)
self.logFinalBenchmark(
samples: samples,
text: result.text,
@@ -506,6 +526,7 @@ final class FluidAudioProvider: TranscriptionProvider {
)
return result
} catch {
+ try self.requireCurrentRecording(generation)
if Task.isCancelled || error is CancellationError {
throw CancellationError()
}
@@ -521,9 +542,11 @@ final class FluidAudioProvider: TranscriptionProvider {
do {
let startedAt = Date().timeIntervalSince1970
let outcome = try await self.transcribeFinalResult(samples, manager: manager)
+ try self.requireCurrentRecording(generation)
self.logFinalBenchmark(samples: samples, text: outcome.result.text, startedAt: startedAt, usedFallback: false)
return outcome.result
} catch {
+ try self.requireCurrentRecording(generation)
guard let fallback = self.streamingAsrManager, fallback !== manager else {
throw error
}
@@ -533,6 +556,7 @@ final class FluidAudioProvider: TranscriptionProvider {
)
let startedAt = Date().timeIntervalSince1970
let outcome = try await self.transcribeFinalResult(samples, manager: fallback)
+ try self.requireCurrentRecording(generation)
self.logFinalBenchmark(samples: samples, text: outcome.result.text, startedAt: startedAt, usedFallback: true)
return outcome.result
}
@@ -546,7 +570,7 @@ final class FluidAudioProvider: TranscriptionProvider {
self.resetIncrementalSession()
}
if self.incrementalSession == nil {
- self.incrementalSession = try await manager.makeIncrementalSession(source: .microphone)
+ try await self.startIncrementalSession(manager: manager)
}
guard let session = self.incrementalSession else {
throw NSError(
@@ -571,6 +595,8 @@ final class FluidAudioProvider: TranscriptionProvider {
userInfo: [NSLocalizedDescriptionKey: "Incremental ASR session cannot finalize this recording"]
)
}
+ let generation = self.recordingGeneration
+ let profiles = self.incrementalPronunciationProfiles
let startedAt = ProcessInfo.processInfo.systemUptime
let acceptedBeforeFinal = self.incrementalAcceptedSampleCount
if samples.count > acceptedBeforeFinal {
@@ -578,6 +604,17 @@ final class FluidAudioProvider: TranscriptionProvider {
}
let appendFinishedAt = ProcessInfo.processInfo.systemUptime
let result = try await session.finish(finalAudioSamples: samples)
+ try self.requireCurrentRecording(generation)
+ let matches = await session.pronunciationMatches
+ let originalText = await session.unboostedText
+ try self.requireCurrentRecording(generation)
+ let text = self.effectivePronunciationMatchingEnabled && originalText == result.text
+ ? Self.applyPronunciationMatches(
+ result: result,
+ matches: matches,
+ profiles: profiles,
+ labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries)
+ ) : result.text
let finishFinishedAt = ProcessInfo.processInfo.systemUptime
DebugLogger.shared.debug(
"ASR_BENCH incremental_final_split acceptedBefore=\(acceptedBeforeFinal) " +
@@ -586,7 +623,7 @@ final class FluidAudioProvider: TranscriptionProvider {
"finishMs=\(Self.milliseconds(from: appendFinishedAt, to: finishFinishedAt))",
source: "ASRBenchmark"
)
- return ASRTranscriptionResult(text: result.text, confidence: result.confidence)
+ return ASRTranscriptionResult(text: text, confidence: result.confidence)
}
private static func milliseconds(from start: TimeInterval, to end: TimeInterval) -> String {
@@ -597,10 +634,12 @@ final class FluidAudioProvider: TranscriptionProvider {
_ samples: [Float],
to session: ParakeetIncrementalSession
) async throws {
+ let generation = self.recordingGeneration
var offset = self.incrementalAcceptedSampleCount
while offset < samples.count {
let end = min(offset + Self.incrementalAppendBlockSamples, samples.count)
try await session.append(Array(samples[offset..<end]))
+ try self.requireCurrentRecording(generation)
offset = end
self.incrementalAcceptedSampleCount = offset
}
@@ -609,6 +648,41 @@ final class FluidAudioProvider: TranscriptionProvider {
private func resetIncrementalSession() {
self.incrementalSession = nil
self.incrementalAcceptedSampleCount = 0
+ self.incrementalPronunciationProfiles = []
+ }
+
+ private func requireCurrentRecording(_ generation: UUID) throws {
+ try Task.checkCancellation()
+ guard self.recordingGeneration == generation else { throw CancellationError() }
+ }
+
+ private func pronunciationProfiles() async -> [PronunciationDictionaryProfile] {
+ 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 }
+ }
+
+ private static func pronunciationPrototype(_ profile: PronunciationDictionaryProfile) -> PronunciationEmbedding? {
+ PronunciationEmbeddingMatcher.prototype(from: profile.enrollments.map {
+ PronunciationEmbedding(values: $0.values, sourceFrameCount: $0.sourceFrameCount)
+ })
+ }
+
+ private func startIncrementalSession(manager: AsrManager) async throws {
+ let generation = self.recordingGeneration
+ let profiles = await self.pronunciationProfiles()
+ try self.requireCurrentRecording(generation)
+ let pairs = profiles.compactMap { profile in
+ Self.pronunciationPrototype(profile).map { (profile, $0) }
+ }
+ let session = try await manager.makeIncrementalSession(
+ source: .microphone, pronunciationPrototypes: pairs.map { $0.1 }
+ )
+ try self.requireCurrentRecording(generation)
+ self.incrementalPronunciationProfiles = pairs.map { $0.0 }
+ self.incrementalSession = session
+ self.incrementalAcceptedSampleCount = 0
}
func transcribeWithWordTimings(_ samples: [Float]) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {
@@ -620,7 +694,7 @@ final class FluidAudioProvider: TranscriptionProvider {
)
}
- let outcome: (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool)
+ let outcome: (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool) // swiftlint:disable:this discouraged_optional_collection
do {
let startedAt = Date().timeIntervalSince1970
outcome = try await self.transcribeFinalResult(samples, manager: manager)
@@ -648,14 +722,19 @@ final class FluidAudioProvider: TranscriptionProvider {
private func transcribeFinalResult(
_ samples: [Float], manager: AsrManager
- ) async throws -> (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool) {
+ ) async throws -> (result: ASRTranscriptionResult, tokenTimings: [TokenTiming]?, textMayBeCorrected: Bool) { // swiftlint:disable:this discouraged_optional_collection
+ if self.effectivePronunciationMatchingEnabled, samples.count > Self.incrementalChunkingThresholdSamples {
+ self.resetIncrementalSession()
+ try await self.startIncrementalSession(manager: manager)
+ return try (await self.transcribeIncrementalFinal(samples), nil, true)
+ }
let matchingEnabled = self.effectivePronunciationMatchingEnabled && samples.count <= 16_000 * 15
let dictionaryLabels = Self.dictionaryLabels(
from: self.effectiveCustomDictionaryEntries
)
let profiles: [PronunciationDictionaryProfile]
if matchingEnabled {
- let storedProfiles = await PronunciationDictionaryStore.shared.profiles(
+ let storedProfiles = await self.pronunciationStore.profiles(
modelKey: self.pronunciationModelKey
)
profiles = storedProfiles.compactMap { storedProfile in
@@ -733,10 +812,28 @@ final class FluidAudioProvider: TranscriptionProvider {
else { return nil }
return (profile, prototype)
}
- let matches = PronunciationEmbeddingMatcher.bestMatches(
- prototypes: usableProfiles.map { $0.1 },
- in: features
+ let matches = PronunciationEmbeddingMatcher.allMatches(
+ prototypes: usableProfiles.map { $0.1 }, in: features
+ ).enumerated().flatMap { index, hits in
+ hits.map { PronunciationWindowMatch(prototypeIndex: index, score: $0.score, frameRange: $0.frameRange) }
+ }
+ return Self.applyPronunciationMatches(
+ result: result,
+ matches: matches,
+ profiles: usableProfiles.map { $0.0 },
+ labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries)
)
+ }
+
+ static func applyPronunciationMatches(
+ result: ASRResult,
+ matches: [PronunciationWindowMatch],
+ profiles: [PronunciationDictionaryProfile],
+ labels: [UUID: String]
+ ) -> String {
+ guard let timings = result.tokenTimings else { return result.text }
+ let words = WordAudioChunkExtractor.words(from: timings)
+ guard !words.isEmpty else { return result.text }
struct Candidate {
let label: String
@@ -744,22 +841,30 @@ final class FluidAudioProvider: TranscriptionProvider {
let wordIndices: [Int]
}
var candidates: [Candidate] = []
- for (index, match) in matches.enumerated() {
- guard let match, match.score >= PronunciationCustomizationDefaults.acceptanceThreshold else { continue }
- let startTime = Double(match.frameRange.lowerBound) * features.frameDuration
- let endTime = Double(match.frameRange.upperBound) * features.frameDuration
+ for match in matches {
+ guard match.score.isFinite, match.score >= PronunciationCustomizationDefaults.acceptanceThreshold,
+ profiles.indices.contains(match.prototypeIndex),
+ let label = labels[profiles[match.prototypeIndex].dictionaryEntryID],
+ !match.frameRange.isEmpty, match.frameRange.lowerBound >= 0
+ else { continue }
+ let startTime = Double(match.frameRange.lowerBound) * 0.08
+ let endTime = Double(match.frameRange.upperBound) * 0.08
let indices = WordAudioChunkExtractor.substantiallyOverlappingWordIndices(
in: words,
startTime: startTime,
endTime: endTime
)
guard !indices.isEmpty else { continue }
- candidates.append(Candidate(label: usableProfiles[index].0.label, score: match.score, wordIndices: indices))
+ candidates.append(Candidate(label: label, score: match.score, wordIndices: indices))
}
var claimed = Set<Int>()
var accepted: [Candidate] = []
- for candidate in candidates.sorted(by: { $0.score > $1.score }) {
+ for candidate in candidates.sorted(by: {
+ 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
+ }) {
guard candidate.wordIndices.allSatisfy({ !claimed.contains($0) }) else { continue }
accepted.append(candidate)
claimed.formUnion(candidate.wordIndices)
@@ -869,6 +974,7 @@ final class FluidAudioProvider: TranscriptionProvider {
}
func clearCache() async throws {
+ self.recordingGeneration = UUID()
self.resetIncrementalSession()
let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
let selectedModel = self.modelOverride ?? SettingsStore.shared.selectedSpeechModel
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index 7729b8e8..2811ec4c 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -114,8 +114,7 @@ struct CustomDictionaryView: View {
private var trainingFinalOutputIsReady: Bool {
if self.activePronunciationMatching {
- return !self.trainingAlreadyCorrectWithoutReplacement &&
- self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount
+ return self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount
}
return !self.trainingAlreadyCorrectWithoutReplacement &&
self.trainingOutputIsCovered &&
@@ -123,12 +122,7 @@ struct CustomDictionaryView: View {
}
private var trainingAlreadyCorrectWithoutReplacement: Bool {
- if self.activePronunciationMatching {
- return self.trainingVariants.isEmpty &&
- !self.lastTrainingOutput.isEmpty &&
- self.lastTrainingOutput.caseInsensitiveCompare(self.normalizedTrainingReplacement) == .orderedSame &&
- self.trainingPronunciationEnrollments.count >= CustomDictionaryTrainingMerge.readyCoveredCount
- }
+ if self.activePronunciationMatching { return false }
return self.trainingVariants.isEmpty &&
self.trainingOutputIsCovered &&
!self.lastTrainingOutput.isEmpty &&
@@ -622,7 +616,7 @@ struct CustomDictionaryView: View {
Label(
self.activePronunciationMatching
? "Voice profile for \(self.trainingTargetReference) captured 3 times."
- : "FluidVoice recognized \(self.trainingTargetReference) 3 times in a row.",
+ : "The last 3 recordings are covered by this correction.",
systemImage: "checkmark.circle.fill"
)
.font(self.theme.typography.captionStrong)
@@ -644,7 +638,7 @@ struct CustomDictionaryView: View {
self.trainingInstruction(
number: 4,
text: self.activePronunciationMatching
- ? "Repeat 3 times to teach FluidVoice how your voice sounds."
+ ? "Repeat 3 times to capture pronunciation samples."
: "Keep repeating it until the circle reaches 3/3."
)
}
@@ -654,7 +648,8 @@ struct CustomDictionaryView: View {
DictionaryTrainingReadinessRing(
progress: self.trainingReadinessProgress,
total: CustomDictionaryTrainingMerge.readyCoveredCount,
- isReady: self.trainingFinalOutputIsReady || self.trainingAlreadyCorrectWithoutReplacement
+ isReady: self.trainingFinalOutputIsReady || self.trainingAlreadyCorrectWithoutReplacement,
+ usesVoiceMatching: self.activePronunciationMatching
)
Text(self.trainingReadinessCaption)
@@ -749,11 +744,11 @@ struct CustomDictionaryView: View {
private var trainingFinalOutputPanel: some View {
HStack(alignment: .center, spacing: self.theme.metrics.spacing.md) {
VStack(alignment: .leading, spacing: 5) {
- Text("Final output")
+ Text(self.activePronunciationMatching ? "Spelling to save" : "Final output")
.font(self.theme.typography.captionStrong)
.foregroundStyle(self.theme.palette.secondaryText)
- Text(self.trainingFinalOutputText)
+ Text(self.activePronunciationMatching ? self.normalizedTrainingReplacement : self.trainingFinalOutputText)
.font(self.theme.typography.bodySmallStrong)
.foregroundStyle(self.lastTrainingOutput.isEmpty ? self.theme.palette.tertiaryText : self.theme.palette.primaryText)
.lineLimit(1)
@@ -2177,12 +2172,13 @@ struct CustomDictionaryView: View {
let updatesExisting = self.entries.contains {
$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame
}
- self.entries = CustomDictionaryTrainingMerge.mergedEntries(
+ let updatedEntries = CustomDictionaryTrainingMerge.mergedEntries(
current: self.entries,
replacement: replacementText,
- triggers: self.trainingVariants
+ triggers: self.trainingVariants,
+ savePronunciation: self.activePronunciationMatching
)
- let entry = self.entries.first {
+ let entry = updatedEntries.first {
$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame
}
let enrollments = self.trainingPronunciationEnrollments
@@ -2205,11 +2201,15 @@ struct CustomDictionaryView: View {
return
}
}
+ let savedPronunciation = self.activePronunciationMatching
+ self.entries = updatedEntries
self.saveEntries()
self.resetTraining()
self.showReplacementConfirmation(
- title: updatesExisting ? "Replacement updated" : "Recorded",
- detail: updatesExisting ? "Your variants are ready." : "Replacement added at the top."
+ title: savedPronunciation ? "Word saved" : (updatesExisting ? "Replacement updated" : "Recorded"),
+ detail: savedPronunciation
+ ? "Spelling and pronunciation samples saved. Try the word in a sentence."
+ : (updatesExisting ? "Your variants are ready." : "Replacement added at the top.")
)
}
@@ -2480,7 +2480,8 @@ private extension CustomDictionaryView {
var asr: ASRService { self.appServices.asr }
var trainedReplacementButtonTitle: String {
- self.trainingAlreadyCorrectWithoutReplacement ? "Nothing to Save" : "Add Replacement"
+ self.activePronunciationMatching ? "Save Word"
+ : (self.trainingAlreadyCorrectWithoutReplacement ? "Nothing to Save" : "Add Replacement")
}
var shouldEmphasizeTrainedReplacementButton: Bool {
@@ -2750,12 +2751,12 @@ private enum DictionaryTrainingCopy {
}
if isReady {
return usesVoiceMatching
- ? "Ready. FluidVoice learned how \(target) sounds in your voice."
- : "Ready. FluidVoice got \(target) right 3 times in a row."
+ ? "3 samples captured for \(target). Save, then try it in a sentence."
+ : "Ready. The last 3 recordings are covered by this correction."
}
return usesVoiceMatching
- ? "Say \(target) 3 times to unlock Add Replacement."
- : "Keep trying until FluidVoice gets \(target) right 3 times in a row."
+ ? "Say \(target) 3 times to capture pronunciation samples."
+ : "Repeat until 3 recordings in a row need no new corrections."
}
}
@@ -2963,11 +2964,23 @@ enum CustomDictionaryTrainingMerge {
static func mergedEntries(
current entries: [SettingsStore.CustomDictionaryEntry],
replacement: String,
- triggers: [String]
+ triggers: [String],
+ savePronunciation: Bool = false
) -> [SettingsStore.CustomDictionaryEntry] {
let replacementText = self.normalizedReplacement(replacement)
- let incomingTriggers = self.normalizedTriggers(from: triggers, intendedReplacement: replacementText)
- guard !replacementText.isEmpty, !incomingTriggers.isEmpty else { return entries }
+ var incomingTriggers = self.normalizedTriggers(from: triggers, intendedReplacement: replacementText)
+ guard !replacementText.isEmpty else { return entries }
+ // Retraining pronunciation must not change existing text correction rules.
+ if incomingTriggers.isEmpty, savePronunciation,
+ entries.contains(where: { $0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame })
+ {
+ return entries
+ }
+ // A spelling-only rule anchors the pronunciation profile without inventing a misheard alias.
+ if incomingTriggers.isEmpty, savePronunciation {
+ incomingTriggers = [replacementText.lowercased()]
+ }
+ guard !incomingTriggers.isEmpty else { return entries }
let matchingIndex = entries.firstIndex {
$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame
@@ -2977,10 +2990,13 @@ enum CustomDictionaryTrainingMerge {
$0.replacement.caseInsensitiveCompare(replacementText) == .orderedSame
}
let existingTriggers = matchingEntries.flatMap(\.triggers)
- let combinedTriggers = self.normalizedTriggers(
+ var combinedTriggers = self.normalizedTriggers(
from: existingTriggers + incomingTriggers,
intendedReplacement: replacementText
)
+ if combinedTriggers.isEmpty, savePronunciation {
+ combinedTriggers = [replacementText.lowercased()]
+ }
let triggerKeys = Set(combinedTriggers)
let mergedEntry = replacementID.map {
@@ -3097,6 +3113,7 @@ private struct DictionaryTrainingReadinessRing: View {
let progress: Int
let total: Int
let isReady: Bool
+ let usesVoiceMatching: Bool
@Environment(\.theme) private var theme
@@ -3124,7 +3141,7 @@ private struct DictionaryTrainingReadinessRing: View {
.foregroundStyle(self.isReady ? self.theme.palette.accent : self.theme.palette.primaryText)
.monospacedDigit()
- Text(self.isReady ? "Ready" : "correct")
+ Text(self.usesVoiceMatching ? "samples" : "covered")
.font(self.theme.typography.captionSmall)
.foregroundStyle(self.theme.palette.secondaryText)
}
@@ -3134,7 +3151,7 @@ private struct DictionaryTrainingReadinessRing: View {
.animation(.easeOut(duration: 0.24), value: self.progress)
.accessibilityElement(children: .ignore)
.accessibilityLabel("Training progress")
- .accessibilityValue("\(self.progress) of \(self.total) correct")
+ .accessibilityValue("\(self.progress) of \(self.total) \(self.usesVoiceMatching ? "samples captured" : "recordings covered")")
}
}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index 4d4a7b8e..e392efab 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -1,5 +1,8 @@
@testable import FluidVoice_Debug
import Foundation
+#if arch(arm64)
+import FluidAudio
+#endif
import XCTest
@MainActor
@@ -707,6 +710,49 @@ extension DictationE2ETests {
XCTAssertEqual(triggers, ["fluid voice"])
}
+ func testPronunciationTrainingCanSaveAlreadyCorrectWordWithoutInventingMisheardAliases() async throws {
+ let untouched = SettingsStore.CustomDictionaryEntry(triggers: ["other phrase"], replacement: "Other")
+ let entries = CustomDictionaryTrainingMerge.mergedEntries(
+ current: [untouched], replacement: "Barath", triggers: [], savePronunciation: true
+ )
+ let entry = try XCTUnwrap(entries.first)
+ XCTAssertEqual(entry.replacement, "Barath")
+ XCTAssertEqual(entry.triggers, ["barath"])
+ XCTAssertEqual(entries.last, untouched)
+
+ let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("Pronunciation-\(UUID().uuidString).json")
+ defer { try? FileManager.default.removeItem(at: fileURL) }
+ let store = PronunciationDictionaryStore(fileURL: fileURL)
+ let enrollments = (0..<3).map { _ in
+ PronunciationEnrollmentCapture(values: [1, 0], sourceFrameCount: 3, modelKey: "parakeet-v3")
+ }
+ try await store.upsert(dictionaryEntryID: entry.id, label: entry.replacement, modelKey: "parakeet-v3", enrollments: enrollments)
+ let restored = await PronunciationDictionaryStore(fileURL: fileURL).allProfiles()
+ XCTAssertEqual(restored.first?.dictionaryEntryID, entry.id)
+ XCTAssertEqual(restored.first?.enrollments.count, 3)
+ XCTAssertEqual(restored.first?.label, "Barath")
+ }
+
+ func testBasicTrainingAlreadyCorrectWordStillDoesNotCreateReplacement() {
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["other phrase"], replacement: "Other")
+ XCTAssertEqual(
+ CustomDictionaryTrainingMerge.mergedEntries(current: [entry], replacement: "Barath", triggers: []),
+ [entry]
+ )
+ XCTAssertEqual(
+ CustomDictionaryTrainingMerge.mergedEntries(current: [entry], replacement: " ", triggers: [], savePronunciation: true),
+ [entry]
+ )
+ }
+
+ func testPronunciationOnlyRetrainingKeepsExistingIdentityAndCorrections() {
+ let entry = SettingsStore.CustomDictionaryEntry(triggers: ["bar at"], replacement: "Barath")
+ let entries = CustomDictionaryTrainingMerge.mergedEntries(
+ current: [entry], replacement: "Barath", triggers: [], savePronunciation: true
+ )
+ XCTAssertEqual(entries, [entry])
+ }
+
func testDictionaryTrainingMergeDedupesAndMovesDuplicateTriggers() {
let oldReplacement = SettingsStore.CustomDictionaryEntry(
triggers: ["Fluid Voice.", "old trigger"],
@@ -981,6 +1027,90 @@ extension DictationE2ETests {
XCTAssertFalse(SettingsStore.SpeechModel.cohereTranscribeSixBit.supportsPronunciationMatching)
}
+ #if arch(arm64)
+ func testLongPronunciationMatchesDeduplicateOverlapAndKeepRepeatedWords() {
+ let id = UUID()
+ let profile = PronunciationDictionaryProfile(dictionaryEntryID: id, label: "old", modelKey: "v3", hiddenSize: 1, enrollments: [])
+ let result = ASRResult(text: "fluid voice and fluid voice", confidence: 1, duration: 120, processingTime: 0, tokenTimings: [
+ TokenTiming(token: "▁fluid", tokenId: 1, startTime: 13, endTime: 13.3, confidence: 1),
+ TokenTiming(token: "▁voice", tokenId: 2, startTime: 13.3, endTime: 13.6, confidence: 1),
+ TokenTiming(token: "▁and", tokenId: 3, startTime: 14, endTime: 14.3, confidence: 1),
+ TokenTiming(token: "▁fluid", tokenId: 1, startTime: 110, endTime: 110.3, confidence: 1),
+ TokenTiming(token: "▁voice", tokenId: 2, startTime: 110.3, endTime: 110.6, confidence: 1),
+ ])
+ let hits = [
+ PronunciationWindowMatch(prototypeIndex: 0, score: 0.9, frameRange: 162..<170),
+ PronunciationWindowMatch(prototypeIndex: 0, score: 0.8, frameRange: 161..<171),
+ PronunciationWindowMatch(prototypeIndex: 0, score: 0.9, frameRange: 1375..<1383),
+ ]
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: hits, profiles: [profile], labels: [id: "FluidVoice"]), "FluidVoice and FluidVoice")
+ // Deleted dictionary entries and low-confidence hits leave speech untouched.
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: hits, profiles: [profile], labels: [:]), result.text)
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [PronunciationWindowMatch(prototypeIndex: 0, score: 0.1, frameRange: 162..<170)], profiles: [profile], labels: [id: "FluidVoice"]), result.text)
+ XCTAssertEqual(FluidAudioProvider.applyPronunciationMatches(result: result, matches: [PronunciationWindowMatch(prototypeIndex: 99, score: 1, frameRange: 162..<170)], profiles: [profile], labels: [id: "FluidVoice"]), result.text)
+ }
+
+ func testPronunciationStreamingTwoMinuteRealAudio() async throws {
+ guard let path = ProcessInfo.processInfo.environment["FLUIDVOICE_PRONUNCIATION_AUDIO"] else {
+ throw XCTSkip("Set FLUIDVOICE_PRONUNCIATION_AUDIO to the public real-speech fixture")
+ }
+ let source = try AudioConverter().resampleAudioFile(path: path)
+ XCTAssertGreaterThanOrEqual(source.count, 960_000)
+ // Repeat a real 60-second recording for a reproducible two-minute repeated-word fixture.
+ let minute = Array(source.prefix(960_000))
+ let samples = minute + minute
+ let id = UUID()
+ let file = FileManager.default.temporaryDirectory.appendingPathComponent("pronunciation-\(UUID()).json")
+ defer { try? FileManager.default.removeItem(at: file) }
+ let store = PronunciationDictionaryStore(fileURL: file)
+ let entry = SettingsStore.CustomDictionaryEntry(id: id, triggers: [], replacement: "TrainedWord")
+ let provider = FluidAudioProvider(
+ modelOverride: .parakeetTDT,
+ configureWordBoosting: false,
+ enhancementOptions: FluidAudioProviderEnhancementOptions(experimentalUnifiedFinalEnabled: false, pronunciationMatchingEnabled: true, customDictionaryEntries: [entry]),
+ pronunciationStore: store
+ )
+ try await provider.prepare()
+ let training = try await provider.transcribeDictionaryTraining(Array(minute.prefix(32_000)))
+ let capture = try XCTUnwrap(training.pronunciationEnrollment)
+ try await store.upsert(dictionaryEntryID: id, label: entry.replacement, modelKey: capture.modelKey, enrollments: [capture, capture, capture])
+ var fullTimes: [Double] = []
+ var stopTimes: [Double] = []
+ for run in 0..<4 {
+ provider.resetStreamingPreviewCache()
+ let batchStart = Date()
+ let batch = try await provider.transcribeFinal(samples)
+ let batchMs = Date().timeIntervalSince(batchStart) * 1000
+ provider.resetStreamingPreviewCache()
+ for end in stride(from: 32_000, through: samples.count - 32_000, by: 32_000) {
+ if let start = provider.incrementalPreviewDeltaStart(totalSampleCount: end) {
+ _ = try await provider.transcribeStreamingDelta(Array(samples[start..<end]), totalSampleCount: end)
+ } else {
+ _ = try await provider.transcribeStreaming(Array(samples.prefix(end)))
+ }
+ }
+ let stop = Date()
+ let streamed = try await provider.transcribeFinal(samples)
+ let stopMs = Date().timeIntervalSince(stop) * 1000
+ XCTAssertEqual(streamed.text, batch.text, "Feed cadence must not change final corrections")
+ XCTAssertTrue(streamed.text.contains("TrainedWord"))
+ if run > 0 { fullTimes.append(batchMs); stopTimes.append(stopMs) }
+ }
+ print("PRONUNCIATION_TWO_MINUTE batchMs=\(fullTimes) stopMs=\(stopTimes)")
+ // A reset during suspended model work must prevent the old recording from publishing.
+ provider.resetStreamingPreviewCache()
+ let entered = expectation(description: "Old preview entered")
+ let old = Task {
+ entered.fulfill()
+ return try await provider.transcribeStreaming(samples)
+ }
+ await fulfillment(of: [entered], timeout: 5)
+ provider.resetStreamingPreviewCache()
+ do { _ = try await old.value; XCTFail("Stale preview was accepted") } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") }
+ XCTAssertNil(provider.incrementalPreviewDeltaStart(totalSampleCount: samples.count))
+ }
+ #endif
+
func testDictionaryTrainingAudioCursorResetsAfterBufferGenerationChange() {
var cursor = DictionaryTrainingAudioCursor(generation: 4)
cursor.consume(1600)
@@ -2909,11 +3039,11 @@ final class OverlayFailureStateTests: XCTestCase {
final class AudioBudgetMeasurementGateTests: XCTestCase {
func testMeasurementRequiresMatchingRevisionAndBudget() {
- let gate = AudioBudgetMeasurementGate(revision: 7, budgetBytes: 1_000)
+ let gate = AudioBudgetMeasurementGate(revision: 7, budgetBytes: 1000)
- XCTAssertTrue(gate.accepts(currentRevision: 7, currentBudgetBytes: 1_000))
- XCTAssertFalse(gate.accepts(currentRevision: 8, currentBudgetBytes: 1_000))
- XCTAssertFalse(gate.accepts(currentRevision: 7, currentBudgetBytes: 2_000))
+ XCTAssertTrue(gate.accepts(currentRevision: 7, currentBudgetBytes: 1000))
+ XCTAssertFalse(gate.accepts(currentRevision: 8, currentBudgetBytes: 1000))
+ XCTAssertFalse(gate.accepts(currentRevision: 7, currentBudgetBytes: 2000))
}
func testPendingOrReferencedAudioIsNeverDeletedAsOrphan() {
diff --git a/docs/design/dictionary-learning-api.md b/docs/design/dictionary-learning-api.md
new file mode 100644
index 00000000..7b2fef1a
--- /dev/null
+++ b/docs/design/dictionary-learning-api.md
@@ -0,0 +1,143 @@
+# 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.
+
+## Outcome
+
+A user correction should associate the intended spelling with the actual pronunciation from that dictation. A confirmed, well-aligned original occurrence can supply one real example; the application should not automatically ask for three fresh recordings. Save audio evidence and its derived embedding together, so the spelling, text variants and sound all refer to the same occurrence. These are personalization examples, not acoustic-model weight training.
+
+Manual entry, correction approval, explicit voice enrollment and future automatic additions all call the same learning service. They choose how an addition is initiated; they do not each implement extraction, embedding, persistence or matching rules. No new HTTP server is needed: the internal Swift service is the canonical API, with optional adapters for the existing Local API later.
+
+## What exists today, and review findings
+
+| Path | Current result | Missing for correction-based learning |
+|---|---|---|
+| Manual dictionary entry | Intended spelling and text triggers | No audio exists unless linked to a spoken occurrence |
+| Basic voice training / correction popup training | Text variants collected from new recordings | Popup ignores pronunciationEnrollment; original correction audio is not linked |
+| Advanced voice training in dictionary page | Text aliases and model-specific embedding examples | No persisted audio reference; requires three examples |
+| Detected correction / Add Only | heardText and correctedText become text replacement | Candidate lacks recording ID, original token span and audio evidence |
+| Long-recording matching | Matches existing trained profiles during dictation | Discards encoder features after producing hits; cannot learn an unknown word from those hits alone |
+
+Source anchors: AutomaticDictionaryCorrectionCandidate in AutomaticDictionaryCorrectionTracker.swift; AutomaticDictionaryTrainingSession.persist/addOnlyCorrection; PronunciationEnrollmentCapture and PronunciationDictionaryStore; FluidAudioProvider.pronunciationProfiles/transcribeFinalResult; CustomDictionaryView.finishTrainingSampleStop.
+
+Two runtime gates still require enrollments.count >= 3. Merely saving one embedding would not activate it. They must eventually consume a common eligibility policy, not be changed independently to accept everything.
+
+ASRService retains completed audio only when history and history-audio saving are enabled. That snapshot is consumed by other flows. It is not a reliable learning-evidence API. Also, correction observation starts with inserted text and target PID; inserted text may already contain alias replacements, formatting or AI rewriting. Searching that text for a word is not sufficient to select the correct audio occurrence.
+
+The existing save paths update UserDefaults text entries and a separate JSON pronunciation store. They cannot provide a single atomic learning commit, especially once audio files are added. The shared service must own a recoverable commit boundary before its clients claim success.
+
+## Service boundaries
+
+```swift
+// Contract sketch, not compiled production declarations.
+protocol DictionaryLearning {
+ func prepare(_ request: LearningRequest) async throws -> LearningProposal
+ func commit(_ proposal: ProposalID, decision: LearningDecision,
+ idempotencyKey: UUID) async throws -> LearningReceipt
+ func discard(_ proposal: ProposalID) async
+ func retract(_ learningEvent: LearningEventID) async throws
+ func snapshot(for model: AcousticModelIdentity) async throws -> DictionaryMatchingSnapshot
+}
+```
+
+`prepare` resolves evidence, checks eligibility, stages the clip/embedding and produces a reviewable proposal. It must not change active dictionary rules, microphone state, boosting, history settings or UI selection. `commit` activates exactly the prepared content under the current learning policy. A retry with the same idempotency key returns the original receipt. `retract` removes that event's contributions, not an entire word's unrelated examples or aliases.
+
+The service actor coordinates independent components:
+
+- `DictationEvidenceStore`: immutable recording receipts, ephemeral audio ownership and bounded evidence leases.
+- `CorrectionAlignmentResolver`: maps the corrected delivered-text span back to the original ASR token occurrence, with explicit ambiguity results.
+- `PronunciationEvidenceExtractor`: creates a focal audio example and an embedding using a versioned acoustic backend. No UI or dictionary writes.
+- `DictionaryLearningPolicy`: determines confirmation requirements, alias scope and whether an example is eligible for matching.
+- `DictionaryLearningRepository`: atomic metadata commits, staged audio files, recovery, migrations and immutable matching snapshots.
+
+FluidAudio owns feature extraction and scoring. FluidVoice owns user intent, text-edit provenance, policy, retention and persistence. A model/search-library swap changes the extractor implementation, not each UI caller.
+
+## Request and evidence identity
+
+`LearningRequest` contains:
+
+- Request/event UUID and optional existing dictionary entry UUID/revision.
+- Intended spelling; observed original ASR text when known.
+- Source: explicit correction, manual word, fresh voice example or automatic proposal. Source is provenance, not permission to bypass policy.
+- Evidence input: a dictation receipt plus delivered-text span, a fresh recording receipt plus focal span, or no audio.
+- Confirmation/policy context supplied by the trusted adapter. Reuse must not allow arbitrary callers to assert automatic approval.
+
+A `DictationReceipt` contains a recording UUID, generation, ASR model identity, raw transcript revision, original token timings, delivery ID and the transformation mapping to delivered text. Each edit stage records span mappings where reliable. Rewritten or ambiguous regions are explicitly unmappable. Ranges use named coordinate systems: UTF-16 for text, integer sample offsets for audio, global encoder-frame offsets for features. Never pass a bare range with an assumed unit.
+
+An accepted `PronunciationExample` contains:
+
+- Stable example/event/entry IDs, source recording and original token span.
+- Audio asset reference, sample rate/channel format, focal sample range and context range.
+- Embedding values/dimension, acoustic model revision, feature-extraction/pooling version and normalization convention.
+- Actual heard text and intended spelling, provenance and alignment/quality measurements.
+- Policy state and creation time. Quality measurements are not mislabeled probabilities.
+
+Keep distinct examples; do not count retry copies or the same source occurrence as multiple independent recordings. A computed prototype is a cache derived from examples and versioned by entry revision/model identity. Do not persist only its average and throw away its provenance.
+
+## Reusing the actual recording efficiently
+
+1. Capture starts immediately through the existing pipeline. Learning adds no wait before the first PCM.
+2. During dictation, existing pronunciation matching continues to reuse each ASR chunk's encoder output. This matching is independent of enrollment.
+3. When correction tracking is enabled, finalize a bounded temporary recording receipt without awaiting disk work on the insert path. The receipt covers earlier words too: keeping only the newest 15 seconds cannot learn a correction near the start of a two-minute recording.
+4. Retain temporary evidence for the correction-observation window under explicit age, count and byte budgets. A short lease protects an accepted operation from eviction. Budget exhaustion/expiry returns evidenceUnavailable, never waits indefinitely. History recording remains a separate preference and consumer; do not steal its consume-once snapshot.
+5. On a confirmed correction, resolve the exact source occurrence and crop its word/phrase with the context needed by the encoder. Prefer compatible retained features when available. Otherwise run one bounded encoder-only pass on the original context window in the background. No second encoder pass is required on every dictation.
+6. Persist the accepted focal clip plus necessary bounded context and focal boundaries. The context and extractor identity matter: embedding a tiny isolated crop can differ from embedding that word in its original sentence. Store enough evidence to reproduce the chosen extraction. Do not retain an entire dictation permanently for a single word.
+7. Discard temporary recording evidence when the bounded observation/lease ends. Removing an example deletes its audio when no other example references it.
+
+Retention limits must be explicit configuration and tested; the service may not silently remove earlier audio and then attach a same-spelled later occurrence. Sensitive source audio must not appear in logs or ordinary dictionary text exports. Existing audio-history opt-out must not be silently reinterpreted as agreement to permanent full-recording storage; learning retention is an explicit product policy.
+
+## Results and one-example eligibility
+
+Prepare/commit outcomes are explicit, with no permanently pending branches:
+
+| Outcome | Meaning |
+|---|---|
+| learned | Spelling, accepted sound example and configured text evidence are durably saved and eligible |
+| savedTextOnly | Spelling/rule saved; there was no usable audio; never present this as pronunciation learned |
+| savedPendingEvidence | Example retained but not eligible yet; include a concrete reason and next action |
+| needsConfirmation | Proposed spelling/meaning needs approval before activation |
+| needsAudio | Evidence expired, missing or could not be aligned; user may optionally speak once |
+| rejected | Unsupported evidence, conflict or invalid request; no active partial writes |
+| cancelled | No new active rule; staged artifacts released |
+
+The API accepts one confirmed occurrence. Activation from one example must be justified by evaluation and quality/alignment checks, not by duplicating it three times or replacing the current count gate with a permissive threshold. Strong evidence can activate without three repeats once calibrated; uncertain evidence requests one additional example or remains pending. Existing three-example profiles remain supported during migration.
+
+Text variants and acoustic evidence complement each other. A newly observed alias can be ambiguous common speech, so evidence storage is separate from granting a global unconditional text replacement. Preserve explicitly authored global rules; learned aliases can require acoustic/context support. Never learn from the system's own automatic replacement as if it were a fresh user correction. Homophones require intent/context, not a claim that embeddings can distinguish identical sounds.
+
+## Persistence and event contract
+
+Use a canonical transactional learning repository with versioned entries/examples/alias provenance/learning events. Migrate legacy text entries and pronunciation JSON once with an idempotent version marker; do not leave two independently writable sources of truth. Preserve legacy entry IDs and track missing audio as an explicit legacy state. Use a temporary migration fallback only with a bounded exit and visible failure result.
+
+Stage audio in the same app-support volume, validate content, then atomically rename to its final asset before committing a database reference. A crash before metadata commit leaves an orphan that recovery can remove; an active entry must never point to an uncommitted/missing staged file. Commit the word, examples, alias policy and event receipt together. Startup recovery resolves interrupted transactions and staged/orphan files under a bounded cleanup policy.
+
+Publish a narrow `dictionaryLearningCommitted(revision, changedEntryIDs)` event once after durable success. Its consumers rebuild text-match caches and pronunciation snapshots, coalescing updates. Do not reuse `.parakeetVocabularyDidChange` as the learning event: it has ASR/configuration/UI consumers. Enrolling pronunciation must not implicitly enable boosting, reload unrelated audio hardware or switch the selected model. Trace existing producers/consumers when adapting legacy setters.
+
+Model changes do not compare incompatible vectors. Re-embedding from retained audio is an explicit background migration with a policy/result state; unavailable model/audio keeps the text entry usable without falsely marking acoustic matching ready.
+
+## Implementation sequence
+
+1. Evidence receipt and span-coordinate types; ownership/expiry contract; no automatic additions yet.
+2. Extractor API with original context and one-occurrence example storage. Extend ASR/delivery plumbing to retain reliable mappings; keep insertion fast.
+3. Transactional learning service and policy results; migrate legacy profile/alias adapters. Replace duplicated three-count gates with the common eligibility result only after one-example evaluation.
+4. Route user-approved correction through the API; use the original audio when mapped, with truthful fallback when unavailable.
+5. Route fresh voice/manual entry through the same service. Fresh voice becomes an optional source of extra evidence; manual text without a recording cannot manufacture a pronunciation example.
+6. Add automatic proposal/approval rules as another adapter after precision validation. Its trigger and UI can evolve without changing extraction/storage contracts.
+
+## Review and verification gates
+
+Long-recording review: source confirms stable matches are retained once, tail candidates replace earlier tail candidates, global offsets reach final token reconciliation, old recording generations cannot publish, and cancelled current preview state is cleared without resetting newer state. Existing evidence is in `scratch/pronunciation-streaming-benchmark/RESULTS.md`: boundary parity, repeated-word/overlap checks, two-minute provider regression and multilingual batch parity. This review does not prove false-positive safety for every accent; previous 34 ms is remaining library processing, not end-to-end insertion latency.
+
+Before enabling correction-based learning, test:
+
+- Same evidence through different UI/API callers produces the same entry/example; retry produces no duplicate example.
+- A correction at the first minute and the same word at the second minute binds to the selected occurrence only.
+- Formatting, AI rewriting and multiword-to-one-word corrections preserve a known mapping or reject acoustic learning; never guess.
+- Missing/expired audio yields a truthful text-only or needsAudio result.
+- Saving without audio never reports learned; saving one genuine example never counts it as three.
+- Persist failure/crash/restart, stale proposal revision, cancel, delete during preparation and retraction leave no partial active entry or lost unrelated examples.
+- Model mismatch, duplicate events, incompatible embeddings and rejected proposals cannot become active matches.
+- Both approved correction and future automatic adapters pass the same conformance suite; neither changes boosting, microphone lifecycle, history preferences, live text or other entries as a side effect.
+- Original recorded speech is tested against target-present, target-absent/confusable and already-correct speech across accents. Report recall AND false substitutions before selecting activation thresholds.
+- Measure correction preparation separately from dictation stop latency, and repeat long-recording tests after adding evidence retention. Test bounded memory/disk, expiry and cleanup during rapid new recordings.
+
+No automatic-learning behavior or audio-retention change was implemented as part of this design review.
diff --git a/docs/research/pronunciation-long-recording-stage-costs.md b/docs/research/pronunciation-long-recording-stage-costs.md
new file mode 100644
index 00000000..4ceb89dd
--- /dev/null
+++ b/docs/research/pronunciation-long-recording-stage-costs.md
@@ -0,0 +1,25 @@
+# Long-recording finalization stage review — 2026-09-19
+
+Measured the actual 120-second all-after-stop path with one pronunciation prototype, Parakeet v3, no vocabulary boosting, on Apple M5 Max / 128 GiB. Fixture: public jensen-60s.wav repeated twice, 1,920,000 samples at 16 kHz, 1,571 transcript characters. Nine stable windows plus one tail window. Two warmup runs, seven measured Release runs. Instrumentation is in a scratch copy of the exact companion library source; production sources were not instrumented. All profiled runs produced identical text.
+
+| Stage | Median milliseconds |
+|---|---:|
+| preprocessor | 12.48 |
+| encoder | 245.48 |
+| decode | 277.84 |
+| pronunciation | 8.20 |
+| mergeAndText | 0.32 |
+| other | 0.78 |
+| Full finalization | 545.73 |
+
+Pronunciation includes 1.26 ms copying existing encoder features across all ten windows; that is nested, not an extra additive stage. The remainder builds/scans pronunciation candidates. Encoder and decoder together account for roughly 96% of this workload. No second acoustic encoder is run for matching. Stage medians are separately aggregated, so their sum can differ slightly from the median total.
+
+Preprocessor includes mel/input preparation; encoder includes acoustic feature inference and its prepared-buffer management. Decode includes token prediction, extraction and associated buffer release. Merge/text covers overlap merging and final result construction. Other is per-run residual bookkeeping, PCM append/copy/chunk preparation and actor-call overhead. Model initialization is outside the measurement.
+
+The earlier 546 ms to 34 ms result compares all work after stop with reusing stable windows already processed during dictation. It is not a 16x reduction in total compute, and it is not microphone-to-keystroke latency. Raw app delivery, dictionary text regexes and AI cleanup are outside this library benchmark. The prior 100-prototype workload used duplicate durations/vectors; diverse dictionary durations can cost more.
+
+Evidence: scratch/pronunciation-stage-profile/results.json and results.log; scratch/pronunciation-stage-profile/Sources/Profile/main.swift; instrumented library under FluidAudioProfiled. The unchanged baseline and lifecycle/accuracy limitations are documented in scratch/pronunciation-streaming-benchmark/RESULTS.md.
+
+Review checks already run on the implementation: two-minute app parity and stale-recording regression, repeated-word/overlap unit checks, 14 library unit tests, eight-language/three-pattern batch parity, Release boundary/cancellation assertions, signed FI install. Scoped lint has zero violations. Required whole-repo format/lint was run: unrelated formatter edits were restored; full lint reports 623 existing violations outside these two source files. No unrelated Feedback edits are included in the dictionary commits.
+
+Companion FluidAudio commit: 97ed23265098a78a09378659063d52dee908f9e0. The app commit pins that revision; the local working tree retains a development override. The library commit must be published before a fresh machine can resolve the app pin. No pushes performed.