Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src-tauri/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,12 +312,13 @@ impl ShortcutAction for TranscribeAction {
recording_start_time.elapsed()
);
recently_cancelled::wipe(app);
let tm = Arc::clone(&app.state::<Arc<TranscriptionManager>>());
crate::window_names::capture(context_reads(
&settings,
processing_mode_for(&binding_id),
tm.local_can_boost(&settings),
));
crate::codex_stream::park(live);
let tm = Arc::clone(&app.state::<Arc<TranscriptionManager>>());
// The stream first, so its handshake overlaps the speaking
// time. Then the connection warm-up: it is quick, and the
// local warm-up can block on a model load.
Expand Down Expand Up @@ -474,7 +475,11 @@ pub(crate) fn restore(app: &AppHandle, operation: ProcessingOperation, kept: Kep
} else {
ProcessingMode::Standard
};
crate::window_names::capture(context_reads(&get_settings(app), mode));
let settings = get_settings(app);
let local_boosts = app
.state::<Arc<TranscriptionManager>>()
.local_can_boost(&settings);
crate::window_names::capture(context_reads(&settings, mode, local_boosts));
change_tray_icon(app, TrayIconState::Transcribing);
show_transcribing_overlay(app);
shortcut::register_cancel_shortcut(app);
Expand Down Expand Up @@ -635,6 +640,7 @@ impl TranscribeAction {
Arc::clone(&samples),
operation.clone(),
language.as_deref(),
&window.boost_terms,
live,
mode,
)
Expand Down
21 changes: 15 additions & 6 deletions src-tauri/src/actions/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,21 +108,30 @@ where
}

/// What a dictation starting now reads from the frontmost window. Cleanup
/// uses the names, the field and the kind of app; a language set for a kind
/// of app needs the kind too, with or without cleanup. A raw dictation never
/// runs cleanup, so it skips window names, field excerpts and style lookups
/// and only reads the kind when `category_languages` is set.
pub(super) fn context_reads(settings: &AppSettings, mode: ProcessingMode) -> ContextReads {
/// uses the names, the field and the kind of app; a local model that boosts
/// on-screen terms (`local_boosts`) uses `boost_terms` even when cleanup is
/// off; a language set for a kind of app needs the kind too, with or without
/// cleanup. A raw dictation never runs cleanup or boosting, so it skips window
/// names, boost terms, field excerpts and style lookups and only reads the
/// kind when `category_languages` is set.
pub(super) fn context_reads(
settings: &AppSettings,
mode: ProcessingMode,
local_boosts: bool,
) -> ContextReads {
match mode {
ProcessingMode::Raw => ContextReads {
names: false,
boost_terms: false,
field: false,
kind: !settings.category_languages.is_empty(),
},
ProcessingMode::Standard => {
let cleanup_reads = settings.window_names_enabled && settings.ai_cleanup_enabled;
let on = settings.window_names_enabled;
let cleanup_reads = on && settings.ai_cleanup_enabled;
ContextReads {
names: cleanup_reads,
boost_terms: on && local_boosts,
field: cleanup_reads,
kind: (settings.ai_cleanup_enabled && !settings.category_styles.is_empty())
|| !settings.category_languages.is_empty(),
Expand Down
46 changes: 27 additions & 19 deletions src-tauri/src/actions/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,29 @@ fn cleanup_follows_the_chosen_dictation_style() {
}

#[test]
fn the_window_is_read_only_with_cleanup_and_the_setting_on() {
for (setting, cleanup, read) in [
(true, true, true),
(false, true, false),
(true, false, false),
(false, false, false),
fn window_reads_follow_cleanup_local_boosting_and_the_setting() {
for (setting, cleanup, local_boosts, names, boost_terms, field) in [
(true, true, true, true, true, true),
(true, true, false, true, false, true),
(true, false, true, false, true, false),
(true, false, false, false, false, false),
(false, true, true, false, false, false),
(false, true, false, false, false, false),
(false, false, true, false, false, false),
(false, false, false, false, false, false),
] {
let mut settings = get_default_settings();
settings.window_names_enabled = setting;
settings.ai_cleanup_enabled = cleanup;
assert_eq!(
context_reads(&settings, ProcessingMode::Standard),
context_reads(&settings, ProcessingMode::Standard, local_boosts),
ContextReads {
kind: false,
names: read,
field: read
names,
boost_terms,
field,
},
"setting {setting}, cleanup {cleanup}"
"setting {setting}, cleanup {cleanup}, local_boosts {local_boosts}"
);
}
}
Expand All @@ -80,6 +85,7 @@ fn window() -> WindowContext {
WindowContext {
kind: None,
names: vec!["Ingrid".to_string()],
boost_terms: Vec::new(),
field: Some(FieldExcerpt {
before: "Hi Ingrid, ".to_string(),
after: String::new(),
Expand Down Expand Up @@ -472,34 +478,34 @@ fn plan_for(settings: &AppSettings, text: &str, category: AppCategory) -> Cleanu
#[test]
fn a_dictation_reads_the_kind_of_app_only_when_a_kind_has_a_style() {
let mut settings = get_default_settings();
assert!(!context_reads(&settings, ProcessingMode::Standard).kind);
assert!(!context_reads(&settings, ProcessingMode::Standard, false).kind);

settings
.category_styles
.insert(AppCategory::Emails, CategoryStyle::Formal);
assert!(context_reads(&settings, ProcessingMode::Standard).kind);
assert!(context_reads(&settings, ProcessingMode::Standard, false).kind);

// The window names switch does not gate it: the kind is not window text.
settings.window_names_enabled = false;
assert!(context_reads(&settings, ProcessingMode::Standard).kind);
assert!(context_reads(&settings, ProcessingMode::Standard, false).kind);

settings.ai_cleanup_enabled = false;
assert!(!context_reads(&settings, ProcessingMode::Standard).kind);
assert!(!context_reads(&settings, ProcessingMode::Standard, false).kind);
}

#[test]
fn a_language_for_a_kind_of_app_reads_the_kind_even_without_cleanup() {
let mut settings = get_default_settings();
settings.ai_cleanup_enabled = false;
assert!(!context_reads(&settings, ProcessingMode::Standard).kind);
assert!(!context_reads(&settings, ProcessingMode::Standard, false).kind);

settings
.category_languages
.insert(AppCategory::Coding, "en".to_string());
let reads = context_reads(&settings, ProcessingMode::Standard);
let reads = context_reads(&settings, ProcessingMode::Standard, false);
assert!(reads.kind);
// The language needs no window text.
assert!(!reads.names && !reads.field);
assert!(!reads.names && !reads.boost_terms && !reads.field);
}

#[test]
Expand All @@ -512,9 +518,10 @@ fn raw_dictation_skips_cleanup_window_reads_but_keeps_category_languages() {
.insert(AppCategory::Emails, CategoryStyle::Formal);

assert_eq!(
context_reads(&settings, ProcessingMode::Raw),
context_reads(&settings, ProcessingMode::Raw, true),
ContextReads {
names: false,
boost_terms: false,
field: false,
kind: false,
}
Expand All @@ -524,9 +531,10 @@ fn raw_dictation_skips_cleanup_window_reads_but_keeps_category_languages() {
.category_languages
.insert(AppCategory::Coding, "en".to_string());
assert_eq!(
context_reads(&settings, ProcessingMode::Raw),
context_reads(&settings, ProcessingMode::Raw, true),
ContextReads {
names: false,
boost_terms: false,
field: false,
kind: true,
}
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/audio_toolkit/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn word_key(word: &str) -> String {
}

/// Everyday English and French words, lowercase.
fn is_everyday_word(word: &str) -> bool {
pub(crate) fn is_everyday_word(word: &str) -> bool {
static WORDS: OnceLock<HashSet<&'static str>> = OnceLock::new();
WORDS
.get_or_init(|| include_str!("common_words.txt").lines().collect())
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/commands/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ pub async fn retry_history_entry_transcription(
Arc::new(samples),
operation.clone(),
language.as_deref(),
&[],
None,
ProcessingMode::Standard,
)
Expand Down
146 changes: 121 additions & 25 deletions src-tauri/src/engine/local/boost.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,74 @@
//! The words the local model listens for: the user's custom words. Names
//! read in the frontmost window are left out: on the real model, product
//! names among them replaced common words ("lazy dog" heard as "Datadog",
//! "table" as "Tableau"), while the custom words replaced none
//! (`real_engine::boosting_hears_custom_words_and_leaves_other_speech_alone`).
//! The words the local model listens for: the user's custom words first, then
//! up to `MAX_SCREEN_TERMS` uncommon terms visible in the frontmost window at
//! lower priority. The helper holds screen terms to a closer spelling match
//! (0.75 against FluidAudio's 0.50–0.55 for custom words) so they never replace
//! everyday speech ("table" -> "Tableau" is 0.71, "lazy dog" -> "Datadog" is
//! 0.57, while "use settings store" -> "useSettingsStore" is 1.0).

use crate::window_names::MAX_SCREEN_TERMS;
use std::collections::HashSet;
use std::fmt;

/// FluidAudio rates vocabulary boosting excellent up to 50 terms.
pub const MAX_BOOST_TERMS: usize = 50;

/// Shorter terms cause false replacements, such as "or" heard as "VR".
const MIN_TERM_CHARS: usize = 3;

pub fn boost_terms(custom_words: &[String]) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
custom_words
.iter()
.map(|term| term.trim())
.filter(|term| term.chars().count() >= MIN_TERM_CHARS)
.filter(|term| seen.insert(term.to_lowercase()))
.take(MAX_BOOST_TERMS)
.map(str::to_string)
.collect()
/// What one dictation listens for. A term appears in one list only: a custom
/// word always stays in `words` even when it also appears on screen.
#[derive(Default, Clone, PartialEq, Eq)]
pub struct BoostTerms {
/// The user's custom words, boosted at full priority.
pub words: Vec<String>,
/// Uncommon terms read from the frontmost window, held to a closer match.
pub screen: Vec<String>,
}

impl BoostTerms {
pub const EMPTY: Self = Self {
words: Vec::new(),
screen: Vec::new(),
};

pub fn empty() -> &'static Self {
static EMPTY: BoostTerms = BoostTerms::EMPTY;
&EMPTY
}

pub fn len(&self) -> usize {
self.words.len() + self.screen.len()
}
}

/// Counts only, so a stray `{:?}` never logs on-screen or custom terms.
impl fmt::Debug for BoostTerms {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoostTerms")
.field("words", &self.words.len())
.field("screen", &self.screen.len())
.finish()
}
}

/// The custom words first (up to `MAX_BOOST_TERMS`), then the on-screen terms
/// they leave room for (up to `MAX_SCREEN_TERMS`).
pub fn boost_terms(custom_words: &[String], screen_terms: &[String]) -> BoostTerms {
let mut seen = HashSet::new();
let mut usable = |terms: &[String], room: usize| -> Vec<String> {
terms
.iter()
.map(|term| term.trim())
.filter(|term| term.chars().count() >= MIN_TERM_CHARS)
.filter(|term| seen.insert(term.to_lowercase()))
.take(room)
.map(str::to_string)
.collect()
};
let words = usable(custom_words, MAX_BOOST_TERMS);
let screen_room = (MAX_BOOST_TERMS - words.len()).min(MAX_SCREEN_TERMS);
let screen = usable(screen_terms, screen_room);
BoostTerms { words, screen }
}

#[cfg(test)]
Expand All @@ -33,32 +82,79 @@ mod tests {
#[test]
fn the_custom_words_keep_their_order() {
assert_eq!(
boost_terms(&strings(&["Siobhán", "Kubernetes", "Nguyen"])),
boost_terms(&strings(&["Siobhán", "Kubernetes", "Nguyen"]), &[]).words,
["Siobhán", "Kubernetes", "Nguyen"]
);
}

#[test]
fn a_term_seen_in_any_case_is_kept_once_as_first_written() {
assert_eq!(
boost_terms(&strings(&[
"Siobhán", "SIOBHÁN", "siobhán", "Nguyen", "nguyen"
])),
["Siobhán", "Nguyen"]
boost_terms(
&strings(&["Siobhán", "SIOBHÁN", "siobhán", "Nguyen", "nguyen"]),
&strings(&["useSettingsStore", "USESETTINGSSTORE"])
),
BoostTerms {
words: strings(&["Siobhán", "Nguyen"]),
screen: strings(&["useSettingsStore"]),
}
);
}

#[test]
fn a_screen_term_that_is_also_a_custom_word_stays_at_custom_word_priority() {
assert_eq!(
boost_terms(
&strings(&["useSettingsStore"]),
&strings(&["AudioRecordingManager", "usesettingsstore", "SQLite"])
),
BoostTerms {
words: strings(&["useSettingsStore"]),
screen: strings(&["AudioRecordingManager", "SQLite"]),
}
);
}

#[test]
fn terms_under_three_characters_are_dropped_and_spaces_trimmed() {
assert_eq!(
boost_terms(&strings(&["AI", " Zoë ", "", "Bo", "Q3", "Ana"])),
["Zoë", "Ana"]
boost_terms(
&strings(&["AI", " Zoë ", "", "Bo", "Q3", "Ana"]),
&strings(&["UX", " useSettingsStore "])
),
BoostTerms {
words: strings(&["Zoë", "Ana"]),
screen: strings(&["useSettingsStore"]),
}
);
}

#[test]
fn the_list_is_capped_at_the_first_terms() {
let custom: Vec<String> = (0..80).map(|i| format!("Custom{i}")).collect();
assert_eq!(boost_terms(&custom), custom[..MAX_BOOST_TERMS]);
fn screen_terms_are_capped_at_24_and_never_displace_custom_words() {
let screen: Vec<String> = (0..40).map(|i| format!("Symbol{i}")).collect();
let terms = boost_terms(&[], &screen);
assert_eq!(terms.screen, screen[..MAX_SCREEN_TERMS]);

let custom: Vec<String> = (0..35).map(|i| format!("Custom{i}")).collect();
let terms = boost_terms(&custom, &screen);
assert_eq!(terms.words, custom);
assert_eq!(terms.screen, screen[..MAX_BOOST_TERMS - 35]);

let full: Vec<String> = (0..80).map(|i| format!("Custom{i}")).collect();
let terms = boost_terms(&full, &screen);
assert_eq!(terms.words, full[..MAX_BOOST_TERMS]);
assert!(terms.screen.is_empty());
}

#[test]
fn debug_formatting_logs_only_counts_never_terms() {
let terms = boost_terms(
&strings(&["SecretCustomWord"]),
&strings(&["SecretScreenSymbol"]),
);
let formatted = format!("{terms:?}");
assert!(!formatted.contains("SecretCustomWord"));
assert!(!formatted.contains("SecretScreenSymbol"));
assert!(formatted.contains("words: 1") && formatted.contains("screen: 1"));
}
}
Loading
Loading