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.

8.5 KB
Raw Blame
//! Cleanup of local transcripts before anything reads them (the AREC, the
//! talk-key paste, the viewer). Runs in `local::process` next to the
//! dictionary's spelling pass, before the status leaves "transcribing".
//!
//! - Junk removal is always on: it drops markers a speech model writes when
//!   it hears no words (`[BLANK_AUDIO]`, `(music)`, `<|endoftext|>`, a
//!   segment of only music notes). Nobody said them, so this never changes
//!   what someone said.
//! - Filler removal ("um", "uh", "erm", "hmm") is on by default (since
//!   2026-11-30; it used to be off); Settings →
//!   Preferences → Transcription turns it off. Unset reads as on, an
//!   explicit off stays off, so existing users who never touched it get the
//!   new default and nobody who turned it off is overridden. It is
//!   English only and runs only on a transcript whose language is known to
//!   be English (German "Er" and Portuguese "um" are real words).
//!
//! Agent narration segments are never touched. Stored in `settings.json`
//! under `transcript_remove_fillers`; kept in memory as well because
//! processing runs on a worker thread.

pub mod rules;

use std::sync::atomic::{AtomicBool, Ordering};

use serde::Serialize;
use serde_json::Value;
use tauri::{AppHandle, Runtime};
use tauri_plugin_store::StoreExt;

use crate::commands::SETTINGS_STORE;

const FILLERS_STORE_KEY: &str = "transcript_remove_fillers";

static REMOVE_FILLERS: AtomicBool = AtomicBool::new(DEFAULT_REMOVE_FILLERS);

/// Filler removal when the user never set it: on in the official app.
/// Clipy Local keeps its old default (off), since it has no switch for it.
const DEFAULT_REMOVE_FILLERS: bool = crate::edition::CLOUD;

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TranscriptCleanupDto {
    /// False where Settings has no Transcription section (everything but
    /// macOS). Junk removal still runs everywhere.
    supported: bool,
    remove_fillers: bool,
}

fn dto() -> TranscriptCleanupDto {
    TranscriptCleanupDto {
        supported: cfg!(target_os = "macos"),
        remove_fillers: REMOVE_FILLERS.load(Ordering::Relaxed),
    }
}

/// Reads the stored switch into memory. Called once at launch. A missing or
/// unreadable value reads as the default (on); a stored `false` stays off.
pub fn init<R: Runtime>(app: &AppHandle<R>) {
    let on = app
        .store(SETTINGS_STORE)
        .ok()
        .and_then(|store| store.get(FILLERS_STORE_KEY))
        .and_then(|value| value.as_bool())
        .unwrap_or(DEFAULT_REMOVE_FILLERS);
    REMOVE_FILLERS.store(on, Ordering::Relaxed);
}

#[tauri::command]
pub fn get_transcript_cleanup() -> TranscriptCleanupDto {
    dto()
}

#[tauri::command]
pub fn set_transcript_cleanup(
    app: AppHandle,
    remove_fillers: bool,
) -> Result<TranscriptCleanupDto, String> {
    let store = app.store(SETTINGS_STORE).map_err(|e| e.to_string())?;
    store.set(FILLERS_STORE_KEY, Value::Bool(remove_fillers));
    store.save().map_err(|e| e.to_string())?;
    REMOVE_FILLERS.store(remove_fillers, Ordering::Relaxed);
    Ok(dto())
}

/// What a cleanup pass did, in counts only (logs never carry words).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Cleaned {
    /// Segments whose text changed.
    pub changed: usize,
    /// Segments removed because nothing was left.
    pub dropped: usize,
}

/// Cleans transcript segments (`startMs`, `endMs`, `text`) in place with the
/// user's current setting. Segments `protected` accepts (agent narration)
/// are kept byte for byte.
///
/// `language` is the language the engine transcribed in (`en_US`, `de`);
/// filler removal runs only when it is English, and never when it is
/// unknown. Junk removal does not depend on it.
pub fn clean_segments(
    segments: &mut Vec<Value>,
    language: Option<&str>,
    protected: impl Fn(&str) -> bool,
) -> Cleaned {
    clean_with(
        segments,
        REMOVE_FILLERS.load(Ordering::Relaxed),
        language,
        protected,
    )
}

fn clean_with(
    segments: &mut Vec<Value>,
    remove_fillers: bool,
    language: Option<&str>,
    protected: impl Fn(&str) -> bool,
) -> Cleaned {
    let remove_fillers = remove_fillers && rules::is_english(language);
    let mut cleaned = Cleaned::default();
    segments.retain_mut(|segment| {
        let Some(text) = segment["text"].as_str() else {
            return true;
        };
        if protected(text) {
            return true;
        }
        let mut next = rules::remove_junk(text);
        if remove_fillers {
            let current = next.as_deref().unwrap_or(text);
            if let Some(without) = rules::remove_fillers(current) {
                next = Some(without);
            }
        }
        let Some(next) = next else {
            return true;
        };
        if next.is_empty() {
            cleaned.dropped += 1;
            return false;
        }
        cleaned.changed += 1;
        segment["text"] = Value::String(next);
        true
    });
    cleaned
}

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

    fn narration(text: &str) -> bool {
        text.starts_with("Narration: ")
    }

    #[test]
    fn junk_goes_always_fillers_only_when_asked() {
        let original = vec![
            json!({"startMs": 0, "endMs": 900, "text": "[BLANK_AUDIO]"}),
            json!({"startMs": 900, "endMs": 2000, "text": "Um, open the settings (music)"}),
            json!({"startMs": 2000, "endMs": 3000, "text": "Narration: um [BLANK_AUDIO]"}),
            json!({"startMs": 3000, "endMs": 4000, "text": "uh"}),
        ];

        let mut off = original.clone();
        assert_eq!(
            clean_with(&mut off, false, Some("en_US"), narration),
            Cleaned {
                changed: 1,
                dropped: 1
            }
        );
        assert_eq!(
            off,
            vec![
                json!({"startMs": 900, "endMs": 2000, "text": "Um, open the settings"}),
                json!({"startMs": 2000, "endMs": 3000, "text": "Narration: um [BLANK_AUDIO]"}),
                json!({"startMs": 3000, "endMs": 4000, "text": "uh"}),
            ]
        );

        let mut on = original;
        assert_eq!(
            clean_with(&mut on, true, Some("en_US"), narration),
            Cleaned {
                changed: 1,
                dropped: 2
            }
        );
        assert_eq!(
            on,
            vec![
                json!({"startMs": 900, "endMs": 2000, "text": "Open the settings"}),
                json!({"startMs": 2000, "endMs": 3000, "text": "Narration: um [BLANK_AUDIO]"}),
            ]
        );
    }

    #[test]
    fn clean_segments_are_left_alone() {
        let mut segments =
            vec![json!({"startMs": 0, "endMs": 1, "text": "hello  there", "extra": 1})];
        assert_eq!(
            clean_with(&mut segments, true, Some("en"), narration),
            Cleaned::default()
        );
        assert_eq!(
            segments,
            vec![json!({"startMs": 0, "endMs": 1, "text": "hello  there", "extra": 1})]
        );
    }

    #[test]
    fn fillers_stay_unless_the_transcript_is_known_to_be_english() {
        let cases = [
            ("de_DE", "Er hat den Fehler gefunden."),
            ("de", "Hmm, er hat recht."),
            ("pt_BR", "Preciso de um arquivo."),
            ("pt-PT", "Um momento, por favor."),
        ];
        for (language, text) in cases {
            let mut segments = vec![json!({"startMs": 0, "endMs": 1000, "text": text})];
            assert_eq!(
                clean_with(&mut segments, true, Some(language), narration),
                Cleaned::default(),
                "{language}: {text}"
            );
            assert_eq!(segments[0]["text"], text);
        }

        // An unknown language removes no fillers, but junk still goes.
        let mut unknown = vec![
            json!({"startMs": 0, "endMs": 1000, "text": "Um, open it [BLANK_AUDIO]"}),
            json!({"startMs": 1000, "endMs": 2000, "text": "Preciso de um arquivo."}),
        ];
        assert_eq!(
            clean_with(&mut unknown, true, None, narration),
            Cleaned {
                changed: 1,
                dropped: 0
            }
        );
        assert_eq!(unknown[0]["text"], "Um, open it");
        assert_eq!(unknown[1]["text"], "Preciso de um arquivo.");

        // The same English sentence with the language known loses its filler.
        let mut english = vec![json!({"startMs": 0, "endMs": 1000, "text": "Um, open it"})];
        clean_with(&mut english, true, Some("en_GB"), narration);
        assert_eq!(english[0]["text"], "Open it");
    }
}