Cotton code
534 lines · 20.6 KB · RustRaw
//! Cotton Meetings' pure rules: how long audio is cut into windows for a//! transcriber, how the windows' lines come back together as one transcript//! (overlap de-duplicated, one set of speakers across windows, a language per//! line), and the open bundle's text, SRT and JSON (apps/meetings/CORE.md).//!//! Every transcriber — the Mac's sherpa-onnx drain, the phone while charging,//! an outside service when the owner turns one on — hands its windows to//! [`merge`], so a better engine changes the words and never the rules.//!//! No voice is remembered past one meeting: a speaker's embedding lives only//! inside one [`merge`] call, to tell the windows' voices apart, and is never//! returned.use serde::{Deserialize, Serialize};/// How long a window is, and how much two neighbours share, by default:/// thirty seconds suits Whisper's own window and is long enough for a/// transducer; three seconds of overlap holds a word cut at either edge.pub const WINDOW_MS: i64 = 30_000;pub const OVERLAP_MS: i64 = 3_000;/// How far a cut may move from its ideal place to land in a silence.pub const CUT_SLACK_MS: i64 = 5_000;/// How alike two windows' voices must be (cosine) to be one speaker.pub const SAME_VOICE: f32 = 0.55;/// A stretch of audio, in milliseconds from the start of the recording.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Span {    pub start_ms: i64,    pub end_ms: i64,}/// One window a transcriber reads.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Window {    pub index: usize,    pub start_ms: i64,    pub end_ms: i64,}/// Cut `duration_ms` of audio into windows of about `window_ms` sharing/// `overlap_ms` with the next. When `speech` (voice-activity spans) is given,/// each cut moves, within [`CUT_SLACK_MS`], to the middle of the silence/// nearest its ideal place, so a window rarely ends inside a word; a window/// holding no speech at all is left out. Windows are in order and cover every/// spoken moment.pub fn windows(duration_ms: i64, speech: &[Span], window_ms: i64, overlap_ms: i64) -> Vec<Window> {    let duration_ms = duration_ms.max(0);    let window_ms = window_ms.max(1_000);    let overlap_ms = overlap_ms.clamp(0, window_ms / 2);    if duration_ms == 0 {        return Vec::new();    }    let mut speech: Vec<Span> = speech.iter().copied().filter(|s| s.end_ms > s.start_ms).collect();    speech.sort_by_key(|s| s.start_ms);    let silences = silences_of(&speech, duration_ms);    let mut out = Vec::new();    let mut start = 0i64;    loop {        let ideal = start + window_ms;        if ideal >= duration_ms {            out.push(Window { index: 0, start_ms: start, end_ms: duration_ms });            break;        }        let end = if speech.is_empty() { ideal } else { cut_near(ideal, &silences, start + window_ms / 2) };        out.push(Window { index: 0, start_ms: start, end_ms: end });        start = (end - overlap_ms).max(start + 1);    }    if !speech.is_empty() {        out.retain(|w| speech.iter().any(|s| s.start_ms < w.end_ms && s.end_ms > w.start_ms));    }    for (index, window) in out.iter_mut().enumerate() {        window.index = index;    }    out}fn silences_of(speech: &[Span], duration_ms: i64) -> Vec<Span> {    let mut out = Vec::new();    let mut at = 0;    for s in speech {        if s.start_ms > at {            out.push(Span { start_ms: at, end_ms: s.start_ms });        }        at = at.max(s.end_ms);    }    if at < duration_ms {        out.push(Span { start_ms: at, end_ms: duration_ms });    }    out}/// The cut nearest `ideal` within the slack: the middle of a silence when one/// is near, else `ideal` itself; never before `floor`.fn cut_near(ideal: i64, silences: &[Span], floor: i64) -> i64 {    let mut best: Option<(i64, i64)> = None;    for s in silences {        let lo = s.start_ms.max(ideal - CUT_SLACK_MS).max(floor);        let hi = s.end_ms.min(ideal + CUT_SLACK_MS);        if lo >= hi {            continue;        }        let cut = ((s.start_ms + s.end_ms) / 2).clamp(lo, hi);        let far = (cut - ideal).abs();        if best.map_or(true, |(_, b)| far < b) {            best = Some((cut, far));        }    }    best.map_or(ideal, |(cut, _)| cut)}/// One timed line as a transcriber hears it, times absolute (from the start of/// the recording).#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Line {    /// The window's label for the voice; empty when the engine cannot tell    /// voices apart (a phone), and every such line is the recording's one voice.    #[serde(default)]    pub speaker: String,    pub start_ms: i64,    pub end_ms: i64,    pub text: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub language: Option<String>,}/// A voice inside one window: its label there and, when the engine gives/// one, an embedding to match it with the other windows' voices.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct WindowSpeaker {    pub label: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub embedding: Option<Vec<f32>>,}/// What a transcriber hands back for one window.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct WindowHeard {    pub index: usize,    pub start_ms: i64,    pub end_ms: i64,    /// The window's language when the engine detected one for all of it; a    /// line's own language wins.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub language: Option<String>,    #[serde(default)]    pub lines: Vec<Line>,    #[serde(default)]    pub speakers: Vec<WindowSpeaker>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Speaker {    pub label: String,}/// The one shape every transcriber's result takes (CORE.md "transcript").#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Transcript {    #[serde(default)]    pub by: String,    #[serde(default)]    pub languages: Vec<String>,    #[serde(default)]    pub speakers: Vec<Speaker>,    #[serde(default)]    pub lines: Vec<Line>,}/// The windows' lines as one transcript.////// * **Overlap**: where two windows share audio, a line belongs to the window///   whose middle it is nearer: the earlier keeps what starts before the///   middle of the shared stretch, the later what starts after it./// * **Speakers**: each window's voices are matched to the voices already///   heard — by embedding (cosine at least [`SAME_VOICE`]) when both have one,///   else by speaking at the same moment in the shared stretch — and a voice///   that matches none is a new speaker. Labels are then renumbered S1, S2…///   in order of first speech./// * **Languages**: a line's own, else its window's; the transcript's in///   order of first speech.pub fn merge(by: &str, heard: &[WindowHeard]) -> Transcript {    let mut heard: Vec<&WindowHeard> = heard.iter().collect();    heard.sort_by_key(|w| (w.start_ms, w.index));    // Global voices: (id, centroid, count).    let mut voices: Vec<(usize, Option<Vec<f32>>, usize)> = Vec::new();    // The one voice of lines whose engine told no voices apart (no label).    let mut untold: Option<usize> = None;    let mut kept: Vec<(usize, Line)> = Vec::new();    for (at, window) in heard.iter().enumerate() {        let prev = at.checked_sub(1).map(|p| heard[p]);        let next = heard.get(at + 1);        let keep_from = prev.filter(|p| p.end_ms > window.start_ms).map_or(i64::MIN, |p| (window.start_ms + p.end_ms) / 2);        let keep_until = next.filter(|n| n.start_ms < window.end_ms).map_or(i64::MAX, |n| (n.start_ms + window.end_ms) / 2);        // Map this window's labels to global voices.        let mut labels: Vec<String> = window.speakers.iter().map(|s| s.label.clone()).collect();        for line in &window.lines {            if !labels.contains(&line.speaker) {                labels.push(line.speaker.clone());            }        }        let mut map: Vec<(String, usize)> = Vec::new();        let mut taken: Vec<usize> = Vec::new();        for label in &labels {            let embedding = window.speakers.iter().find(|s| &s.label == label).and_then(|s| s.embedding.clone());            let by_voice = embedding.as_ref().and_then(|e| {                voices                    .iter()                    .filter(|(id, c, _)| c.is_some() && !taken.contains(id))                    .map(|(id, c, _)| (*id, cosine(e, c.as_ref().unwrap())))                    .filter(|(_, sim)| *sim >= SAME_VOICE)                    .max_by(|a, b| a.1.total_cmp(&b.1))                    .map(|(id, _)| id)            });            let by_time = || {                let prev = prev?;                let shared = Span { start_ms: window.start_ms, end_ms: prev.end_ms };                let mine: Vec<&Line> = window.lines.iter().filter(|l| &l.speaker == label && l.end_ms > shared.start_ms && l.start_ms < shared.end_ms).collect();                let mut best: Option<(usize, i64)> = None;                for (id, line) in kept.iter().filter(|(_, l)| l.end_ms > shared.start_ms) {                    let together: i64 = mine.iter().map(|m| (m.end_ms.min(line.end_ms) - m.start_ms.max(line.start_ms)).max(0)).sum();                    if together > 0 && !taken.contains(id) && best.map_or(true, |(_, b)| together > b) {                        best = Some((*id, together));                    }                }                best.map(|(id, _)| id)            };            let id = if label.is_empty() {                *untold.get_or_insert_with(|| {                    voices.push((voices.len(), None, 0));                    voices.len() - 1                })            } else {                by_voice.or_else(by_time).unwrap_or_else(|| {                    voices.push((voices.len(), None, 0));                    voices.len() - 1                })            };            if let Some(e) = embedding {                let voice = &mut voices[id];                voice.1 = Some(match voice.1.take() {                    None => e,                    Some(c) => c.iter().zip(&e).map(|(a, b)| (a * voice.2 as f32 + b) / (voice.2 as f32 + 1.0)).collect(),                });                voice.2 += 1;            }            taken.push(id);            map.push((label.clone(), id));        }        for line in &window.lines {            if line.start_ms < keep_from || line.start_ms >= keep_until || line.text.trim().is_empty() {                continue;            }            let id = map.iter().find(|(l, _)| l == &line.speaker).map(|(_, id)| *id).unwrap_or(0);            let mut line = line.clone();            line.text = line.text.trim().to_string();            if line.language.is_none() {                line.language = window.language.clone();            }            kept.push((id, line));        }    }    kept.sort_by_key(|(_, l)| (l.start_ms, l.end_ms));    let mut order: Vec<usize> = Vec::new();    for (id, _) in &kept {        if !order.contains(id) {            order.push(*id);        }    }    let label_of = |id: usize| format!("S{}", order.iter().position(|o| *o == id).unwrap_or(0) + 1);    let mut languages: Vec<String> = Vec::new();    let lines: Vec<Line> = kept        .into_iter()        .map(|(id, mut line)| {            line.speaker = label_of(id);            if let Some(lang) = &line.language {                if !languages.contains(lang) {                    languages.push(lang.clone());                }            }            line        })        .collect();    Transcript {        by: by.to_string(),        languages,        speakers: (1..=order.len()).map(|n| Speaker { label: format!("S{n}") }).collect(),        lines,    }}/// One person's track of a call's notes (Take notes): their own audio, heard alone.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct TrackHeard {    /// The track's id, which is its voice's label in the transcript.    pub track: String,    #[serde(default)]    pub windows: Vec<WindowHeard>,}/// A call's notes as one transcript (chat CONTRACT "Take notes"): each track is one person, so each is merged on its/// own as one voice whatever its windows' labels say, labelled by its track, and the tracks' lines are then laid/// together by time. Who said what is the track's, never a guess.pub fn merge_tracks(by: &str, tracks: &[TrackHeard]) -> Transcript {    let mut lines: Vec<Line> = Vec::new();    let mut speakers: Vec<Speaker> = Vec::new();    let mut languages: Vec<String> = Vec::new();    for track in tracks {        let one: Vec<WindowHeard> = track            .windows            .iter()            .map(|w| {                let mut w = w.clone();                w.speakers.clear();                for line in &mut w.lines {                    line.speaker.clear();                }                w            })            .collect();        let heard = merge(by, &one);        if heard.lines.is_empty() {            continue;        }        speakers.push(Speaker { label: track.track.clone() });        for lang in heard.languages {            if !languages.contains(&lang) {                languages.push(lang);            }        }        lines.extend(heard.lines.into_iter().map(|mut l| {            l.speaker = track.track.clone();            l        }));    }    lines.sort_by(|a, b| (a.start_ms, a.end_ms, &a.speaker).cmp(&(b.start_ms, b.end_ms, &b.speaker)));    Transcript { by: by.to_string(), languages, speakers, lines }}fn cosine(a: &[f32], b: &[f32]) -> f32 {    if a.len() != b.len() || a.is_empty() {        return 0.0;    }    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();    let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();    let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();    if na == 0.0 || nb == 0.0 {        0.0    } else {        dot / (na * nb)    }}/// Per speaker: lines, milliseconds spoken, and when first heard.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct SpeakerFigures {    pub label: String,    pub lines: i64,    pub talk_ms: i64,    pub first_ms: i64,}pub fn speaker_figures(transcript: &Transcript) -> Vec<SpeakerFigures> {    transcript        .speakers        .iter()        .map(|s| {            let mine: Vec<&Line> = transcript.lines.iter().filter(|l| l.speaker == s.label).collect();            SpeakerFigures {                label: s.label.clone(),                lines: mine.len() as i64,                talk_ms: mine.iter().map(|l| (l.end_ms - l.start_ms).max(0)).sum(),                first_ms: mine.iter().map(|l| l.start_ms).min().unwrap_or(0),            }        })        .collect()}/// A line kept over a new transcription: one a person corrected.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct HeldLine {    pub start_ms: i64,    pub end_ms: i64,    pub text: String,    pub speaker: String,    #[serde(default)]    pub language: Option<String>,}/// `fresh` with every line written as its language is written/// (`crate::script`, one value: Telugu in Latin letters for now). Both/// landings, the Mac's and the phone's, pass the engine's transcript through/// this before it is kept; a person's corrected line is theirs and is not.pub fn as_written(fresh: &Transcript) -> Transcript {    let mut out = fresh.clone();    for line in &mut out.lines {        line.text = crate::script::as_written(&line.text);    }    out}/// `fresh` with every corrected line in `held` kept: a new line overlapping a/// held one by more than half of the shorter is dropped for it.pub fn keep_corrections(fresh: &Transcript, held: &[HeldLine]) -> Transcript {    let mut out = fresh.clone();    out.lines.retain(|line| {        !held.iter().any(|h| {            let shared = (line.end_ms.min(h.end_ms) - line.start_ms.max(h.start_ms)).max(0);            let shorter = (line.end_ms - line.start_ms).min(h.end_ms - h.start_ms).max(1);            shared * 2 > shorter        })    });    for h in held {        out.lines.push(Line { speaker: h.speaker.clone(), start_ms: h.start_ms, end_ms: h.end_ms, text: h.text.clone(), language: h.language.clone() });        if !out.speakers.iter().any(|s| s.label == h.speaker) {            out.speakers.push(Speaker { label: h.speaker.clone() });        }    }    out.lines.sort_by_key(|l| (l.start_ms, l.end_ms));    out}// ── the open bundle ─────────────────────────────────────────────────────────/// `h:mm:ss` (or `m:ss` under an hour) for the plain text.pub fn clock(ms: i64) -> String {    let s = ms.max(0) / 1000;    let (h, m, s) = (s / 3600, (s / 60) % 60, s % 60);    if h > 0 {        format!("{h}:{m:02}:{s:02}")    } else {        format!("{m}:{s:02}")    }}fn srt_clock(ms: i64) -> String {    let ms = ms.max(0);    format!("{:02}:{:02}:{:02},{:03}", ms / 3_600_000, (ms / 60_000) % 60, (ms / 1000) % 60, ms % 1000)}/// The name a speaker goes by in an export: their given name, else the label.pub fn said_by<'a>(label: &'a str, names: &'a [(String, String)]) -> &'a str {    names.iter().find(|(l, _)| l == label).map(|(_, n)| n.as_str()).filter(|n| !n.trim().is_empty()).unwrap_or(label)}/// Plain text: a speaker's turn starts with their name and the time; their/// following lines join it until someone else speaks.pub fn to_text(title: &str, transcript: &Transcript, names: &[(String, String)]) -> String {    let mut out = String::new();    if !title.trim().is_empty() {        out.push_str(title.trim());        out.push_str("\n\n");    }    let mut last: Option<&str> = None;    for line in &transcript.lines {        if last != Some(line.speaker.as_str()) {            if last.is_some() {                out.push_str("\n\n");            }            out.push_str(&format!("{} [{}]\n", said_by(&line.speaker, names), clock(line.start_ms)));            out.push_str(&line.text);        } else {            out.push(' ');            out.push_str(&line.text);        }        last = Some(line.speaker.as_str());    }    if !transcript.lines.is_empty() {        out.push('\n');    }    out}/// SubRip: one cue a line, the speaker's name before the words.pub fn to_srt(transcript: &Transcript, names: &[(String, String)]) -> String {    let mut out = String::new();    for (n, line) in transcript.lines.iter().enumerate() {        out.push_str(&format!("{}\n{} --> {}\n{}: {}\n\n", n + 1, srt_clock(line.start_ms), srt_clock(line.end_ms.max(line.start_ms + 1)), said_by(&line.speaker, names), line.text));    }    out}/// The transcript as JSON, each speaker with the name given to them.pub fn to_json(title: &str, transcript: &Transcript, names: &[(String, String)]) -> serde_json::Value {    serde_json::json!({        "title": title,        "by": transcript.by,        "languages": transcript.languages,        "speakers": transcript.speakers.iter().map(|s| serde_json::json!({            "label": s.label,            "name": names.iter().find(|(l, _)| l == &s.label).map(|(_, n)| n.clone()),        })).collect::<Vec<_>>(),        "lines": transcript.lines,    })}// ── measuring ───────────────────────────────────────────────────────────────/// Words for scoring: lower case, punctuation gone (letters, marks and digits/// of any script kept).pub fn score_words(text: &str) -> Vec<String> {    text.chars()        .map(|c| if c.is_alphanumeric() || c == '\'' || is_mark(c) { c.to_lowercase().next().unwrap_or(c) } else { ' ' })        .collect::<String>()        .split_whitespace()        .map(str::to_string)        .collect()}fn is_mark(c: char) -> bool {    // Combining marks (Indic vowel signs and viramas among them).    matches!(c as u32, 0x0300..=0x036F | 0x0900..=0x0903 | 0x093A..=0x094F | 0x0951..=0x0957 | 0x0962..=0x0963 | 0x0C00..=0x0C04 | 0x0C3C..=0x0C56 | 0x0C62..=0x0C63)}/// Word error rate of `hypothesis` against `reference`: (substitutions +/// deletions + insertions) / reference words, with the counts.pub fn word_errors(reference: &str, hypothesis: &str) -> (usize, usize) {    let r = score_words(reference);    let h = score_words(hypothesis);    let mut prev: Vec<usize> = (0..=h.len()).collect();    for i in 1..=r.len() {        let mut row = vec![i; h.len() + 1];        for j in 1..=h.len() {            let sub = prev[j - 1] + usize::from(r[i - 1] != h[j - 1]);            row[j] = sub.min(prev[j] + 1).min(row[j - 1] + 1);        }        prev = row;    }    (prev[h.len()], r.len())}#[cfg(test)]#[path = "meetings_tests.rs"]mod tests;