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): add opt-in temporal matching and negative examples

altic-dev998896343a3a
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 6f5c7f2f..c9dca52a 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -722,7 +722,7 @@ final class ASRService: ObservableObject {
guard self.activeActivityLease == lease, lease.activity == .meeting else { return }
let taskID = UUID()
- let handbackTask = Task { @MainActor [weak self] () -> Void in
+ let handbackTask = Task { @MainActor [weak self] () in
guard let self else { return }
await self.performMeetingAudioHandback(lease)
}
@@ -3578,10 +3578,14 @@ final class ASRService: ObservableObject {
}
// Do not update self.finalText here to avoid instant binding insert in playground
- if !isolatedDictionaryCapture, SettingsStore.shared.automaticDictionaryLearningEnabled,
+ if !isolatedDictionaryCapture, SettingsStore.shared.automaticDictionaryLearningEnabled || DictionaryMatcherExperiment.collectNegatives,
let alignment = result.dictionaryLearningAlignment
{
- self.retainDictionaryLearningRecording(DictionaryLearningRecording(alignment: alignment, samples: capturedPCM))
+ self.retainDictionaryLearningRecording(DictionaryLearningRecording(
+ alignment: alignment,
+ samples: capturedPCM,
+ retainAudio: SettingsStore.shared.automaticDictionaryLearningEnabled
+ ))
}
let textWithoutFillers = ASRService.removeFillerWords(result.text)
diff --git a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
index 42f16405..3a06a84d 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
@@ -8,6 +8,7 @@ struct AutomaticDictionaryCorrectionCandidate: Equatable, Identifiable {
let correctedText: String
var sourceUTF16Range: NSRange?
var audioEvidence: DictionaryLearningAudioEvidence?
+ var negativeCorrection: DictionaryNegativeCorrection?
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.id == rhs.id && lhs.heardText == rhs.heardText && lhs.correctedText == rhs.correctedText
@@ -29,7 +30,6 @@ enum AutomaticDictionaryCorrectionDetector {
)
private static let maxCandidateLength = 40
private static let maxCombinedLength = 70
- private static let maxWords = 3
static func textChange(before: String, after: String) -> AutomaticDictionaryTextChange? {
guard before != after else { return nil }
@@ -217,7 +217,7 @@ enum AutomaticDictionaryCorrectionDetector {
}
let words = value.split(whereSeparator: { $0.isWhitespace })
- return !words.isEmpty && words.count <= self.maxWords
+ return !words.isEmpty && words.count <= 3
}
private static func isMeaningfulCorrection(heard: String, corrected: String) -> Bool {
@@ -436,7 +436,7 @@ final class AutomaticDictionaryCorrectionTracker {
_ insertedText: String, targetPID: pid_t?, learningRecording: DictionaryLearningRecording? = nil
) {
self.cancel()
- guard SettingsStore.shared.automaticDictionaryLearningEnabled,
+ guard SettingsStore.shared.automaticDictionaryLearningEnabled || DictionaryMatcherExperiment.collectNegatives,
!insertedText.isEmpty
else {
return
@@ -732,6 +732,17 @@ final class AutomaticDictionaryCorrectionTracker {
}
self.stopObservation()
+ if let candidate, let context, DictionaryMatcherExperiment.collectNegatives,
+ !SettingsStore.shared.shouldShowOnboarding, !AppServices.shared.asr.isRunning,
+ !DictionaryCorrectionOverlayController.shared.isPresented,
+ let negative = DictionaryNegativeEvidenceResolver.resolve(context: context, heard: candidate.heardText, corrected: candidate.correctedText)
+ {
+ var prepared = candidate
+ prepared.negativeCorrection = negative
+ DictionaryCorrectionOverlayController.shared.show(candidate: prepared) { _ in }
+ return
+ }
+
guard let candidate,
SettingsStore.shared.automaticDictionaryLearningEnabled,
!SettingsStore.shared.shouldShowOnboarding,
diff --git a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
index 0312fe3a..29bde5e6 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryTrainingSession.swift
@@ -155,12 +155,66 @@ final class AutomaticDictionaryTrainingSession: ObservableObject {
}
func addOnlyCorrection() {
+ guard !self.isCancelled, self.capturePhase == .idle else { return }
self.persist(triggers: [self.candidate.heardText])
}
+ func confirmWrongMatch() {
+ guard !self.isCancelled, self.capturePhase == .idle,
+ let correction = self.candidate.negativeCorrection else { return }
+ self.onInteraction?()
+ self.capturePhase = .processing
+ self.statusMessage = "Saving wrong match…"
+ Task { @MainActor in
+ defer { self.capturePhase = .idle }
+ let store = DictionaryNegativeExampleStore.shared
+ let revision = await store.revision()
+ let evidence = correction.evidence
+ func entryIsCurrent() -> Bool {
+ SettingsStore.shared.customDictionaryEntries.contains { $0.id == evidence.entryID && $0.replacement == evidence.label }
+ }
+ do {
+ let profiles = await PronunciationDictionaryStore.shared.profiles(modelKey: evidence.modelKey)
+ guard !self.isCancelled, DictionaryMatcherExperiment.collectNegatives, entryIsCurrent(),
+ correction.expiresAt > Date(), profiles.contains(where: {
+ $0.dictionaryEntryID == evidence.entryID && DictionaryNegativeEvidenceResolver.profileKey($0) == evidence.profileKey
+ }) else { throw PronunciationDictionaryStoreError.staleEvidence }
+ try await store.save(correction, expectedRevision: revision)
+ let latest = await PronunciationDictionaryStore.shared.profiles(modelKey: evidence.modelKey)
+ guard !self.isCancelled, DictionaryMatcherExperiment.collectNegatives, entryIsCurrent(),
+ await store.revision() == revision,
+ latest.contains(where: { $0.dictionaryEntryID == evidence.entryID && DictionaryNegativeEvidenceResolver.profileKey($0) == evidence.profileKey })
+ else {
+ try await store.remove(id: evidence.id)
+ throw PronunciationDictionaryStoreError.staleEvidence
+ }
+ self.completeSave(title: "Wrong Match Saved")
+ } catch {
+ guard !self.isCancelled else { return }
+ self.hasError = true
+ self.statusMessage = "Couldn’t save this example. It may have expired or the word changed."
+ }
+ }
+ }
+
func addTrainedReplacement() {
- guard self.canSave else { return }
- self.persist(triggers: self.variants)
+ guard self.canSave, !self.isCancelled else { return }
+ self.isAutomaticCaptureEnabled = false
+ self.capturePhase = .processing
+ let variants = self.variants
+ Task { @MainActor in
+ let filtered = await VoiceTrainingAliasFilter.filter(variants)
+ self.capturePhase = .idle
+ guard !self.isCancelled else { return }
+ guard !filtered.accepted.isEmpty else {
+ self.hasError = true
+ self.statusMessage = filtered.lookupAvailable
+ ? "These recordings contain everyday words. Try again, or add the correction manually."
+ : "Couldn't check these words. Try saving again, or add the correction manually."
+ return
+ }
+ self.persist(triggers: filtered.accepted)
+ }
}
func removeVariant(_ variant: String) {
diff --git a/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift b/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift
new file mode 100644
index 00000000..20822515
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift
@@ -0,0 +1,138 @@
+import Accelerate
+import Foundation
+
+/// Independent opt-ins. Off returns the existing matcher unchanged.
+nonisolated enum DictionaryMatcherExperiment {
+ static var positiveEnabled: Bool { UserDefaults.standard.bool(forKey: "DictionaryTemporalMatcherEnabled") }
+ static var collectNegatives: Bool { UserDefaults.standard.bool(forKey: "DictionaryNegativeLearningEnabled") }
+ static var compareNegatives: Bool { UserDefaults.standard.bool(forKey: "DictionaryNegativeComparisonEnabled") }
+ static var needsFrames: Bool { positiveEnabled || collectNegatives || compareNegatives }
+ static let version = "parakeet-exact-rms005-frames-v1"
+}
+
+nonisolated struct DictionaryMatchFrames: Codable, Equatable, Sendable {
+ let hiddenSize: Int
+ let values: [Float]
+ var count: Int { self.hiddenSize > 0 ? self.values.count / self.hiddenSize : 0 }
+ var isValid: Bool {
+ (1...1024).contains(self.hiddenSize) && (1...192).contains(self.count)
+ && self.values.count == self.count * self.hiddenSize && self.values.allSatisfy(\.isFinite)
+ }
+
+ func normalized() -> Self {
+ guard self.isValid else { return self }
+ var result = self.values
+ for f in 0..<self.count {
+ let start = f * self.hiddenSize
+ let length = sqrt(values[start..<(start + self.hiddenSize)].reduce(Float(0)) { $0 + $1 * $1 })
+ for d in 0..<self.hiddenSize {
+ result[start + d] /= max(length, 1e-12)
+ }
+ }
+ return Self(hiddenSize: self.hiddenSize, values: result)
+ }
+}
+
+/// No labels, settings, disk, audio capture, or model loading inside the decision layer.
+nonisolated enum DictionaryExperimentalMatcher {
+ struct Metrics: Equatable, Sendable { let mean: Float; let lower: Float }
+ struct Decision: Sendable { let accepted: Bool; let meanRelative: Float; let lowerRelative: Float }
+
+ @concurrent static func comparePositive(query: DictionaryMatchFrames, references: [DictionaryMatchFrames]) async -> Decision? {
+ self.positive(query: query, references: references)
+ }
+
+ @concurrent static func compareNegative(query: DictionaryMatchFrames, references: [DictionaryMatchFrames], negatives: [DictionaryMatchFrames]) async -> Bool {
+ self.negativeAllows(query: query, references: references, negatives: negatives)
+ }
+
+ static func metrics(reference: DictionaryMatchFrames, query: DictionaryMatchFrames) -> Metrics? {
+ guard reference.isValid, query.isValid, reference.hiddenSize == query.hiddenSize else { return nil }
+ let r = reference.normalized(), q = query.normalized()
+ let n = r.count, m = q.count, width = m + 1, hidden = r.hiddenSize
+ var sim = [Float](repeating: 0, count: n * m)
+ r.values.withUnsafeBufferPointer { rp in q.values.withUnsafeBufferPointer { qp in sim.withUnsafeMutableBufferPointer { sp in
+ guard let referencePointer = rp.baseAddress, let queryPointer = qp.baseAddress, let outputPointer = sp.baseAddress else { return }
+ cblas_sgemm(
+ CblasRowMajor,
+ CblasNoTrans,
+ CblasTrans,
+ Int32(n),
+ Int32(m),
+ Int32(hidden),
+ 1,
+ referencePointer,
+ Int32(hidden),
+ queryPointer,
+ Int32(hidden),
+ 0,
+ outputPointer,
+ Int32(m)
+ )
+ } } }
+ var cost = [Double](repeating: .infinity, count: (n + 1) * width)
+ var previous = [UInt8](repeating: 0, count: cost.count)
+ cost[0] = 0
+ for i in 1...n {
+ for j in 1...m {
+ if abs(Double(i - 1) / Double(max(1, n - 1)) - Double(j - 1) / Double(max(1, m - 1))) > 0.25 + 1 / Double(min(n, m)) { continue }
+ var best = cost[(i - 1) * width + j - 1]
+ var step: UInt8 = 0
+ let up = cost[(i - 1) * width + j] + 0.05
+ if up < best { best = up; step = 1 }
+ let left = cost[i * width + j - 1] + 0.05
+ if left < best { best = left; step = 2 }
+ cost[i * width + j] = best + 1 - Double(sim[(i - 1) * m + j - 1])
+ previous[i * width + j] = step
+ }
+ }
+ guard cost[n * width + m].isFinite else { return nil }
+ var sums = [Double](repeating: 0, count: n), counts = [Int](repeating: 0, count: n)
+ var i = n, j = m
+ while i > 0 || j > 0 {
+ guard i > 0, j > 0 else { return nil }
+ sums[i - 1] += Double(sim[(i - 1) * m + j - 1]); counts[i - 1] += 1
+ switch previous[i * width + j] {
+ case 0: i -= 1; j -= 1
+ case 1: i -= 1
+ default: j -= 1
+ }
+ }
+ guard counts.allSatisfy({ $0 > 0 }) else { return nil }
+ let values = zip(sums, counts).map { $0.0 / Double($0.1) }.sorted()
+ let index = Double(n - 1) * 0.25, lo = Int(index), hi = min(n - 1, Int(ceil(index)))
+ return Metrics(mean: Float(values.reduce(0, +) / Double(n)), lower: Float(values[lo] + (values[hi] - values[lo]) * (index - Double(lo))))
+ }
+
+ static func positive(query: DictionaryMatchFrames, references: [DictionaryMatchFrames]) -> Decision? {
+ guard references.count >= 3, references.count <= 10 else { return nil }
+ var calibration: [Metrics] = []
+ for i in references.indices {
+ for j in references.indices where i != j {
+ guard let value = metrics(reference: references[i], query: references[j]) else { return nil }
+ calibration.append(value)
+ }
+ }
+ let mean = max(0.1, calibration.map(\.mean).reduce(0, +) / Float(calibration.count))
+ let lower = max(0.1, calibration.map(\.lower).reduce(0, +) / Float(calibration.count))
+ let scores = references.compactMap { self.metrics(reference: $0, query: query) }
+ guard scores.count == references.count else { return nil }
+ let a = (scores.map(\.mean).max() ?? -1) / mean, b = (scores.map(\.lower).max() ?? -1) / lower
+ return Decision(accepted: a >= 0.70 && b >= 0.55, meanRelative: a, lowerRelative: b)
+ }
+
+ static func similarity(_ a: DictionaryMatchFrames, _ b: DictionaryMatchFrames) -> Float? {
+ guard let ab = metrics(reference: a, query: b), let ba = metrics(reference: b, query: a) else { return nil }
+ return (ab.mean + ba.mean) / 2
+ }
+
+ /// A negative may veto an existing acceptance; it can never create an acceptance.
+ static func negativeAllows(query: DictionaryMatchFrames, references: [DictionaryMatchFrames], negatives: [DictionaryMatchFrames]) -> Bool {
+ guard !negatives.isEmpty else { return true }
+ guard let positive = references.compactMap({ similarity(query, $0) }).max(),
+ let negative = negatives.compactMap({ similarity(query, $0) }).max() else { return true }
+ // Require a close negative and an advantage over every enrolled positive.
+ // One correction must not suppress a broad neighborhood of valid pronunciations.
+ return !(negative >= 0.75 && negative > positive + 0.05)
+ }
+}
diff --git a/Sources/Fluid/Services/DictionaryLearningEvidence.swift b/Sources/Fluid/Services/DictionaryLearningEvidence.swift
index 37014fcd..fc7c8811 100644
--- a/Sources/Fluid/Services/DictionaryLearningEvidence.swift
+++ b/Sources/Fluid/Services/DictionaryLearningEvidence.swift
@@ -4,6 +4,8 @@ import Foundation
nonisolated struct DictionaryLearningAlignment: Sendable {
let modelKey: String
let words: [ASRWordTiming]
+ var acousticOutput: String? = nil
+ var acousticEvidence: [DictionaryAcousticEvidence] = []
}
/// Short-lived ownership of original PCM, independent from the consume-once history snapshot.
@@ -21,6 +23,7 @@ nonisolated struct DictionaryLearningRecording: Sendable {
id: UUID = UUID(),
alignment: DictionaryLearningAlignment,
samples: [Float],
+ retainAudio: Bool = true,
now: Date = Date()
) {
guard !samples.isEmpty, samples.count <= Self.maximumSamples,
@@ -29,7 +32,8 @@ nonisolated struct DictionaryLearningRecording: Sendable {
self.id = id
self.expiresAt = now.addingTimeInterval(Self.lifetime)
self.alignment = alignment
- self.samples = samples
+ // Negative confirmation needs only accepted-word features, not the full recording PCM.
+ self.samples = retainAudio ? samples : []
}
}
diff --git a/Sources/Fluid/Services/DictionaryNegativeExamples.swift b/Sources/Fluid/Services/DictionaryNegativeExamples.swift
new file mode 100644
index 00000000..5ac81e03
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryNegativeExamples.swift
@@ -0,0 +1,129 @@
+import CryptoKit
+import Foundation
+
+nonisolated struct DictionaryAcousticEvidence: Sendable {
+ let id: UUID
+ let entryID: UUID
+ let label: String
+ let profileKey: String
+ let modelKey: String
+ let sourceWordRange: Range<Int>
+ let frames: DictionaryMatchFrames
+}
+
+nonisolated struct DictionaryNegativeCorrection: Sendable {
+ let evidence: DictionaryAcousticEvidence
+ let correctedText: String
+ let expiresAt: Date
+}
+
+nonisolated enum DictionaryNegativeEvidenceResolver {
+ static func normalized(_ text: String) -> String {
+ text.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).joined(separator: " ")
+ }
+
+ /// Only an unchanged delivered utterance and a unique, complete inserted label qualify.
+ /// Repeated names, AI rewrites, partial selections, and stale audio are deliberately ignored.
+ static func resolve(context: DictionaryLearningCorrectionContext, heard: String, corrected: String, now: Date = Date()) -> DictionaryNegativeCorrection? {
+ let alignment = context.recording.alignment
+ guard now < context.recording.expiresAt, alignment.acousticOutput == context.deliveredTextBeforeEdit,
+ !self.normalized(corrected).isEmpty, self.normalized(heard) != self.normalized(corrected) else { return nil }
+ let source = context.deliveredTextBeforeEdit as NSString
+ let selected = context.selectedUTF16Range
+ guard selected.location >= 0, selected.length > 0, selected.location <= source.length,
+ selected.length <= source.length - selected.location,
+ source.substring(with: selected).trimmingCharacters(in: .whitespacesAndNewlines.union(.punctuationCharacters)) == heard else { return nil }
+ let selectedLabel = source.range(of: heard, range: selected)
+ let eligible = alignment.acousticEvidence.filter { evidence in
+ guard evidence.label == heard, evidence.frames.isValid else { return false }
+ let range = source.range(of: evidence.label)
+ guard range == selectedLabel else { return false }
+ let after = NSMaxRange(range)
+ return source.range(of: evidence.label, range: NSRange(location: after, length: source.length - after)).location == NSNotFound
+ }
+ guard eligible.count == 1 else { return nil }
+ return DictionaryNegativeCorrection(evidence: eligible[0], correctedText: corrected, expiresAt: context.recording.expiresAt)
+ }
+
+ static func profileKey(_ profile: PronunciationDictionaryProfile) -> String {
+ // Retraining, replacement spelling, model changes, and extraction changes invalidate examples.
+ var hash = SHA256()
+ hash.update(data: Data((DictionaryMatcherExperiment.version + profile.modelKey + profile.label).utf8))
+ for e in profile.enrollments {
+ hash.update(data: Data((e.inspectionID?.uuidString ?? e.originalAudioID?.uuidString ?? "").utf8))
+ e.values.withUnsafeBytes { hash.update(data: Data($0)) }
+ }
+ return hash.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+}
+
+/// Separate, removable experimental store; never mutates positive enrollments or dictionary text.
+actor DictionaryNegativeExampleStore {
+ static let shared = DictionaryNegativeExampleStore()
+ struct Example: Codable, Sendable {
+ let id: UUID
+ let entryID: UUID
+ let profileKey: String
+ let modelKey: String
+ let frames: DictionaryMatchFrames
+ }
+
+ private let url: URL
+ private var generation = UUID()
+ private let collectionEnabled: @Sendable () -> Bool
+
+ init(
+ url: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("FluidVoice/dictionary-negative-examples-v1.plist"),
+ collectionEnabled: @escaping @Sendable () -> Bool = { DictionaryMatcherExperiment.collectNegatives }
+ ) {
+ self.url = url
+ self.collectionEnabled = collectionEnabled
+ }
+
+ func revision() -> UUID { self.generation }
+
+ private func read() throws -> [Example] {
+ guard FileManager.default.fileExists(atPath: self.url.path) else { return [] }
+ let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? Int.max
+ guard size <= 32_000_000 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let examples = try PropertyListDecoder().decode([Example].self, from: Data(contentsOf: self.url))
+ guard examples.count <= 32, examples.allSatisfy({ $0.frames.isValid }) else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ return examples
+ }
+
+ func frames(entryID: UUID, profileKey: String, modelKey: String) -> [DictionaryMatchFrames] {
+ ((try? self.read()) ?? []).filter { $0.entryID == entryID && $0.profileKey == profileKey && $0.modelKey == modelKey }.map(\.frames)
+ }
+
+ func save(_ correction: DictionaryNegativeCorrection, expectedRevision: UUID) throws {
+ guard self.generation == expectedRevision, self.collectionEnabled(), correction.expiresAt > Date() else { throw PronunciationDictionaryStoreError.staleEvidence }
+ let e = correction.evidence
+ guard e.frames.isValid else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ var all = try read()
+ if all.contains(where: { $0.id == e.id }) { return }
+ // Six examples per word; 32 globally. Only frame features are persisted, no PCM or transcript.
+ all.removeAll { $0.entryID == e.entryID && $0.profileKey != e.profileKey }
+ while all.filter({ $0.entryID == e.entryID }).count >= 6 {
+ if let index = all.firstIndex(where: { $0.entryID == e.entryID }) { all.remove(at: index) }
+ }
+ all.append(Example(id: e.id, entryID: e.entryID, profileKey: e.profileKey, modelKey: e.modelKey, frames: e.frames))
+ all = Array(all.suffix(32))
+ let encoder = PropertyListEncoder(); encoder.outputFormat = .binary
+ let data = try encoder.encode(all)
+ guard data.count <= 32_000_000 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ try FileManager.default.createDirectory(at: self.url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: self.url, options: .atomic)
+ }
+
+ func clear() throws {
+ self.generation = UUID()
+ if FileManager.default.fileExists(atPath: self.url.path) { try FileManager.default.removeItem(at: self.url) }
+ }
+
+ func remove(id: UUID) throws {
+ let all = try read().filter { $0.id != id }
+ let encoder = PropertyListEncoder(); encoder.outputFormat = .binary
+ try encoder.encode(all).write(to: self.url, options: .atomic)
+ }
+}
diff --git a/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift b/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
index 4e398ff5..e65b07bf 100644
--- a/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
+++ b/Sources/Fluid/Services/DictionaryPronunciationExperiment.swift
@@ -2,7 +2,7 @@ import Foundation
/// Local opt-in. Both switches default off in a fresh installation.
nonisolated enum DictionaryPronunciationExperiment {
- static var enabled: Bool { UserDefaults.standard.bool(forKey: "DictionaryEdgeMatchingEnabled") }
+ static var enabled: Bool { UserDefaults.standard.bool(forKey: "DictionaryEdgeMatchingEnabled") || DictionaryMatcherExperiment.positiveEnabled }
static var captureEnabled: Bool { UserDefaults.standard.bool(forKey: "DictionaryPronunciationDebugCapture") }
/// Only the outer quiet edges are removed. Internal pauses and low-energy consonants remain.
diff --git a/Sources/Fluid/Services/DictionaryTemporalEncoder.swift b/Sources/Fluid/Services/DictionaryTemporalEncoder.swift
new file mode 100644
index 00000000..71b0e341
--- /dev/null
+++ b/Sources/Fluid/Services/DictionaryTemporalEncoder.swift
@@ -0,0 +1,55 @@
+#if arch(arm64)
+import CoreML
+import FluidAudio
+import Foundation
+
+/// Uses the provider's already-loaded models; never downloads or starts an ASR decoder.
+nonisolated enum DictionaryTemporalEncoder {
+ @concurrent static func encode(_ input: [Float], models: AsrModels) async throws -> DictionaryMatchFrames {
+ guard !input.isEmpty, input.count <= 240_000, input.allSatisfy(\.isFinite), let encoder = models.encoder else {
+ throw PronunciationDictionaryStoreError.inconsistentEnrollment
+ }
+ try Task.checkCancellation()
+ let rms = sqrt(input.reduce(Double(0)) { $0 + Double($1) * Double($1) } / Double(input.count))
+ let peak = Double(input.map(abs).max() ?? 0)
+ let gain = Float(min(32, min(0.05 / max(rms, 1e-12), 0.95 / max(peak, 1e-12))))
+ let audio = try MLMultiArray(shape: [1, 240_000], dataType: .float32)
+ let pointer = audio.dataPointer.bindMemory(to: Float.self, capacity: 240_000)
+ pointer.initialize(repeating: 0, count: 240_000)
+ for i in input.indices {
+ pointer[i] = input[i] * gain
+ }
+ let length = try MLMultiArray(shape: [1], dataType: .int32)
+ length[0] = NSNumber(value: input.count)
+ let provider = try MLDictionaryFeatureProvider(dictionary: ["audio_signal": audio, "audio_length": length])
+ let pre = try await models.preprocessor.prediction(from: provider, options: AsrModels.optimizedPredictionOptions())
+ try Task.checkCancellation()
+ var fields: [String: MLFeatureValue] = [:]
+ for key in encoder.modelDescription.inputDescriptionsByName.keys {
+ fields[key] = pre.featureValue(for: key) ?? provider.featureValue(for: key)
+ }
+ let output = try await encoder.prediction(from: MLDictionaryFeatureProvider(dictionary: fields), options: AsrModels.optimizedPredictionOptions())
+ try Task.checkCancellation()
+ guard let array = output.featureValue(for: "encoder")?.multiArrayValue,
+ let encodedLength = output.featureValue(for: "encoder_length")?.multiArrayValue,
+ array.dataType == .float32, array.shape.count == 3 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let shape = array.shape.map(\.intValue), strides = array.strides.map(\.intValue)
+ let hiddenAxis = shape[1] == 1024 ? 1 : 2, timeAxis = hiddenAxis == 1 ? 2 : 1
+ guard shape[hiddenAxis] == 1024 else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let end = min(input.count, max(1, Int((Double(input.count) / 1280).rounded()) * 1280))
+ let count = min(encodedLength[0].intValue, min(shape[timeAxis], (end + 1279) / 1280))
+ guard (1...192).contains(count) else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ let data = array.dataPointer.bindMemory(to: Float.self, capacity: array.count)
+ var values: [Float] = []
+ values.reserveCapacity(count * 1024)
+ for frame in 0..<count {
+ for d in 0..<1024 {
+ values.append(data[frame * strides[timeAxis] + d * strides[hiddenAxis]])
+ }
+ }
+ let frames = DictionaryMatchFrames(hiddenSize: 1024, values: values)
+ guard frames.isValid else { throw PronunciationDictionaryStoreError.inconsistentEnrollment }
+ return frames
+ }
+}
+#endif
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index ae80dd2b..73922f79 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -72,6 +72,11 @@ final class FluidAudioProvider: TranscriptionProvider {
let label: String
}
+ struct TemporalMatchKey: Hashable {
+ let prototypeIndex: Int
+ let frameRange: Range<Int>
+ }
+
static func dictionaryLabels(
from entries: [SettingsStore.CustomDictionaryEntry]
) -> [UUID: String] {
@@ -115,6 +120,8 @@ final class FluidAudioProvider: TranscriptionProvider {
private var boostedTermLookup: [String] = []
private var pronunciationModelKey = ""
private var edgeReferenceCache: [UUID: PronunciationEmbedding] = [:]
+ private var temporalModels: AsrModels?
+ private var temporalReferenceCache: [String: [DictionaryMatchFrames]] = [:]
/// Optional model override - if set, uses this model instead of the global setting.
/// Used for downloading specific models without changing the active selection.
@@ -296,6 +303,7 @@ final class FluidAudioProvider: TranscriptionProvider {
source: "FluidAudioProvider"
)
+ self.temporalModels = models
// Streaming manager: lightweight, no vocab boosting → avoids CTC/ANE contention
// that causes intermittent SIGTRAP crashes during streaming inference.
let streamingManager = AsrManager(config: ASRConfig.default)
@@ -698,8 +706,11 @@ final class FluidAudioProvider: TranscriptionProvider {
includeManual: self.explicitPronunciationMatchingEnabled,
includeOriginal: SettingsStore.shared.automaticDictionaryLearningEnabled
).map(\.dictionaryEntryID))
+ var acousticEvidence: [DictionaryAcousticEvidence] = []
+ var acceptedEvidence: [DictionaryAcousticEvidence] = []
+ var temporalMatches: Set<TemporalMatchKey> = []
if let manager = self.finalAsrManager ?? self.streamingAsrManager, originalText == result.text {
- matches = try await self.refineEdgeMatches(matches, profiles: profiles, samples: samples, manager: manager, transcript: result.text, timings: result.tokenTimings ?? [])
+ matches = try await self.refineEdgeMatches(matches, profiles: profiles, samples: samples, manager: manager, transcript: result.text, timings: result.tokenTimings ?? [], evidence: &acousticEvidence, temporalMatches: &temporalMatches)
}
try self.requireCurrentRecording(generation)
let text = self.effectivePronunciationMatchingEnabled && originalText == result.text
@@ -707,7 +718,11 @@ final class FluidAudioProvider: TranscriptionProvider {
result: result,
matches: matches,
profiles: profiles,
- labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries).filter { eligibleIDs.contains($0.key) }
+ labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries).filter { eligibleIDs.contains($0.key) },
+ temporalMatches: temporalMatches,
+ onAccepted: { id, label, range in
+ acceptedEvidence += acousticEvidence.filter { $0.entryID == id && $0.label == label && $0.sourceWordRange == range }
+ }
) : result.text
let finishFinishedAt = ProcessInfo.processInfo.systemUptime
DebugLogger.shared.debug(
@@ -717,9 +732,10 @@ final class FluidAudioProvider: TranscriptionProvider {
"finishMs=\(Self.milliseconds(from: appendFinishedAt, to: finishFinishedAt))",
source: "ASRBenchmark"
)
- return ASRTranscriptionResult(
- text: text, confidence: result.confidence, dictionaryLearningAlignment: self.learningAlignment(for: result)
- )
+ var alignment = self.learningAlignment(for: result)
+ alignment?.acousticOutput = text
+ alignment?.acousticEvidence = acceptedEvidence
+ return ASRTranscriptionResult(text: text, confidence: result.confidence, dictionaryLearningAlignment: alignment)
}
private static func milliseconds(from start: TimeInterval, to end: TimeInterval) -> String {
@@ -821,7 +837,7 @@ final class FluidAudioProvider: TranscriptionProvider {
}
private func learningAlignment(for result: ASRResult) -> DictionaryLearningAlignment? {
- guard SettingsStore.shared.automaticDictionaryLearningEnabled, !self.isWordBoostingActive,
+ guard SettingsStore.shared.automaticDictionaryLearningEnabled || DictionaryMatcherExperiment.collectNegatives, !self.isWordBoostingActive,
let timings = result.tokenTimings, !timings.isEmpty
else { return nil }
return DictionaryLearningAlignment(modelKey: self.pronunciationModelKey, words: Self.makeWordTimings(from: timings))
@@ -859,14 +875,37 @@ final class FluidAudioProvider: TranscriptionProvider {
).enumerated().flatMap { index, hits in
hits.map { PronunciationWindowMatch(prototypeIndex: index, score: $0.score, frameRange: $0.frameRange) }
}
- let refined = try await self.refineEdgeMatches(matches, profiles: references.map(\.profile), samples: samples, manager: manager, transcript: result.text, timings: result.tokenTimings ?? [])
- let corrected = Self.applyPronunciationMatches(result: result, matches: refined, profiles: references.map(\.profile), labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries))
+ var acousticEvidence: [DictionaryAcousticEvidence] = []
+ var acceptedEvidence: [DictionaryAcousticEvidence] = []
+ var temporalMatches: Set<TemporalMatchKey> = []
+ let refined = try await self.refineEdgeMatches(
+ matches,
+ profiles: references.map(\.profile),
+ samples: samples,
+ manager: manager,
+ transcript: result.text,
+ timings: result.tokenTimings ?? [],
+ evidence: &acousticEvidence,
+ temporalMatches: &temporalMatches
+ )
+ let corrected = Self.applyPronunciationMatches(
+ result: result,
+ matches: refined,
+ profiles: references.map(\.profile),
+ labels: Self.dictionaryLabels(from: self.effectiveCustomDictionaryEntries),
+ temporalMatches: temporalMatches,
+ onAccepted: { id, label, range in
+ acceptedEvidence += acousticEvidence.filter { $0.entryID == id && $0.label == label && $0.sourceWordRange == range }
+ })
let elapsedMs = Int(((Date().timeIntervalSince1970 - startedAt) * 1000).rounded())
DebugLogger.shared.info(
"PRONUNCIATION_MATCH profiles=\(profiles.count) elapsedMs=\(elapsedMs) changed=\(corrected != result.text)",
source: "PronunciationMatching"
)
- return (ASRTranscriptionResult(text: corrected, confidence: result.confidence, dictionaryLearningAlignment: self.learningAlignment(for: result)), result.tokenTimings, textMayBeCorrected)
+ var alignment = self.learningAlignment(for: result)
+ alignment?.acousticOutput = corrected
+ alignment?.acousticEvidence = acceptedEvidence
+ return (ASRTranscriptionResult(text: corrected, confidence: result.confidence, dictionaryLearningAlignment: alignment), result.tokenTimings, textMayBeCorrected)
} catch {
_ = await manager.consumePronunciationEncoderFeatures()
await manager.setPronunciationCustomizationEnabled(false)
@@ -901,13 +940,17 @@ final class FluidAudioProvider: TranscriptionProvider {
return prepared
}
+ // Carry both frame decisions and exact accepted evidence through this bounded refinement pass.
+ // swiftlint:disable:next function_parameter_count
private func refineEdgeMatches(
_ matches: [PronunciationWindowMatch],
profiles: [PronunciationDictionaryProfile],
samples: [Float],
manager: AsrManager,
transcript: String,
- timings: [TokenTiming]
+ timings: [TokenTiming],
+ evidence: inout [DictionaryAcousticEvidence],
+ temporalMatches: inout Set<TemporalMatchKey>
) async throws -> [PronunciationWindowMatch] {
let calibrated = profiles.map(\.edgeCalibration)
var output = matches.filter { calibrated.indices.contains($0.prototypeIndex) && calibrated[$0.prototypeIndex] == nil }
@@ -916,6 +959,14 @@ final class FluidAudioProvider: TranscriptionProvider {
let wordIndex = WordAudioOverlapIndex(words: words)
var used: [Int: [Range<Int>]] = [:]
var encoded: [Range<Int>: PronunciationEmbedding] = [:]
+ let positiveEnabled = DictionaryMatcherExperiment.positiveEnabled
+ let compareNegatives = DictionaryMatcherExperiment.compareNegatives
+ let collectNegatives = DictionaryMatcherExperiment.collectNegatives
+ let needsFrames = positiveEnabled || compareNegatives || collectNegatives
+ if !needsFrames { self.temporalReferenceCache.removeAll() }
+ var temporalEncoded: [Range<Int>: DictionaryMatchFrames] = [:]
+ var negativeFrames: [String: [DictionaryMatchFrames]] = [:]
+ let negativeRevision = compareNegatives ? await DictionaryNegativeExampleStore.shared.revision() : nil
// Bounded experimental reranking: up to three non-overlapping candidates per word, 24 encoder calls total.
for match in matches.sorted(by: { $0.score > $1.score }) {
try Task.checkCancellation()
@@ -954,6 +1005,48 @@ final class FluidAudioProvider: TranscriptionProvider {
used[match.prototypeIndex, default: []].append(range)
let raw = zip(embedding.values, calibration.center).reduce(Float(0)) { $0 + $1.0 * $1.1 }
let relative = raw / calibration.baseline
+ if needsFrames, let models = self.temporalModels {
+ let profile = profiles[match.prototypeIndex]
+ let key = DictionaryNegativeEvidenceResolver.profileKey(profile)
+ do {
+ let query: DictionaryMatchFrames
+ if let cached = temporalEncoded[trimmed] { query = cached } else {
+ query = try await DictionaryTemporalEncoder.encode(Array(samples[trimmed]), models: models)
+ temporalEncoded[trimmed] = query
+ }
+ if compareNegatives, negativeFrames[key] == nil {
+ negativeFrames[key] = await DictionaryNegativeExampleStore.shared.frames(entryID: profile.dictionaryEntryID, profileKey: key, modelKey: profile.modelKey)
+ }
+ let needsReferences = positiveEnabled || (compareNegatives && !(negativeFrames[key] ?? []).isEmpty)
+ let references = needsReferences ? try await self.temporalReferences(profile, key: key, models: models) : []
+ if positiveEnabled, let decision = await DictionaryExperimentalMatcher.comparePositive(query: query, references: references), DictionaryMatcherExperiment.positiveEnabled {
+ DebugLogger.shared.info("DICTIONARY_EXPERIMENT mode=positive accepted=\(decision.accepted) mean=\(decision.meanRelative) lower=\(decision.lowerRelative)", source: "PronunciationMatching")
+ guard decision.accepted else { continue }
+ temporalMatches.insert(TemporalMatchKey(prototypeIndex: match.prototypeIndex, frameRange: alignedFrames))
+ }
+ if compareNegatives, DictionaryMatcherExperiment.compareNegatives {
+ let allowed = await DictionaryExperimentalMatcher.compareNegative(query: query, references: references, negatives: negativeFrames[key] ?? [])
+ DebugLogger.shared.info("DICTIONARY_EXPERIMENT mode=negative allowed=\(allowed) examples=\(negativeFrames[key]?.count ?? 0)", source: "PronunciationMatching")
+ if !allowed, DictionaryMatcherExperiment.compareNegatives,
+ await DictionaryNegativeExampleStore.shared.revision() == negativeRevision { continue }
+ }
+ if collectNegatives, DictionaryMatcherExperiment.collectNegatives {
+ evidence.append(DictionaryAcousticEvidence(
+ id: UUID(),
+ entryID: profile.dictionaryEntryID,
+ label: profile.label,
+ profileKey: key,
+ modelKey: profile.modelKey,
+ sourceWordRange: first..<(last + 1),
+ frames: query
+ ))
+ }
+ } catch {
+ if error is CancellationError || Task.isCancelled { throw CancellationError() }
+ // An unavailable experiment must preserve the legacy decision, never fabricate evidence.
+ DebugLogger.shared.warning("Experimental dictionary comparison unavailable; using existing matcher", source: "PronunciationMatching")
+ }
+ }
output.append(PronunciationWindowMatch(prototypeIndex: match.prototypeIndex, score: relative, frameRange: alignedFrames))
reports.append(.init(
word: profiles[match.prototypeIndex].label,
@@ -976,6 +1069,21 @@ final class FluidAudioProvider: TranscriptionProvider {
return output
}
+ private func temporalReferences(_ profile: PronunciationDictionaryProfile, key: String, models: AsrModels) async throws -> [DictionaryMatchFrames] {
+ if let cached = self.temporalReferenceCache[key] { return cached }
+ guard profile.enrollments.count >= 3 else { return [] }
+ var result: [DictionaryMatchFrames] = []
+ for capture in profile.enrollments.prefix(3) {
+ guard let id = capture.inspectionID,
+ let audio = try? await self.pronunciationStore.inspection(for: id),
+ let range = DictionaryPronunciationExperiment.trimmedRange(Array(audio.samples.prefix(audio.recordedSampleCount))) else { return [] }
+ try result.append(await DictionaryTemporalEncoder.encode(Array(audio.samples[range]), models: models))
+ }
+ if self.temporalReferenceCache.count >= 8 { self.temporalReferenceCache.removeAll(keepingCapacity: true) }
+ self.temporalReferenceCache[key] = result
+ return result
+ }
+
private func makeEnrollment(
result: ASRResult,
features: EncoderFeatureSequence?,
@@ -997,7 +1105,7 @@ final class FluidAudioProvider: TranscriptionProvider {
modelKey: self.pronunciationModelKey
)
if samples.count <= 16_000 * 15,
- DictionaryPronunciationExperiment.captureEnabled
+ DictionaryPronunciationExperiment.captureEnabled || DictionaryMatcherExperiment.needsFrames
{
capture.pendingInspection = DictionaryAudioInspection(
samples: samples,
@@ -1015,7 +1123,9 @@ final class FluidAudioProvider: TranscriptionProvider {
result: ASRResult,
matches: [PronunciationWindowMatch],
profiles: [PronunciationDictionaryProfile],
- labels: [UUID: String]
+ labels: [UUID: String],
+ temporalMatches: Set<TemporalMatchKey> = [],
+ onAccepted: ((UUID, String, Range<Int>) -> Void)? = nil
) -> String {
guard let timings = result.tokenTimings else { return result.text }
let words = WordAudioChunkExtractor.words(from: timings)
@@ -1046,7 +1156,8 @@ final class FluidAudioProvider: TranscriptionProvider {
guard !indices.isEmpty else { continue }
let profile = profiles[match.prototypeIndex]
let heard = indices.map { words[$0].text }.joined(separator: " ")
- guard DictionaryPronunciationDecision.accepts(score: match.score, heardText: heard, profile: profile) else { continue }
+ let temporalAccepted = temporalMatches.contains(TemporalMatchKey(prototypeIndex: match.prototypeIndex, frameRange: match.frameRange))
+ guard temporalAccepted || DictionaryPronunciationDecision.accepts(score: match.score, heardText: heard, profile: profile) else { continue }
var correctedLabel = label
if profile.hasOriginalAudio {
guard profile.label.caseInsensitiveCompare(label) == .orderedSame else { continue }
@@ -1087,7 +1198,7 @@ final class FluidAudioProvider: TranscriptionProvider {
claimed.formUnion(candidate.wordIndices)
if accepted.count <= DictionaryReplacementDiagnostics.maximumEvents {
let heard = candidate.wordIndices.map { words[$0].text }.joined(separator: " ")
- DebugLogger.shared.debug(
+ DebugLogger.shared.info(
"PRONUNCIATION_HIT stage=acoustic_candidate entryID=\(candidate.entryID) " +
"score=\(String(format: "%.3f", candidate.score)) " +
"threshold=\(candidate.threshold) " +
@@ -1102,6 +1213,10 @@ final class FluidAudioProvider: TranscriptionProvider {
let replacements = accepted.compactMap { candidate -> PronunciationTextReplacement? in
guard let first = candidate.wordIndices.first, let last = candidate.wordIndices.last else { return nil }
+ let heard = candidate.wordIndices.map { words[$0].text }.joined(separator: " ")
+ if DictionaryNegativeEvidenceResolver.normalized(heard) != DictionaryNegativeEvidenceResolver.normalized(candidate.label) {
+ onAccepted?(candidate.entryID, candidate.label, first..<(last + 1))
+ }
return PronunciationTextReplacement(wordRange: first...last, label: candidate.label)
}
return Self.applyingPronunciationReplacements(
@@ -1235,6 +1350,8 @@ final class FluidAudioProvider: TranscriptionProvider {
self.isReady = false
self.streamingAsrManager = nil
self.finalAsrManager = nil
+ self.temporalModels = nil
+ self.temporalReferenceCache.removeAll()
self.isWordBoostingActive = false
self.boostedVocabularyTermsCount = 0
self.boostedTermLookup = []
diff --git a/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift b/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift
index 01a1ac78..540fe593 100644
--- a/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift
+++ b/Sources/Fluid/UI/DictionaryMatchDiagnosticsView.swift
@@ -26,7 +26,11 @@ struct DictionaryMatchDiagnosticsView: View {
var body: some View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
-
+ if DictionaryMatcherExperiment.positiveEnabled || DictionaryMatcherExperiment.compareNegatives {
+ Text("Experimental comparisons are enabled. Replay scores below show the original matcher; use live dictation to compare results. This cutoff controls fallback matching.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
HStack {
Text(self.running ? "Checking this recording…" : "Pronunciation match")
.font(self.theme.typography.bodyStrong)
diff --git a/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift b/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift
new file mode 100644
index 00000000..9e6c7ea5
--- /dev/null
+++ b/Sources/Fluid/UI/DictionaryMatcherExperimentSettings.swift
@@ -0,0 +1,43 @@
+import SwiftUI
+
+struct DictionaryMatcherExperimentSettings: View {
+ @Environment(\.theme) private var theme
+ @AppStorage("DictionaryTemporalMatcherEnabled") private var temporal = false
+ @AppStorage("DictionaryNegativeLearningEnabled") private var learning = false
+ @AppStorage("DictionaryNegativeComparisonEnabled") private var comparison = false
+ @State private var clearing = false
+ @State private var message = ""
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Label("Dictionary matching experiments", systemImage: "waveform.badge.magnifyingglass")
+ .font(self.theme.typography.bodyStrong)
+ Toggle("Compare the whole pronunciation", isOn: self.$temporal)
+ Text("Checks the whole word using three voice recordings. Parakeet only. These experiments keep new voice-training recordings locally; words without saved audio use existing matching until you record them again.")
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
+ Toggle("Learn from confirmed wrong matches", isOn: self.$learning)
+ Text("After you edit an inserted word, confirm whether you said a different word. Saves only audio features locally. Requires the whole-pronunciation experiment (or legacy edge matching) and an app that supports correction detection.")
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
+ Toggle("Use saved wrong-match examples", isOn: self.$comparison)
+ Text("Rejects a close match to a confirmed mistake. You can collect examples with this switched off, or disable either comparison at any time.")
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
+ Button("Clear wrong-match examples", role: .destructive) {
+ self.clearing = true
+ Task {
+ defer { clearing = false }
+ do {
+ try await DictionaryNegativeExampleStore.shared.clear()
+ self.message = "Wrong-match examples cleared. Your dictionary and voice recordings are unchanged."
+ } catch { self.message = "Couldn’t clear examples: \(error.localizedDescription)" }
+ }
+ }
+ .fluidGlassAction()
+ .disabled(self.clearing)
+ if !self.message.isEmpty {
+ Text(self.message).font(self.theme.typography.caption).foregroundStyle(.secondary)
+ }
+ Text("All three experiments are off by default. Turning them off restores the existing matcher. These are experimental comparisons, not guaranteed improvements.")
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/SettingsSearch.swift b/Sources/Fluid/UI/SettingsSearch.swift
index 94663199..a3ed4dc4 100644
--- a/Sources/Fluid/UI/SettingsSearch.swift
+++ b/Sources/Fluid/UI/SettingsSearch.swift
@@ -68,6 +68,7 @@ enum SettingsSearchTarget: Hashable {
case experimental
case returnToStartingField
case fasterLongDictation
+ case dictionaryMatcherExperiments
case historyPerformance
var section: SettingsSection {
@@ -124,7 +125,7 @@ enum SettingsSearchTarget: Hashable {
case .dataAndDiagnostics, .backupAndRestore, .debugLogs:
return .dataAndDiagnostics
- case .experimental, .returnToStartingField, .fasterLongDictation, .historyPerformance:
+ case .experimental, .returnToStartingField, .fasterLongDictation, .dictionaryMatcherExperiments, .historyPerformance:
return .experimental
}
}
@@ -439,6 +440,11 @@ enum SettingsSearchIndex {
title: "Experimental",
terms: ["preview early access optional features"]
),
+ .init(
+ target: .dictionaryMatcherExperiments,
+ title: "Dictionary Matching Experiments",
+ terms: ["pronunciation positive negative false match correction learn examples clear experimental"]
+ ),
.init(
target: .historyPerformance,
title: "Show Performance in History",
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 71f64832..ea98c541 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -1593,6 +1593,12 @@ struct SettingsView: View {
Divider().padding(.vertical, 4)
+ DictionaryMatcherExperimentSettings()
+ .disabled(self.asr.isRunningOrStarting)
+ .settingsSearchTarget(.dictionaryMatcherExperiments)
+
+ Divider().padding(.vertical, 4)
+
self.settingsToggleRow(
title: "Faster Long Dictation",
description: "For long recordings, reuse completed live windows and process only the remaining tail when you stop.",
diff --git a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
index da877c5a..4087e8cd 100644
--- a/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
+++ b/Sources/Fluid/Views/AutomaticDictionaryCorrectionOverlay.swift
@@ -667,16 +667,21 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {
private var choiceContent: some View {
VStack(alignment: .leading, spacing: 10) {
- self.header(title: "Learn this word?", allowsBack: false)
+ self.header(title: self.session.candidate.negativeCorrection == nil ? "Learn this word?" : "Was this a wrong match?", allowsBack: false)
self.correctionPair
- Text("Save only this correction, or teach FluidVoice other pronunciations.")
+ Text(self.session.candidate.negativeCorrection == nil ? "Save only this correction, or teach FluidVoice other pronunciations." : "Confirm only if you said a different word, not a spelling change.")
.font(.fluidSystem(size: 11))
.foregroundStyle(.white.opacity(0.58))
.lineLimit(1)
HStack(spacing: 8) {
+ if self.session.candidate.negativeCorrection != nil {
+ CorrectionOverlayActionButton(title: "That Was a Wrong Match", systemImage: "xmark.circle", style: .accent, accent: self.accent, action: self.session.confirmWrongMatch)
+ .disabled(self.session.capturePhase != .idle)
+ CorrectionOverlayActionButton(title: "Ignore", systemImage: "minus", style: .secondary, accent: self.accent, action: self.onIgnore)
+ } else {
CorrectionOverlayActionButton(
title: "Train by Voice",
systemImage: "mic.fill",
@@ -694,6 +699,10 @@ private struct AutomaticDictionaryCorrectionOverlayView: View {
)
self.moreOptionsMenu
+ }
+ }
+ if self.session.hasError {
+ Text(self.session.statusMessage).font(.fluidSystem(size: 11)).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
}
}
.transition(.opacity)
diff --git a/Tests/Standalone/DictionaryMatcherExperimentTests.swift b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
new file mode 100644
index 00000000..c2987d3d
--- /dev/null
+++ b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
@@ -0,0 +1,116 @@
+#if DICTIONARY_EXPERIMENT_STANDALONE
+import Foundation
+
+// Minimal surrounding types; the matcher, resolver and persistence implementations under test are production sources.
+struct ASRWordTiming: Sendable { let text: String; let start: Double; let end: Double }
+struct PronunciationEnrollmentCapture { let inspectionID: UUID?; let originalAudioID: UUID?; let values: [Float] }
+struct PronunciationDictionaryProfile { let modelKey: String; let label: String; let enrollments: [PronunciationEnrollmentCapture] }
+enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, staleEvidence }
+
+@main struct DictionaryMatcherExperimentTests {
+ static var checks = 0
+ static func expect(_ condition: Bool, _ message: String) {
+ self.checks += 1
+ if !condition { fatalError(message) }
+ }
+
+ static func main() async throws {
+ let positive = DictionaryMatchFrames(hiddenSize: 2, values: [1, 0, 1, 0, 1, 0])
+ let negative = DictionaryMatchFrames(hiddenSize: 2, values: [0, 1, 0, 1, 0, 1])
+ let refs = [positive, positive, positive]
+ self.expect(DictionaryExperimentalMatcher.positive(query: positive, references: refs)?.accepted == true, "Accept identical positives")
+ self.expect(DictionaryExperimentalMatcher.positive(query: negative, references: refs)?.accepted == false, "Reject a different sequence")
+ self.expect(DictionaryExperimentalMatcher.positive(query: positive, references: [positive]) == nil, "Missing enrollments fallback")
+ self.expect(DictionaryExperimentalMatcher.metrics(reference: positive, query: .init(hiddenSize: 2, values: [.nan, 0])) == nil, "Reject nonfinite values")
+ self.expect(!DictionaryMatchFrames(hiddenSize: 2, values: []).isValid, "Reject empty frames")
+ self.expect(!DictionaryMatchFrames(hiddenSize: 2, values: [1, 0, 1]).isValid, "Reject inconsistent dimensions")
+ self.expect(!DictionaryMatchFrames(hiddenSize: 1025, values: [Float](repeating: 1, count: 1025)).isValid, "Bound hidden size")
+ self.expect(!DictionaryMatchFrames(hiddenSize: 1, values: [Float](repeating: 1, count: 193)).isValid, "Bound duration")
+ self.expect(DictionaryExperimentalMatcher.negativeAllows(query: positive, references: refs, negatives: []), "Empty bank is inert")
+ self.expect(DictionaryExperimentalMatcher.negativeAllows(query: positive, references: refs, negatives: [positive]), "One correction cannot veto equally strong positives")
+ self.expect(!DictionaryExperimentalMatcher.negativeAllows(query: negative, references: refs, negatives: [negative]), "Close negative with margin vetoes")
+ self.expect(DictionaryExperimentalMatcher.negativeAllows(query: positive, references: refs, negatives: [negative]), "Unrelated negative is inert")
+ let now = Date(), entry = UUID()
+ let evidence = DictionaryAcousticEvidence(id: UUID(), entryID: entry, label: "Manimekalai", profileKey: "profile", modelKey: "parakeet-v2", sourceWordRange: 1..<2, frames: positive)
+ func context(_ text: String = "Hello Manimekalai today", events: [DictionaryAcousticEvidence]? = nil, date: Date? = nil, selected: String = "Manimekalai") -> DictionaryLearningCorrectionContext {
+ let alignment = DictionaryLearningAlignment(modelKey: "parakeet-v2", words: [.init(text: "raw", start: 0, end: 1)], acousticOutput: text, acousticEvidence: events ?? [evidence])
+ let recording = DictionaryLearningRecording(alignment: alignment, samples: [0.1, 0.1], now: date ?? now)!
+ return .init(recording: recording, deliveredTextBeforeEdit: text, selectedUTF16Range: (text as NSString).range(of: selected))
+ }
+ let correction = DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "another", now: now)!
+ self.expect(correction.evidence.id == evidence.id, "Keep exact accepted occurrence")
+ let featureOnly = DictionaryLearningRecording(alignment: context().recording.alignment, samples: [0.1], retainAudio: false, now: now)!
+ self.expect(featureOnly.samples.isEmpty && featureOnly.alignment.acousticEvidence.count == 1, "Negative-only observation does not retain full PCM")
+ let punctuated = context("Hello Manimekalai.")
+ let punctuationContext = DictionaryLearningCorrectionContext(recording: punctuated.recording, deliveredTextBeforeEdit: punctuated.deliveredTextBeforeEdit, selectedUTF16Range: NSRange(location: 6, length: 12))
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: punctuationContext, heard: "Manimekalai", corrected: "another", now: now) != nil, "Sentence punctuation still maps to the exact occurrence")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "MANIMEKALAI!", now: now) == nil, "Case and punctuation are not negative examples")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "", now: now) == nil, "Deletion is ambiguous")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(events: []), heard: "Manimekalai", corrected: "other", now: now) == nil, "No acoustic acceptance means no negative")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context("Manimekalai and Manimekalai"), heard: "Manimekalai", corrected: "other", now: now) == nil, "Repeated names are ambiguous")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(selected: "Mani"), heard: "Mani", corrected: "other", now: now) == nil, "Partial label edit is ambiguous")
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(date: now.addingTimeInterval(-121)), heard: "Manimekalai", corrected: "other", now: now) == nil, "Expired recording rejected")
+ let changed = DictionaryLearningCorrectionContext(recording: context().recording, deliveredTextBeforeEdit: "Hello Manimekalai tomorrow", selectedUTF16Range: NSRange(location: 6, length: 11))
+ self.expect(DictionaryNegativeEvidenceResolver.resolve(context: changed, heard: "Manimekalai", corrected: "other", now: now) == nil, "AI rewriting invalidates mapping")
+
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let url = folder.appendingPathComponent("negative.plist")
+ let store = DictionaryNegativeExampleStore(url: url, collectionEnabled: { true })
+ let revision = await store.revision()
+ try await store.save(correction, expectedRevision: revision)
+ try await store.save(correction, expectedRevision: revision)
+ let saved = await store.frames(entryID: entry, profileKey: "profile", modelKey: "parakeet-v2")
+ self.expect(saved.count == 1, "Duplicate event only saved once")
+ let wrongModel = await store.frames(entryID: entry, profileKey: "profile", modelKey: "parakeet-v3")
+ self.expect(wrongModel.isEmpty, "Model isolation")
+ let retrained = await store.frames(entryID: entry, profileKey: "changed", modelKey: "parakeet-v2")
+ self.expect(retrained.isEmpty, "Retraining invalidates old negatives")
+ for _ in 0..<10 {
+ let e = DictionaryAcousticEvidence(id: UUID(), entryID: entry, label: evidence.label, profileKey: "profile", modelKey: evidence.modelKey, sourceWordRange: 1..<2, frames: positive)
+ try await store.save(.init(evidence: e, correctedText: "other", expiresAt: now.addingTimeInterval(120)), expectedRevision: revision)
+ }
+ let bounded = await store.frames(entryID: entry, profileKey: "profile", modelKey: "parakeet-v2")
+ self.expect(bounded.count == 6, "Per-word bank bounded")
+ for _ in 0..<40 {
+ let e = DictionaryAcousticEvidence(id: UUID(), entryID: UUID(), label: evidence.label, profileKey: "profile", modelKey: evidence.modelKey, sourceWordRange: 1..<2, frames: positive)
+ try await store.save(.init(evidence: e, correctedText: "other", expiresAt: now.addingTimeInterval(120)), expectedRevision: revision)
+ }
+ let persisted = try PropertyListDecoder().decode([DictionaryNegativeExampleStore.Example].self, from: Data(contentsOf: url))
+ self.expect(persisted.count == 32, "Global bank bounded")
+ do {
+ try await store.save(.init(evidence: evidence, correctedText: "other", expiresAt: .distantPast), expectedRevision: revision)
+ fatalError("Expired confirmation saved")
+ } catch { self.checks += 1 }
+ let disabled = DictionaryNegativeExampleStore(url: url, collectionEnabled: { false })
+ do { try await disabled.save(correction, expectedRevision: await disabled.revision()); fatalError("Disabled collection wrote") } catch { self.checks += 1 }
+ try await store.clear()
+ do { try await store.save(correction, expectedRevision: revision); fatalError("Stale save survived clear") } catch { self.checks += 1 }
+ self.expect(!FileManager.default.fileExists(atPath: url.path), "Clear removes store")
+ let invalid = Data("broken".utf8)
+ try invalid.write(to: url)
+ let corrupt = await store.frames(entryID: entry, profileKey: "profile", modelKey: "parakeet-v2")
+ self.expect(corrupt.isEmpty, "Corrupt optional bank cannot veto")
+ if CommandLine.arguments.count > 1 { try self.parity(CommandLine.arguments[1]) }
+ print("Dictionary experiments: \(self.checks) checks passed")
+ }
+
+ static func parity(_ path: String) throws {
+ struct Clip: Decodable { let id: String; let word: String; let values: [Float] }
+ struct Input: Decodable { let enrollments: [Clip]; let queries: [Clip] }
+ struct Decision: Decodable { let id: String; let combinedAccepted: Bool; let meanRelative: Float; let lowerRelative: Float }
+ struct Report: Decodable { let decisions: [Decision] }
+ let root = URL(fileURLWithPath: path)
+ let input = try JSONDecoder().decode(Input.self, from: Data(contentsOf: root.appendingPathComponent("native-input.json")))
+ let report = try JSONDecoder().decode(Report.self, from: Data(contentsOf: root.appendingPathComponent("native-report.json")))
+ let expected = Dictionary(uniqueKeysWithValues: report.decisions.map { ($0.id, $0) })
+ for q in input.queries {
+ let refs = input.enrollments.filter { $0.word == q.word }.map { DictionaryMatchFrames(hiddenSize: 1024, values: $0.values) }
+ let d = DictionaryExperimentalMatcher.positive(query: .init(hiddenSize: 1024, values: q.values), references: refs)!
+ let e = expected[q.id]!
+ self.expect(d.accepted == e.combinedAccepted, "Production scorer parity \(q.id)")
+ self.expect(abs(d.meanRelative - e.meanRelative) < 0.00_001 && abs(d.lowerRelative - e.lowerRelative) < 0.00_001, "Production score tolerance \(q.id)")
+ }
+ }
+}
+#endif
diff --git a/Tests/run_dictionary_matcher_experiment_tests.sh b/Tests/run_dictionary_matcher_experiment_tests.sh
new file mode 100644
index 00000000..f20a080d
--- /dev/null
+++ b/Tests/run_dictionary_matcher_experiment_tests.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+set -eu
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+case "$task_developer_dir" in
+ */Xcode*.app/Contents/Developer) ;;
+ *) echo "Set DEVELOPER_DIR to an installed full Xcode." >&2; exit 1 ;;
+esac
+export DEVELOPER_DIR="$task_developer_dir"
+task_repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
+task_test_dir=$(mktemp -d /tmp/fluidvoice-dictionary-tests.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -D DICTIONARY_EXPERIMENT_STANDALONE -O -parse-as-library \
+ "$task_repo_dir/Sources/Fluid/Services/DictionaryExperimentalMatcher.swift" \
+ "$task_repo_dir/Sources/Fluid/Services/DictionaryNegativeExamples.swift" \
+ "$task_repo_dir/Sources/Fluid/Services/DictionaryLearningEvidence.swift" \
+ "$task_repo_dir/Tests/Standalone/DictionaryMatcherExperimentTests.swift" \
+ -o "$task_test_dir/tests"
+"$task_test_dir/tests" "$@"
diff --git a/docs/dictionary-matcher-experiments.md b/docs/dictionary-matcher-experiments.md
new file mode 100644
index 00000000..7c3ed063
--- /dev/null
+++ b/docs/dictionary-matcher-experiments.md
@@ -0,0 +1,62 @@
+# Dictionary matcher experiments
+
+All options live under **Settings → Experimental → Dictionary matching experiments**, are searchable, and default to off. This is an optional test implementation, not a production accuracy claim.
+
+## Correction flow
+
+1. Parakeet accepts an acoustic match and actually replaces a spoken word with a dictionary label.
+2. The provider attaches the accepted occurrence's entry ID, source word range, model/profile identity, and normalized audio features to that dictation's short-lived learning context.
+3. After external text delivery, the existing correction observer sees the user edit the inserted label.
+4. Only a unique, complete label in unchanged delivered text can be linked. No mapping means no negative example. Repeated labels, expired contexts, AI rewrites, partial edits, case-only edits and punctuation-only edits are ignored. Ordinary edits to a dictionary entry are not evidence of a spoken false positive.
+5. The correction overlay asks **Was this a wrong match?** Choose **That Was a Wrong Match** only when a different word was spoken. A spelling/style edit is not automatically a false positive.
+6. Confirmation stores only that occurrence's audio features. It does not add a text replacement, modify a positive enrollment, or enroll the corrected text as a new word.
+7. With negative comparison enabled, future matching can veto a close match to the confirmed mistake. A single negative does not necessarily generalize to other mistakes.
+
+Collection works with the positive whole-pronunciation experiment or the existing legacy edge matcher, and only for occurrences that reach the acoustic replacement path. It does not watch arbitrary edits or retroactively mine history. The existing correction observer requires Accessibility support in the receiving app. Internal dictionary playground edits are not automatically connected to this external correction observer.
+
+## Independent switches
+
+| Switch | Behavior |
+|---|---|
+| Compare the whole pronunciation | Original three positive training recordings; normalized frames, ordered alignment, calibrated mean and lower-quartile checks. Missing reference audio falls back to existing matching. |
+| Learn from confirmed wrong matches | Offers the wrong-match confirmation after an attributable correction. Does not itself change acceptance decisions. |
+| Use saved wrong-match examples | Optional veto after an otherwise accepted candidate. No examples is a no-op. It never creates a new acceptance. |
+| Clear wrong-match examples | Deletes the separate example store and invalidates older pending saves. Leaves dictionary entries and positive recordings untouched. |
+
+Turning all three switches off restores the pre-existing matcher configuration. The existing independent `DictionaryEdgeMatchingEnabled` preference is preserved. No preferences are enabled by this implementation.
+
+With experiments enabled, new voice enrollments retain their original training audio locally so the positive frames can be rebuilt. Existing words without that audio keep their prior matcher until re-recorded. Negative correction learning itself persists features only, not PCM or corrected text. When automatic positive learning is off, the correction observer does not retain the full dictation PCM for negative learning.
+
+## Algorithm and compatibility
+
+- Positive matcher: existing Parakeet encoder, exact-length inputs, RMS .05/peak .95 normalization with gain cap 32. Reference-frame-weighted DTW, .25 time band and .05 stretch penalty. Best-reference calibrated mean ≥ .70 and lower quartile ≥ .55. These are research-selected values, with known noise/timing limitations.
+- Negative veto: symmetric temporal similarity to the saved mistake ≥ .75 and greater than the best positive by > .05. This is deliberately conservative for one-example learning; it is not the earlier larger, labeled-example-bank research result.
+- Reference identity includes model, extractor version, label, enrollment audio identities and vectors. Renaming, retraining or changing models makes old negatives ineligible.
+- At most 6 negative examples per word and 32 total; file size ≤ 32 MB. Duplicate confirmation IDs are ignored. Corrupt optional banks produce no veto; saving reports failure rather than silently overwriting corrupt data.
+- Confirmation checks the entry/profile before and after the store write. Cancellation, disabling collection, changed profiles, expiry, and clearing invalidate stale work.
+- Separate store: `~/Library/Application Support/FluidVoice/dictionary-negative-examples-v1.plist`.
+- Existing loaded Core ML models are reused. No dependency edits, new model downloads, decoder pass, or opening-audio delays. Frame extraction and comparison run off the main actor. Reference caches are bounded to 8 profiles; candidate cuts retain the existing 3-per-word/24-total bound.
+- Candidate discovery and ambiguity handling remain in the existing pipeline. Temporal acceptance is passed separately from the original score, preserving ranking rather than replacing every score with a constant.
+- Only supported Parakeet/Apple Silicon paths run the encoder. Other providers and missing evidence retain existing behavior. Cross-speaker accuracy and older-device runtime have not been established.
+
+## Replace or remove
+
+The independent decision layer is `DictionaryExperimentalMatcher.swift`. The encoder adapter is `DictionaryTemporalEncoder.swift`. Negative provenance/resolution/storage is isolated in `DictionaryNegativeExamples.swift`; settings are in `DictionaryMatcherExperimentSettings.swift`.
+
+Integration points are the final and incremental refinement paths in `FluidAudioProvider`, learning context transport in `DictionaryLearningEvidence`/`ASRService`, and the existing correction tracker/session/overlay. `DictionaryPronunciationExperiment.enabled` enables the edge discovery path only for the positive comparator, not for collection alone. Remove these hooks and the four modules to remove the feature; no positive-store migration is required. The optional negative file can be cleared independently.
+
+## Validation and manual test
+
+Run `DEVELOPER_DIR=/path/to/Xcode.app/Contents/Developer sh Tests/run_dictionary_matcher_experiment_tests.sh`. An optional research-artifact directory argument additionally compares all 392 retained research cut decisions against the production scorer. Tests use only temporary storage and do not change real preferences or recordings.
+
+Build with `INSTALL_APP=0 LAUNCH_APP=0 sh build_with_FI_incremental.sh` (appropriate installed Xcode selected, development signing preserved). This work has not installed or launched a replacement app.
+
+Manual test after installing a test build:
+
+1. Enable whole-pronunciation matching and wrong-match learning. Use a word with three saved training recordings. Keep negative comparison off to collect without changing rejection.
+2. Dictate into an external editor with Accessibility support. Correct an actual dictionary replacement to another word and leave the edited word. Confirm **That Was a Wrong Match** in the overlay.
+3. Enable negative comparison and try the same mistake plus genuine pronunciations of the dictionary word. Check both rejected mistakes and unintended missed correct words.
+4. Toggle comparison off to compare behavior; clear the examples to reset. Rename/retrain a word and verify old negatives no longer affect it.
+5. Check the overlay at narrow widths and Settings in light/dark appearances. These visible flows and live Accessibility delivery have not been manually verified in this change.
+
+Verified for this change: private FI Release build passed with install/launch disabled; 816 isolated component/parity checks passed; production scorer matched all 392 archived cut decisions; production encoder frames matched all six original enrollment extractions exactly; strict lint passed for the four new implementation files. Nineteen unrelated tracked WIP patches were unchanged. Full app XCTest, installed UI, live correction observation and older-Mac testing were not run. Existing replay diagnostics remain the original matcher and now show that limitation when experiments are enabled.