Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

26.3 KB
Raw Blame
//! Transcript cleanup rules, with no Tauri or serde in them so they can be
//! tested anywhere (`rustc --edition 2021 --test rules.rs`).
//!
//! Two passes over one segment's text, both plain string matching:
//! - `remove_junk` (always on): drops markers a speech model writes when it
//!   hears no words, such as `[BLANK_AUDIO]`, `(music)`, `<|endoftext|>` or a
//!   segment of nothing but music notes. Nobody said these, so removing them
//!   never changes what was said. The list is explicit, and a marker is only
//!   removed where a model writes one (a token of its own, never attached to
//!   a word like `play(sound)`); see `remove_junk`.
//! - `remove_fillers` (opt in): drops standalone English hesitations ("um",
//!   "uh", "erm", "hmm") and tidies the punctuation and spacing around them.
//!   Only whole words match, so "umbrella" or "human" never change.
//!
//! Both return `None` when nothing changed, so an untouched segment keeps its
//! text byte for byte. `Some("")` means the segment held nothing else and
//! should be dropped.

/// What a model writes inside brackets for a sound that is not speech,
/// lowercased, with `_` and `-` read as spaces, that no one would say as a
/// bracketed word in a sentence. Removed wherever they stand as a token of
/// their own: "It opened [BLANK_AUDIO] and failed" loses the marker.
const MODEL_MARKERS: &[&str] = &[
    "blank audio",
    "no speech",
    "no audio",
    "music playing",
    "music plays",
    "music ends",
    "background noise",
    "inaudible",
    "indistinct",
    "indistinct chatter",
    "unintelligible",
    "clears throat",
    "keyboard clicking",
    "mouse clicking",
    "sound effect",
    "foreign language",
    "speaking foreign language",
    "speaking in foreign language",
    "non english speech",
    "crosstalk",
];

/// Sound descriptions that are also ordinary words ("the array [sound]",
/// "a [click] handler"). Removed only where a model puts them: as the whole
/// segment, or as a token of their own at its start or end ("(Applause)
/// Thank you", "It worked (laughs)."). In the middle of a sentence they stay.
const SOUND_WORDS: &[&str] = &[
    "blank",
    "silence",
    "music",
    "instrumental",
    "noise",
    "static",
    "applause",
    "laughter",
    "laughs",
    "laughing",
    "chuckles",
    "cough",
    "coughs",
    "coughing",
    "sigh",
    "sighs",
    "breathing",
    "breath",
    "beep",
    "beeping",
    "click",
    "clicking",
    "typing",
    "sound",
    "sounds",
    "wind",
];

/// Model control tokens written without the `<|...|>` form.
const BARE_TOKENS: &[&str] = &["<unk>", "<blank>", "<s>", "</s>", "<pad>", "<sil>"];

/// Music note glyphs Whisper writes for music with no words.
const NOTES: &[char] = &['♪', '♫', '♬', '♩', '🎵', '🎶'];

/// Longest bracketed marker looked at, in characters.
const MAX_MARKER_CHARS: usize = 48;

/// Punctuation that may follow a marker and still leave it a token of its
/// own: "(laughs)." or "[Music],".
const TRAILING: &[char] = &['.', ',', '!', '?', ';', ':', '…'];

fn normalize_marker(inner: &str) -> String {
    let lowered: String = inner
        .trim()
        .trim_matches(|c: char| NOTES.contains(&c) || c == '.' || c == '!' || c == '*')
        .chars()
        .map(|c| if c == '_' || c == '-' { ' ' } else { c })
        .flat_map(char::to_lowercase)
        .collect();
    lowered.split_whitespace().collect::<Vec<_>>().join(" ")
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    /// Never speech: removed anywhere, even attached (`<|en|><|transcribe|>`).
    Control,
    /// A model-only bracketed marker: removed as a standalone token.
    Model,
    /// A sound word in brackets: removed as a standalone token at the
    /// segment's start or end only.
    Sound,
}

fn marker_kind(inner: &str) -> Option<Kind> {
    let marker = normalize_marker(inner);
    if marker.is_empty() {
        // Brackets around only notes: "(♪)".
        let only_notes = inner
            .trim()
            .chars()
            .all(|c| c.is_whitespace() || NOTES.contains(&c))
            && inner.chars().any(|c| NOTES.contains(&c));
        return only_notes.then_some(Kind::Model);
    }
    if MODEL_MARKERS.contains(&marker.as_str()) {
        return Some(Kind::Model);
    }
    if SOUND_WORDS.contains(&marker.as_str()) {
        return Some(Kind::Sound);
    }
    // "(upbeat music)", "[soft piano music]": short descriptions of music.
    let words: Vec<&str> = marker.split(' ').collect();
    let music = words.len() <= 3
        && words.last() == Some(&"music")
        && words.iter().all(|w| w.chars().all(char::is_alphabetic));
    music.then_some(Kind::Sound)
}

fn is_control_token(inner: &str) -> bool {
    // `<|...|>`: lowercase letters, digits, `_` and `.` only (`<|en|>`,
    // `<|endoftext|>`, `<|0.00|>`).
    !inner.is_empty()
        && inner.chars().count() <= 32
        && inner
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '.')
}

/// A candidate marker at `chars[start..end]`.
#[derive(Clone, Copy, Debug)]
struct Span {
    start: usize,
    end: usize,
    kind: Kind,
}

/// Every bracketed marker or control token in the text, left to right, not
/// yet judged on where it stands.
fn candidates(chars: &[char]) -> Vec<Span> {
    let mut spans = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        let close = match c {
            '[' => Some(']'),
            '(' => Some(')'),
            '*' => Some('*'),
            _ => None,
        };
        if let Some(close) = close {
            let end =
                (i + 1..chars.len().min(i + 2 + MAX_MARKER_CHARS)).find(|&j| chars[j] == close);
            if let Some(end) = end {
                let inner: String = chars[i + 1..end].iter().collect();
                if !inner.contains(['[', '(', '*']) {
                    if let Some(kind) = marker_kind(&inner) {
                        spans.push(Span {
                            start: i,
                            end: end + 1,
                            kind,
                        });
                        i = end + 1;
                        continue;
                    }
                }
            }
        }
        if c == '<' {
            if chars.get(i + 1) == Some(&'|') {
                let end = (i + 2..chars.len().saturating_sub(1).min(i + 36))
                    .find(|&j| chars[j] == '|' && chars[j + 1] == '>');
                if let Some(end) = end {
                    let inner: String = chars[i + 2..end].iter().collect();
                    if is_control_token(&inner) {
                        spans.push(Span {
                            start: i,
                            end: end + 2,
                            kind: Kind::Control,
                        });
                        i = end + 2;
                        continue;
                    }
                }
            }
            let rest: String = chars[i..chars.len().min(i + 8)].iter().collect();
            if let Some(token) = BARE_TOKENS
                .iter()
                .find(|t| rest.to_ascii_lowercase().starts_with(*t))
            {
                let end = i + token.chars().count();
                spans.push(Span {
                    start: i,
                    end,
                    kind: Kind::Control,
                });
                i = end;
                continue;
            }
        }
        i += 1;
    }
    spans
}

/// Whether `chars[from..to]`, leaving out the given spans, holds anything
/// but whitespace and punctuation.
fn has_words(chars: &[char], from: usize, to: usize, skip: &[Span]) -> bool {
    (from..to)
        .any(|i| chars[i].is_alphanumeric() && !skip.iter().any(|s| (s.start..s.end).contains(&i)))
}

/// Removes model noise from one segment's text. `None`: nothing to remove.
/// `Some("")`: the segment was only noise.
///
/// A bracketed marker is only removed where a model writes one: as a token
/// of its own (whitespace or the segment's edge before it; whitespace, the
/// edge, or trailing punctuation then whitespace or the edge after it), so
/// `play(sound)`, `array[silence]` and `foo(music)` never match. Several
/// markers written back to back (`[Music][Applause]`) count as one token.
/// Sound words that are also ordinary words (`[sound]`, `(click)`) must also
/// sit at the segment's start or end, so "The array [sound] holds samples"
/// stays. Control tokens (`<|en|>`, `<unk>`) are never speech and go
/// wherever they are.
pub fn remove_junk(text: &str) -> Option<String> {
    let chars: Vec<char> = text.chars().collect();
    let spans = candidates(&chars);

    // Group back-to-back spans into tokens and keep those that stand alone.
    let mut standalone: Vec<Span> = Vec::new();
    let mut i = 0;
    while i < spans.len() {
        let mut j = i;
        while j + 1 < spans.len() && spans[j + 1].start == spans[j].end {
            j += 1;
        }
        let group = &spans[i..=j];
        let (start, end) = (group[0].start, group[group.len() - 1].end);
        let left = start == 0 || chars[start - 1].is_whitespace();
        let mut after = end;
        while after < chars.len() && TRAILING.contains(&chars[after]) {
            after += 1;
        }
        let right = after == chars.len() || chars[after].is_whitespace();
        if left && right {
            standalone.extend_from_slice(group);
        }
        i = j + 1;
    }
    let mut removed: Vec<Span> = spans
        .iter()
        .copied()
        .filter(|s| s.kind == Kind::Control)
        .collect();
    for span in &standalone {
        let keep_out = match span.kind {
            Kind::Control => continue,
            Kind::Model => true,
            Kind::Sound => {
                let at_start = !has_words(&chars, 0, span.start, &standalone);
                let at_end = !has_words(&chars, span.end, chars.len(), &standalone);
                at_start || at_end
            }
        };
        if keep_out {
            removed.push(*span);
        }
    }
    removed.sort_by_key(|s| s.start);

    let mut out = String::with_capacity(text.len());
    let mut next = 0;
    for span in &removed {
        out.extend(&chars[next..span.start]);
        out.push(' ');
        next = span.end;
    }
    out.extend(&chars[next..]);

    // A segment of nothing but notes (and punctuation) is music, not words.
    let only_notes =
        out.chars().any(|c| NOTES.contains(&c)) && !out.chars().any(char::is_alphanumeric);
    if only_notes {
        return Some(String::new());
    }
    if removed.is_empty() {
        return None;
    }
    Some(tidy(&out))
}

/// Collapses whitespace, drops a space left before punctuation, and returns
/// an empty string when no letters or digits are left.
fn tidy(text: &str) -> String {
    if !text.chars().any(char::is_alphanumeric) {
        return String::new();
    }
    let joined = text.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut out = String::with_capacity(joined.len());
    for c in joined.chars() {
        if matches!(c, ',' | '.' | '!' | '?' | ';' | ':') && out.ends_with(' ') {
            out.pop();
        }
        out.push(c);
    }
    // A comma or other separator left at the very start: ", so then".
    out.trim_start_matches(|c: char| matches!(c, ',' | ';' | ':') || c.is_whitespace())
        .to_string()
}

/// Whether a transcript's language is English: a language code or locale
/// such as `en`, `en-GB` or `en_US`. Filler removal is English only (German
/// "Er" and Portuguese "um" are real words), so anything else, including an
/// unknown language, is not.
pub fn is_english(language: Option<&str>) -> bool {
    let Some(language) = language else {
        return false;
    };
    let code = language
        .trim()
        .split(['-', '_', '@', '.'])
        .next()
        .unwrap_or("");
    code.eq_ignore_ascii_case("en") || code.eq_ignore_ascii_case("eng")
}

/// Whether `word` (letters only, any case) is an English hesitation.
/// Patterns, not a guess: um, umm, uhm, uh, uhh, er, erm, ehm, hm, hmm, mmm.
/// Not "mm" (millimetres), "err" (a verb), "ah", "oh", "eh" or "uh-huh",
/// which carry meaning.
pub fn is_filler(word: &str) -> bool {
    let chars: Vec<char> = word.chars().collect();
    if chars.is_empty() || !chars.iter().all(|c| c.is_ascii_alphabetic()) {
        return false;
    }
    // An acronym ("ER", "UM" as a name) is written in capitals.
    if chars.len() >= 2 && chars.iter().all(|c| c.is_ascii_uppercase()) {
        return false;
    }
    let lower = word.to_ascii_lowercase();
    if lower == "er" {
        return true;
    }
    // Runs of letters: ("u", "m") matches u+m+.
    let runs: Vec<(char, usize)> = lower.chars().fold(Vec::new(), |mut runs, c| {
        match runs.last_mut() {
            Some((last, n)) if *last == c => *n += 1,
            _ => runs.push((c, 1)),
        }
        runs
    });
    let shape: String = runs.iter().map(|(c, _)| *c).collect();
    match shape.as_str() {
        "um" | "uh" | "uhm" | "erm" | "ehm" | "hm" => true,
        "m" => runs[0].1 >= 3,
        _ => false,
    }
}

const OPENING: &[char] = &['"', '\'', '“', '‘', '«', '(', '['];
const CLOSING: &[char] = &['"', '\'', '”', '’', '»', ')', ']'];
const SENTENCE_END: &[char] = &['.', '!', '?', '…'];
const QUOTE_PAIRS: &[(char, char)] =
    &[('"', '"'), ('\'', '\''), ('“', '”'), ('‘', '’'), ('«', '»')];
const BRACKET_PAIRS: &[(char, char)] = &[('(', ')'), ('[', ']')];

fn is_quoted_filler(lead: &str, trail: &str) -> bool {
    QUOTE_PAIRS
        .iter()
        .any(|&(open, close)| lead.contains(open) && trail.contains(close))
}

/// Drops matching bracket/parenthesis pairs wrapping a single removed filler
/// so `"Hello (um) world"` becomes `"Hello world"` instead of `"Hello) (world"`.
fn strip_self_brackets(lead: &str, trail: &str) -> (String, String) {
    let mut open_marks: Vec<char> = lead.chars().filter(|c| OPENING.contains(c)).collect();
    let mut trail_chars: Vec<char> = trail.chars().collect();
    loop {
        let pair = BRACKET_PAIRS.iter().find_map(|&(open, close)| {
            let li = open_marks.iter().rposition(|&c| c == open)?;
            let ti = trail_chars.iter().position(|&c| c == close)?;
            Some((li, ti))
        });
        let Some((li, ti)) = pair else {
            break;
        };
        open_marks.remove(li);
        trail_chars.remove(ti);
    }
    (
        open_marks.into_iter().collect(),
        trail_chars.into_iter().collect(),
    )
}

/// One whitespace-separated token split into leading marks, the word, and
/// trailing marks: `"Um,` is (`"`, `Um`, `,`).
struct Token<'a> {
    lead: &'a str,
    core: &'a str,
    trail: &'a str,
}

fn split_token(token: &str) -> Token<'_> {
    let core_start = token
        .char_indices()
        .find(|(_, c)| c.is_alphanumeric())
        .map(|(i, _)| i)
        .unwrap_or(token.len());
    let core_end = token
        .char_indices()
        .rev()
        .find(|(_, c)| c.is_alphanumeric())
        .map(|(i, c)| i + c.len_utf8())
        .unwrap_or(core_start);
    Token {
        lead: &token[..core_start],
        core: &token[core_start..core_end.max(core_start)],
        trail: &token[core_end.max(core_start)..],
    }
}

fn ends_sentence(token: &str) -> bool {
    token.trim_end_matches(CLOSING).ends_with(SENTENCE_END)
}

/// Capitalizes the first letter of `token` unless the word is cased on
/// purpose (iOS, eBay, x86) or is a lone letter other than "i".
fn capitalize(token: &str) -> String {
    let parts = split_token(token);
    let mut core = parts.core.chars();
    let Some(first) = core.next() else {
        return token.to_string();
    };
    let rest: String = core.collect();
    let deliberate = rest.chars().any(|c| c.is_uppercase() || c.is_ascii_digit());
    if !first.is_lowercase() || deliberate || (rest.is_empty() && first != 'i') {
        return token.to_string();
    }
    format!(
        "{}{}{}{}",
        parts.lead,
        first.to_uppercase(),
        rest,
        parts.trail
    )
}

/// Removes standalone hesitations from one segment's text. `None`: none
/// found. `Some("")`: the segment was only hesitations.
pub fn remove_fillers(text: &str) -> Option<String> {
    let tokens: Vec<&str> = text.split_whitespace().collect();
    let mut out: Vec<String> = Vec::with_capacity(tokens.len());
    let mut removed = false;
    let mut capitalize_next = false;
    for token in tokens {
        let parts = split_token(token);
        let quoted = is_quoted_filler(parts.lead, parts.trail);
        if parts.core.is_empty() || quoted || !is_filler(parts.core) {
            if capitalize_next {
                out.push(capitalize(token));
                capitalize_next = false;
            } else {
                out.push(token.to_string());
            }
            continue;
        }
        removed = true;
        let at_sentence_start = out.last().is_none_or(|prev| ends_sentence(prev));
        // A capital on the filler belonged to the sentence; give it to the
        // next word.
        if at_sentence_start && parts.core.starts_with(|c: char| c.is_uppercase()) {
            capitalize_next = true;
        }
        // Drop bracket pairs that wrapped only this filler, and keep any outer
        // punctuation plus remaining opening/closing marks for adjacent words.
        let (lead, trail_rest) = strip_self_brackets(parts.lead, parts.trail);
        let marks: String = trail_rest
            .chars()
            .filter(|c| !CLOSING.contains(c) && *c != ',')
            .collect();
        let close: String = trail_rest.chars().filter(|c| CLOSING.contains(c)).collect();
        let trail_out: String = trail_rest.chars().filter(|c| *c != ',').collect();
        if let Some(prev) = out.last_mut() {
            if !ends_sentence(prev) {
                if !trail_out.is_empty() {
                    let trimmed = prev.trim_end_matches([',', ';', ':']).to_string();
                    *prev = format!("{trimmed}{trail_out}");
                    if marks.ends_with(SENTENCE_END) {
                        capitalize_next = true;
                    }
                }
            } else if !close.is_empty() {
                prev.push_str(&close);
            }
        }
        if !lead.is_empty() {
            // Carried onto the next word by prefixing a placeholder token.
            out.push(lead);
            capitalize_next = capitalize_next || at_sentence_start;
        }
    }
    if !removed {
        return None;
    }
    // Merge a carried opening mark into the word after it.
    let mut merged: Vec<String> = Vec::with_capacity(out.len());
    let mut pending = String::new();
    for token in out {
        if token.chars().all(|c| OPENING.contains(&c)) {
            pending.push_str(&token);
            continue;
        }
        merged.push(format!("{pending}{token}"));
        pending.clear();
    }
    if !merged.iter().any(|t| t.chars().any(char::is_alphanumeric)) {
        return Some(String::new());
    }
    Some(merged.join(" "))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn junk(text: &str) -> Option<String> {
        remove_junk(text)
    }
    fn fill(text: &str) -> Option<String> {
        remove_fillers(text)
    }

    #[test]
    fn markers_alone_empty_the_segment() {
        for text in [
            "[BLANK_AUDIO]",
            " [BLANK AUDIO] ",
            "[Music]",
            "(music)",
            "(upbeat music)",
            "[soft piano music]",
            "(silence)",
            "[ Silence ]",
            "*laughs*",
            "<|endoftext|>",
            "<|nocaptions|>",
            "♪",
            "♪ ♪ ♪",
            "♪♪",
            "(♪)",
            "[MUSIC PLAYING]",
            "[no speech]",
            "<unk>",
        ] {
            assert_eq!(junk(text).as_deref(), Some(""), "{text:?}");
        }
    }

    #[test]
    fn markers_inside_speech_are_removed_and_spacing_tidied() {
        assert_eq!(
            junk("So I opened it [BLANK_AUDIO] and it failed.").as_deref(),
            Some("So I opened it and it failed.")
        );
        assert_eq!(
            junk("<|en|><|transcribe|> Hello there").as_deref(),
            Some("Hello there")
        );
        assert_eq!(junk("It worked (laughs).").as_deref(), Some("It worked."));
        assert_eq!(junk("(Applause) Thank you").as_deref(), Some("Thank you"));
        assert_eq!(
            junk("(upbeat music) Welcome back").as_deref(),
            Some("Welcome back")
        );
        assert_eq!(
            junk("[Music][Applause] Thanks, everyone.").as_deref(),
            Some("Thanks, everyone.")
        );
        assert_eq!(
            junk("That was it. [silence]").as_deref(),
            Some("That was it.")
        );
        assert_eq!(
            junk("Done [MUSIC PLAYING], bye").as_deref(),
            Some("Done, bye")
        );
    }

    #[test]
    fn marker_words_inside_real_expressions_stay() {
        for text in [
            "Call play(sound) next.",
            "The array [sound] holds samples.",
            "Then print(music) to debug",
            "Read items[silence] first",
            "foo(music)",
            "Add a [click] handler here",
            "It worked (laughs) and then broke",
            "The (noise) floor is low",
            "x[BLANK_AUDIO]y",
            "Use [the music] tag",
        ] {
            assert_eq!(junk(text), None, "{text:?}");
        }
    }

    #[test]
    fn real_bracketed_words_and_ordinary_speech_stay_byte_for_byte() {
        for text in [
            "Open the settings (the gear icon) and click save.",
            "The array [index] is wrong",
            "Call foo(bar) twice",
            "It said <b>bold</b>",
            "Use a | b in the shell",
            "We need more music in the intro",
            "Tags like <div> are fine",
            "(see above)",
            "[TODO] fix the login",
            "5 * 3 * 2 is thirty",
            "♪ Never gonna give you up ♪",
            "  double  spaces  stay  ",
            "",
        ] {
            assert_eq!(junk(text), None, "{text:?}");
        }
    }

    #[test]
    fn fillers_are_whole_words_only() {
        for word in [
            "um",
            "Um",
            "umm",
            "UMmm".to_lowercase().as_str(),
            "uh",
            "uhh",
            "uhm",
            "er",
            "erm",
            "ehm",
            "hm",
            "hmm",
            "hmmm",
            "mmm",
        ] {
            assert!(is_filler(word), "{word}");
        }
        for word in [
            "mm", "err", "ah", "oh", "eh", "ER", "UM", "umbrella", "human", "hummus", "uhuh",
            "her", "summer", "m", "u", "h", "e",
        ] {
            assert!(!is_filler(word), "{word}");
        }
    }

    #[test]
    fn fillers_are_removed_with_their_punctuation() {
        assert_eq!(
            fill("So, um, I think we ship it.").as_deref(),
            Some("So, I think we ship it.")
        );
        assert_eq!(fill("Um, I think so.").as_deref(), Some("I think so."));
        assert_eq!(
            fill("Uh so the button is broken").as_deref(),
            Some("So the button is broken")
        );
        assert_eq!(
            fill("I think um the button").as_deref(),
            Some("I think the button")
        );
        assert_eq!(fill("I think, um.").as_deref(), Some("I think."));
        assert_eq!(fill("Is it there, uh?").as_deref(), Some("Is it there?"));
        assert_eq!(
            fill("It broke. Um, then it worked.").as_deref(),
            Some("It broke. Then it worked.")
        );
        assert_eq!(
            fill("It broke, uh. then it worked").as_deref(),
            Some("It broke. Then it worked")
        );
        assert_eq!(fill("Hmm... let me check").as_deref(), Some("Let me check"));
        assert_eq!(fill("Um, iOS is fine").as_deref(), Some("iOS is fine"));
        assert_eq!(
            fill("He said \"um, wait\" twice").as_deref(),
            Some("He said \"wait\" twice")
        );
    }

    #[test]
    fn bracketed_and_delimited_fillers_keep_balanced_delimiters() {
        assert_eq!(fill("Hello (um) world").as_deref(), Some("Hello world"));
        assert_eq!(fill("Hello [uh] world").as_deref(), Some("Hello world"));
        assert_eq!(fill("(Um) hello").as_deref(), Some("Hello"));
        assert_eq!(fill("Hello (um)").as_deref(), Some("Hello"));
        assert_eq!(fill("Hello (um).").as_deref(), Some("Hello."));
        assert_eq!(fill("Hello, (um).").as_deref(), Some("Hello."));
        assert_eq!(fill("I think (yes, um)").as_deref(), Some("I think (yes)"));
        assert_eq!(
            fill("He said \"yeah, um\"").as_deref(),
            Some("He said \"yeah\"")
        );
        assert_eq!(
            fill("I think (yes, um).").as_deref(),
            Some("I think (yes).")
        );
        assert_eq!(
            fill("I think (yes, um.)").as_deref(),
            Some("I think (yes.)")
        );
        assert_eq!(
            fill("I think (yes, (um))").as_deref(),
            Some("I think (yes)")
        );
        assert_eq!(fill("I said (Wait. um)").as_deref(), Some("I said (Wait.)"));
        assert_eq!(fill("(Um), I guess").as_deref(), Some("I guess"));
        assert_eq!(fill("Hello (um)! world").as_deref(), Some("Hello! World"));
    }

    #[test]
    fn only_english_counts_as_english() {
        for language in [
            "en",
            "EN",
            "en-GB",
            "en_US",
            "en_IN@calendar=gregorian",
            "eng",
        ] {
            assert!(is_english(Some(language)), "{language}");
        }
        for language in [
            "de", "de_DE", "pt-BR", "pt_PT", "es", "fr_CA", "", "english", "ne", "enm",
        ] {
            assert!(!is_english(Some(language)), "{language}");
        }
        assert!(!is_english(None));
    }

    #[test]
    fn segments_of_only_fillers_are_emptied() {
        assert_eq!(fill("Um.").as_deref(), Some(""));
        assert_eq!(fill("uh, um, hmm").as_deref(), Some(""));
    }

    #[test]
    fn text_without_fillers_is_untouched() {
        for text in [
            "The umbrella is in the summer house.",
            "Five mm is too small.",
            "To err is human.",
            "Take her to the ER now.",
            "The word is \"um\" and that is fine.",
            "The word is «um» and that is fine.",
            "Uh-huh, that works.",
            "Oh, ah, eh.",
            "  spacing  kept  when  nothing  changes ",
            "",
        ] {
            assert_eq!(fill(text), None, "{text:?}");
        }
    }
}