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.

18.6 KB
Raw Blame
//! After a meeting recording: transcribe each track, split the call side
//! into voices, assemble who said what, then write the notes.
//!
//! One meeting is worked on at a time, on its own thread, after the
//! recording's own processing has finished, so the next recording can start
//! at once. Every stage is written to `meeting-status.json` and announced,
//! so the viewer shows where it stands.

use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::sync::OnceLock;
use std::time::Duration;

use clipy_local_edition::disclosure::Recipient;
use clipy_local_edition::settings::{moment_provider, MomentProvider};
use clipy_local_meetings::assemble::{self, SpeakerTurn, TrackSegment};
use clipy_local_meetings::model::{Notes, NotesState};
use clipy_local_meetings::notes::{self, Context, Error as NotesError, Prompt};
use clipy_local_meetings::{level, sources, track};
use clipy_local_moments::ProviderConfig;
use parking_lot::Mutex;
use serde_json::Value;
use tauri::{AppHandle, Emitter, Runtime};

use super::{
    read_meeting, save_meeting, write_status, VoicesDto, EVENT_VOICES_PROGRESS, FILE_LOCK,
};

/// One meeting at a time: the models use most of the CPU.
static JOB_LOCK: Mutex<()> = Mutex::new(());

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Job {
    /// Transcript from the tracks, then notes.
    Everything,
    /// Notes only, from the saved transcript.
    Notes,
}

const NO_MODEL: &str = "Meeting transcripts need an on-device transcription model. Download one in Settings → Transcription, then choose Redo transcript.";
const NO_WRITER: &str = "Choose a model in Settings → Model to write notes. Ollama and LM Studio run on this computer. The transcript is ready.";
/// Answer tokens allowed for the notes.
const NOTES_MAX_TOKENS: u32 = 4096;
/// Time allowed for one notes request: a model on this computer can take
/// minutes to read a long meeting.
const LOCAL_ATTEMPT: Duration = Duration::from_secs(10 * 60);
const HOSTED_ATTEMPT: Duration = Duration::from_secs(3 * 60);

/// Starts (or queues) work on a meeting. Returns false when that meeting is
/// already being worked on or waiting its turn.
pub(crate) fn spawn<R: Runtime>(app: AppHandle<R>, dir: PathBuf, job: Job) -> bool {
    if !super::mark_running(&dir) {
        return false;
    }
    let thread_dir = dir.clone();
    let result = std::thread::Builder::new()
        .name("clipy-meeting".into())
        .spawn(move || {
            let dir = thread_dir;
            {
                let _one_at_a_time = JOB_LOCK.lock();
                if let Err(message) = run(&app, &dir, job) {
                    tracing::warn!("meeting processing stopped: {message}");
                    write_status(&app, &dir, "failed", &message);
                }
            }
            super::mark_done(&dir);
            super::announce(&app, &dir);
        });
    if let Err(error) = result {
        tracing::warn!("meeting thread could not start: {error}");
        super::mark_done(&dir);
        return false;
    }
    true
}

fn run<R: Runtime>(app: &AppHandle<R>, dir: &Path, job: Job) -> Result<(), String> {
    if job == Job::Everything || read_meeting(dir).is_none() {
        transcript(app, dir)?;
    }
    write_status(app, dir, "writing", "Writing notes");
    notes_for(app, dir);
    write_status(app, dir, "ready", "");
    Ok(())
}

fn transcript<R: Runtime>(app: &AppHandle<R>, dir: &Path) -> Result<(), String> {
    write_status(
        app,
        dir,
        "transcribing",
        "Transcribing each side of the call",
    );
    let read = |name: &str| -> Option<Vec<f32>> {
        let path = dir.join(name);
        if !path.is_file() {
            return None;
        }
        match track::read_track(&path) {
            Ok(pcm) => Some(pcm),
            Err(error) => {
                tracing::warn!(file = name, "meeting track unreadable: {error}");
                None
            }
        }
    };
    let mic_pcm = read(track::MIC_FILE);
    let call_pcm = read(track::SYSTEM_FILE).ok_or("The call track could not be read.")?;
    let cancel = AtomicBool::new(false);

    let mic = match &mic_pcm {
        Some(pcm) => transcribe(app, dir, pcm, &cancel)?,
        None => Vec::new(),
    };
    let call = transcribe(app, dir, &call_pcm, &cancel)?;

    write_status(app, dir, "voices", "Telling the voices on the call apart");
    let turns = voices(app, &call_pcm);
    let mic_level = mic_pcm.as_deref().map(level::envelope);
    let call_level = level::envelope(&call_pcm);
    let duration_ms = metadata_duration(dir)
        .unwrap_or(call_pcm.len() as u64 * 1000 / u64::from(track::TRACK_RATE));
    drop(call_pcm);
    drop(mic_pcm);

    let mut meeting = assemble::assemble(&assemble::Input {
        mic: &mic,
        call: &call,
        turns: turns.as_deref(),
        mic_level: mic_level.as_deref(),
        call_level: Some(&call_level),
        duration_ms,
    });
    meeting.title = crate::local::normalized_title(dir);
    meeting.app = std::fs::read(dir.join(super::CALL_FILE))
        .ok()
        .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
        .and_then(|v| v["app"].as_str().map(str::to_string));

    let _lock = FILE_LOCK.lock();
    // A transcript made again keeps what the user did with the last one: the
    // names go to the voices that spoke at the same times, and the notes stay
    // (linked again to the new lines) until new notes replace them, so a
    // provider that is down never costs the notes and their ticks.
    if let Some(previous) = read_meeting(dir) {
        meeting.carry_names(&previous);
        if let Some(mut notes) = previous.notes {
            let parsed = notes::parse(&notes.markdown);
            notes.sources = sources::link(&parsed.lines, &meeting.utterances);
            meeting.notes = Some(notes);
            meeting.notes_state = NotesState::Ready;
        }
    }
    tracing::info!(
        lines = meeting.utterances.len(),
        voices = meeting.speakers.len(),
        echo_dropped = meeting.echo_dropped,
        voices_split = meeting.voices_split,
        "meeting transcript assembled"
    );
    save_meeting(dir, &meeting).map_err(|e| format!("The meeting could not be saved: {e}"))?;
    Ok(())
}

fn metadata_duration(dir: &Path) -> Option<u64> {
    std::fs::read(dir.join("metadata.json"))
        .ok()
        .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
        .and_then(|m| m["duration_ms"].as_u64())
}

/// The label of the on-device model the tracks will be transcribed with.
pub(crate) fn transcription_model_label<R: Runtime>(app: &AppHandle<R>) -> Option<String> {
    if let Some(model) = crate::transcription_models::chosen_model(app) {
        return Some(model.label().to_string());
    }
    settings_local_model(app).map(|model| model.spec().label.to_string())
}

/// The downloaded model chosen in Clipy Local's own transcription settings,
/// when it is installed.
fn settings_local_model<R: Runtime>(app: &AppHandle<R>) -> Option<clipy_local_stt::LocalModelId> {
    use clipy_local_edition::settings::{transcription_plan, TranscriptionPlan};
    let settings = crate::local::settings::load_settings(app);
    match transcription_plan(&settings) {
        TranscriptionPlan::Local(model) => {
            let model = clipy_local_stt::LocalModelId::parse(model.id())?;
            clipy_local_stt::model_status(model, None)
                .installed
                .then_some(model)
        }
        _ => None,
    }
}

/// One track's transcript with the on-device model, cleaned and spelled as
/// the main transcript is.
fn transcribe<R: Runtime>(
    app: &AppHandle<R>,
    dir: &Path,
    pcm: &[f32],
    cancel: &AtomicBool,
) -> Result<Vec<TrackSegment>, String> {
    if pcm.is_empty() {
        return Ok(Vec::new());
    }
    let words = crate::transcription_dictionary::prompt_words(dir);
    let transcript = if let Some(model) = crate::transcription_models::chosen_model(app) {
        crate::transcription_models::transcribe(model, pcm, cancel, &words)?
    } else {
        let model = settings_local_model(app).ok_or(NO_MODEL)?;
        clipy_local_stt::transcribe_local_with_words(
            pcm,
            model,
            None,
            &words,
            &mut |_| {},
            &clipy_local_stt::CancelToken::new(),
        )
        .map_err(|e| e.to_string())?
    };
    let mut segments: Vec<Value> = transcript
        .segments
        .iter()
        .filter(|s| !s.text.trim().is_empty())
        .map(|s| {
            serde_json::json!({
                "startMs": s.start_ms,
                "endMs": s.end_ms.max(s.start_ms),
                "text": s.text.trim(),
            })
        })
        .collect();
    crate::transcript_cleanup::clean_segments(
        &mut segments,
        transcript.language.as_deref(),
        |_| false,
    );
    crate::transcription_dictionary::correct_segments(dir, &mut segments, |_| false);
    Ok(segments
        .into_iter()
        .map(|s| TrackSegment {
            start_ms: s["startMs"].as_u64().unwrap_or(0),
            end_ms: s["endMs"].as_u64().unwrap_or(0),
            text: s["text"].as_str().unwrap_or("").to_string(),
        })
        .collect())
}

/// The call track's voices, when the voice models are installed (downloading
/// them first if meeting notes are on and they are missing). `None` means
/// the call side stays one speaker, "Others".
fn voices<R: Runtime>(app: &AppHandle<R>, pcm: &[f32]) -> Option<Vec<SpeakerTurn>> {
    if !clipy_local_stt::voices_status(None).installed && super::enabled(app) {
        download_voices(app);
    }
    if !clipy_local_stt::voices_status(None).installed {
        return None;
    }
    let started = std::time::Instant::now();
    match clipy_local_stt::diarize(pcm, None, &clipy_local_stt::CancelToken::new()) {
        Ok(turns) => {
            tracing::info!(
                turns = turns.len(),
                audio_seconds = pcm.len() as f64 / f64::from(track::TRACK_RATE),
                took_ms = started.elapsed().as_millis() as u64,
                "call track split into voices"
            );
            Some(
                turns
                    .into_iter()
                    .map(|t| SpeakerTurn {
                        start_ms: t.start_ms,
                        end_ms: t.end_ms,
                        speaker: t.speaker,
                    })
                    .collect(),
            )
        }
        Err(error) => {
            tracing::warn!("voices could not be told apart: {error}");
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Voice models
// ---------------------------------------------------------------------------

#[derive(Default)]
struct VoicesDownload {
    running: bool,
    error: Option<String>,
}

fn voices_download() -> &'static Mutex<VoicesDownload> {
    static STATE: OnceLock<Mutex<VoicesDownload>> = OnceLock::new();
    STATE.get_or_init(Default::default)
}

pub(crate) fn voices_dto() -> VoicesDto {
    let status = clipy_local_stt::voices_status(None);
    let state = voices_download().lock();
    VoicesDto {
        installed: status.installed,
        downloading: state.running,
        size_bytes: status.size_bytes,
        error: state.error.clone(),
    }
}

pub(crate) fn download_voices_in_background<R: Runtime>(app: AppHandle<R>) {
    if clipy_local_stt::voices_status(None).installed || voices_download().lock().running {
        return;
    }
    let _ = std::thread::Builder::new()
        .name("clipy-voices".into())
        .spawn(move || download_voices(&app));
}

/// Blocking. One download at a time; a second caller waits for the first.
fn download_voices<R: Runtime>(app: &AppHandle<R>) {
    static ONE: Mutex<()> = Mutex::new(());
    let _one = ONE.lock();
    if clipy_local_stt::voices_status(None).installed {
        return;
    }
    {
        let mut state = voices_download().lock();
        state.running = true;
        state.error = None;
    }
    let _ = app.emit(
        EVENT_VOICES_PROGRESS,
        serde_json::json!({ "fraction": 0.0, "state": "downloading" }),
    );
    let mut last = 0.0f64;
    let result = clipy_local_stt::download_voices(
        None,
        &mut |fraction| {
            if fraction - last >= 0.02 || fraction >= 1.0 {
                last = fraction;
                let _ = app.emit(
                    EVENT_VOICES_PROGRESS,
                    serde_json::json!({ "fraction": fraction, "state": "downloading" }),
                );
            }
        },
        &clipy_local_stt::CancelToken::new(),
    );
    let mut state = voices_download().lock();
    state.running = false;
    match result {
        Ok(_) => {
            tracing::info!("voice models installed");
            let _ = app.emit(
                EVENT_VOICES_PROGRESS,
                serde_json::json!({ "fraction": 1.0, "state": "installed" }),
            );
        }
        Err(error) => {
            tracing::warn!("voice models could not be downloaded: {error}");
            state.error = Some(error.to_string());
            let _ = app.emit(
                EVENT_VOICES_PROGRESS,
                serde_json::json!({ "fraction": last, "state": "failed" }),
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Notes
// ---------------------------------------------------------------------------

/// The model provider that writes the notes, with where the text goes and
/// whether it runs on this computer; or why there is none.
pub(crate) fn notes_writer<R: Runtime>(
    app: &AppHandle<R>,
) -> Result<(ProviderConfig, Recipient, bool), String> {
    let settings = crate::local::settings::load_settings(app);
    let keys = crate::local::settings::load_keys(app);
    match moment_provider(&settings, &keys) {
        MomentProvider::Ready { config, recipient } => {
            let local = recipient.is_this_computer();
            Ok((config, recipient, local))
        }
        MomentProvider::RulesOnly => Err(NO_WRITER.into()),
        MomentProvider::Unusable { message } => Err(message),
    }
}

fn set_notes_state<R: Runtime>(app: &AppHandle<R>, dir: &Path, state: NotesState) {
    let _lock = FILE_LOCK.lock();
    if let Some(mut meeting) = read_meeting(dir) {
        meeting.notes_state = state;
        if let Err(error) = save_meeting(dir, &meeting) {
            tracing::warn!("meeting notes state not saved: {error}");
        }
    }
    drop(_lock);
    super::announce(app, dir);
}

fn notes_for<R: Runtime>(app: &AppHandle<R>, dir: &Path) {
    let Some(meeting) = read_meeting(dir) else {
        return;
    };
    if meeting.utterances.is_empty() {
        set_notes_state(
            app,
            dir,
            NotesState::Failed {
                message: "No speech was transcribed, so there is nothing to write notes from."
                    .into(),
            },
        );
        return;
    }
    let (mut config, recipient, local) = match notes_writer(app) {
        Ok(writer) => writer,
        Err(message) => {
            set_notes_state(app, dir, NotesState::Failed { message });
            return;
        }
    };
    config.attempt_timeout = if local { LOCAL_ATTEMPT } else { HOSTED_ATTEMPT };
    // Recorded before anything is sent, so the AREC never understates it.
    if let Err(error) = crate::local::record_notes_recipient(dir, recipient.clone()) {
        tracing::warn!("disclosure not updated, notes not requested: {error:#}");
        set_notes_state(
            app,
            dir,
            NotesState::Failed {
                message:
                    "Clipy could not record where the transcript would go, so it was not sent."
                        .into(),
            },
        );
        return;
    }
    set_notes_state(app, dir, NotesState::Writing);
    let budget = if local {
        notes::LOCAL_BUDGET_CHARS
    } else {
        notes::HOSTED_BUDGET_CHARS
    };
    let ctx = Context {
        title: meeting.title.clone(),
        started: None,
        app: meeting.app.clone(),
        user_notes: None,
        vocabulary: crate::transcription_dictionary::prompt_words(dir),
    };
    let handle = tauri::async_runtime::handle();
    let ask = |prompt: &Prompt| {
        handle.block_on(clipy_local_moments::complete_text(
            &config,
            &prompt.system,
            &prompt.user,
            NOTES_MAX_TOKENS,
        ))
    };
    let started = std::time::Instant::now();
    let generated = notes::generate(&meeting, &ctx, budget, rand::random::<u64>(), ask);
    let written_by = format!("{} ({})", recipient.name, recipient.host);
    let state = match generated {
        Ok(generated) => {
            tracing::info!(
                requests = generated.requests,
                took_ms = started.elapsed().as_millis() as u64,
                "meeting notes written"
            );
            let _lock = FILE_LOCK.lock();
            // Re-read: a rename may have landed while the model was writing.
            let mut latest = read_meeting(dir).unwrap_or(meeting);
            let parsed = notes::parse(&generated.markdown);
            let links = sources::link(&parsed.lines, &latest.utterances);
            latest.notes = Some(Notes {
                markdown: generated.markdown,
                title: generated.title,
                decisions: generated.decisions,
                action_items: generated.action_items,
                sources: links,
                written_by,
                written_at_ms: now_ms(),
            });
            latest.notes_state = NotesState::Ready;
            if let Err(error) = save_meeting(dir, &latest) {
                tracing::warn!("meeting notes not saved: {error}");
            }
            drop(_lock);
            super::announce(app, dir);
            return;
        }
        Err(NotesError::Ask(error)) => {
            // `describe` and the reason never hold a key or the transcript.
            tracing::warn!(error = %error.describe(), "meeting notes request failed");
            NotesState::Failed {
                message: format!(
                    "{written_by} {}. Choose Write notes again to retry.",
                    clipy_local_edition::disclosure::failure_reason(&error)
                ),
            }
        }
        Err(NotesError::Empty) => NotesState::Failed {
            message: format!("{written_by} answered with no notes. Choose Write notes again to retry, or try another model."),
        },
        Err(NotesError::NoTranscript) => NotesState::Failed {
            message: "No speech was transcribed, so there is nothing to write notes from.".into(),
        },
    };
    set_notes_state(app, dir, state);
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}