A free, open source, and extensible speech-to-text application that works completely offline.
fix: preserve ampersands in custom words (#1569)
Pierre0a59e1f3001c
diff --git a/src-tauri/src/audio_toolkit/text.rs b/src-tauri/src/audio_toolkit/text.rsindex 45abb2dc..069f17ee 100644--- a/src-tauri/src/audio_toolkit/text.rs+++ b/src-tauri/src/audio_toolkit/text.rs@@ -10,14 +10,47 @@ use strsim::levenshtein;fn build_ngram(words: &[&str]) -> String {words.iter()- .map(|w| {- w.trim_matches(|c: char| !c.is_alphanumeric())- .to_lowercase()- })+ .map(|w| build_match_key(w)).collect::<Vec<_>>().concat()}+fn build_match_key(word: &str) -> String {+ word.chars()+ .filter(|c| c.is_alphanumeric())+ .flat_map(|c| c.to_lowercase())+ .collect()+}++struct CustomWordMatchKey {+ word_index: usize,+ key: String,+}++fn build_custom_word_match_keys(word: &str, word_index: usize) -> Vec<CustomWordMatchKey> {+ let primary_key = build_match_key(word);+ let mut keys = Vec::with_capacity(2);++ if !primary_key.is_empty() {+ keys.push(CustomWordMatchKey {+ word_index,+ key: primary_key.clone(),+ });+ }++ if word.contains('&') {+ let expanded_key = build_match_key(&word.replace('&', " and "));+ if !expanded_key.is_empty() && expanded_key != primary_key {+ keys.push(CustomWordMatchKey {+ word_index,+ key: expanded_key,+ });+ }+ }++ keys+}+/// Finds the best matching custom word for a candidate string////// Uses Levenshtein distance and Soundex phonetic matching to find@@ -26,7 +59,7 @@ fn build_ngram(words: &[&str]) -> String {/// # Arguments/// * `candidate` - The cleaned/lowercased candidate string to match/// * `custom_words` - Original custom words (for returning the replacement)-/// * `custom_words_nospace` - Custom words with spaces removed, lowercased (for comparison)+/// * `custom_word_match_keys` - Normalized custom-word keys for comparison/// * `threshold` - Maximum similarity score to accept////// # Returns@@ -34,7 +67,7 @@ fn build_ngram(words: &[&str]) -> String {fn find_best_match<'a>(candidate: &str,custom_words: &'a [String],- custom_words_nospace: &[String],+ custom_word_match_keys: &[CustomWordMatchKey],threshold: f64,) -> Option<(&'a String, f64)> {if candidate.is_empty() || candidate.len() > 50 {@@ -44,20 +77,20 @@ fn find_best_match<'a>(let mut best_match: Option<&String> = None;let mut best_score = f64::MAX;- for (i, custom_word_nospace) in custom_words_nospace.iter().enumerate() {+ for custom_word_key in custom_word_match_keys {// Skip if lengths are too different (optimization + prevents over-matching)// Use percentage-based check: max 25% length difference (prevents n-grams from// matching significantly shorter custom words, e.g., "openaigpt" vs "openai")- let len_diff = (candidate.len() as i32 - custom_word_nospace.len() as i32).abs() as f64;- let max_len = candidate.len().max(custom_word_nospace.len()) as f64;+ let len_diff = (candidate.len() as i32 - custom_word_key.key.len() as i32).abs() as f64;+ let max_len = candidate.len().max(custom_word_key.key.len()) as f64;let max_allowed_diff = (max_len * 0.25).max(2.0); // At least 2 chars difference allowedif len_diff > max_allowed_diff {continue;}// Calculate Levenshtein distance (normalized by length)- let levenshtein_dist = levenshtein(candidate, custom_word_nospace);- let max_len = candidate.len().max(custom_word_nospace.len()) as f64;+ let levenshtein_dist = levenshtein(candidate, &custom_word_key.key);+ let max_len = candidate.len().max(custom_word_key.key.len()) as f64;let levenshtein_score = if max_len > 0.0 {levenshtein_dist as f64 / max_len} else {@@ -65,7 +98,7 @@ fn find_best_match<'a>(};// Calculate phonetic similarity using Soundex- let phonetic_match = soundex(candidate, custom_word_nospace);+ let phonetic_match = soundex(candidate, &custom_word_key.key);// Combine scores: favor phonetic matches, but also consider string similaritylet combined_score = if phonetic_match {@@ -76,7 +109,7 @@ fn find_best_match<'a>(// Accept if the score is good enough (configurable threshold)if combined_score < threshold && combined_score < best_score {- best_match = Some(&custom_words[i]);+ best_match = Some(&custom_words[custom_word_key.word_index]);best_score = combined_score;}}@@ -104,13 +137,11 @@ pub fn apply_custom_words(text: &str, custom_words: &[String], threshold: f64) -return text.to_string();}- // Pre-compute lowercase versions to avoid repeated allocations- let custom_words_lower: Vec<String> = custom_words.iter().map(|w| w.to_lowercase()).collect();-- // Pre-compute versions with spaces removed for n-gram comparison- let custom_words_nospace: Vec<String> = custom_words_lower+ // Pre-compute normalized comparison keys to avoid repeated allocations.+ let custom_word_match_keys: Vec<CustomWordMatchKey> = custom_words.iter()- .map(|w| w.replace(' ', ""))+ .enumerate()+ .flat_map(|(index, word)| build_custom_word_match_keys(word, index)).collect();let words: Vec<&str> = text.split_whitespace().collect();@@ -130,7 +161,7 @@ pub fn apply_custom_words(text: &str, custom_words: &[String], threshold: f64) -let ngram = build_ngram(ngram_words);if let Some((replacement, _score)) =- find_best_match(&ngram, custom_words, &custom_words_nospace, threshold)+ find_best_match(&ngram, custom_words, &custom_word_match_keys, threshold){// Extract punctuation from first and last words of the n-gramlet (prefix, _) = extract_punctuation(ngram_words[0]);@@ -564,4 +595,28 @@ mod tests {result);}++ #[test]+ fn test_apply_custom_words_matches_ampersand_word() {+ let text = "send it to RD for review";+ let custom_words = vec!["R&D".to_string()];+ let result = apply_custom_words(text, &custom_words, 0.18);+ assert_eq!(result, "send it to R&D for review");+ }++ #[test]+ fn test_apply_custom_words_matches_spoken_ampersand_word() {+ let text = "send it to R and D for review";+ let custom_words = vec!["R&D".to_string()];+ let result = apply_custom_words(text, &custom_words, 0.18);+ assert_eq!(result, "send it to R&D for review");+ }++ #[test]+ fn test_apply_custom_words_preserves_ampersand_word() {+ let text = "send it to R&D for review";+ let custom_words = vec!["R&D".to_string()];+ let result = apply_custom_words(text, &custom_words, 0.18);+ assert_eq!(result, "send it to R&D for review");+ }}diff --git a/src/components/settings/CustomWords.tsx b/src/components/settings/CustomWords.tsxindex 0137d87e..4731becb 100644--- a/src/components/settings/CustomWords.tsx+++ b/src/components/settings/CustomWords.tsx@@ -20,7 +20,7 @@ export const CustomWords: React.FC<CustomWordsProps> = React.memo(const handleAddWord = () => {const trimmedWord = newWord.trim();- const sanitizedWord = trimmedWord.replace(/[<>"'&]/g, "");+ const sanitizedWord = trimmedWord.replace(/[<>"']/g, "");if (sanitizedWord &&!sanitizedWord.includes(" ") &&