Cotton code
303 lines · 13.8 KB · RustRaw
//! Cotton Meetings on the Mac: recordings turned into text, as film import//! drains what waits for conversion (apps/meetings/CORE.md).//!//! The one transcription step: audio in, the transcript out (timed lines,//! speaker labels, a language per line). The engine is sherpa-onnx, run by//! `scripts/meetings/engine.py` (voice activity, speaker separation over the//! whole recording, the person's languages identified per window, the voice//! catalogue's second-pass model per language); the RULES are the core's —//! the windows ([`cotton_rules::meetings::windows`], cut in silence) and the//! merge into one transcript ([`cotton_rules::meetings::merge`]) — so the//! phone, the Mac and an outside service give one shape.//!//! [`drain`] walks the person's `meetings_meeting` rows waiting for a//! transcriber the Mac may be (`transcribe_on` any or mac), claims one//! through the object's `meeting_claim` (refused when a phone took it first),//! fetches its audio sealed and opens it here, transcribes//! it and lands the speakers and lines, the meeting going `ready` LAST so a//! reader never sees a half-written transcript as ready. A failure says why//! (`status_why`) and leaves the audio as it was: it can be asked again.use std::path::{Path, PathBuf};use std::process::Command;use cotton_rules::meetings::{self as rules, Span, Transcript, WindowHeard};use serde::Deserialize;use serde_json::{json, Value};use crate::object::{Act, ObjectClient};pub const MEETING: &str = "meetings_meeting";pub const SPEAKER: &str = "meetings_speaker";pub const LINE: &str = "meetings_line";/// How the engine is run.#[derive(Debug, Clone)]pub struct Engine {    /// The Python holding sherpa-onnx (`$MEETINGS_PYTHON`, else `$VOICE_PYTHON`, else python3).    pub python: PathBuf,    /// `scripts/meetings/engine.py`.    pub script: PathBuf,    /// The person's languages, in order (one to three).    pub languages: Vec<String>,    pub threads: usize,    /// The language per speech segment (true) or per window (false); none, the    /// engine's default: per segment once the person has two or more languages.    pub per_line_language: Option<bool>,    /// Where on this Mac the step runs, for `transcribed_by` (`mac`, `box`).    pub place: String,}impl Engine {    pub fn from_env(repo: &Path, languages: Vec<String>) -> Engine {        let python = std::env::var_os("MEETINGS_PYTHON").or_else(|| std::env::var_os("VOICE_PYTHON")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("python3"));        Engine { python, script: repo.join("scripts/meetings/engine.py"), languages, threads: 4, per_line_language: None, place: "mac".into() }    }    /// What a run for these languages reads (`engine.py check`: every model    /// is the catalogue's, from the one models folder), refused when this Mac    /// lacks one. `--file` and `--queue` both pass here first, so they choose    /// alike, and the queue claims nothing it could not transcribe.    pub fn check(&self) -> Result<Value, String> {        let languages = self.languages.join(",");        let mut args = vec!["check"];        if !languages.is_empty() {            args.extend(["--languages", languages.as_str()]);        }        let found = self.run(&args, None)?;        if found["ok"] == true {            return Ok(found);        }        let missing: Vec<&str> = found["missing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();        Err(format!("this Mac lacks {} under {}: pnpm voice:fetch {} (with VOICE_MODELS set to that folder)", missing.join(", "), found["folder"].as_str().unwrap_or("its models folder"), missing.join(" ")))    }    fn run(&self, args: &[&str], stdin: Option<&Value>) -> Result<Value, String> {        use std::io::Write;        let mut cmd = Command::new(&self.python);        cmd.arg("-I").arg(&self.script).args(args);        cmd.stdin(if stdin.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() });        cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());        let mut child = cmd.spawn().map_err(|e| format!("the engine did not start ({}): {e}", self.python.display()))?;        if let Some(body) = stdin {            child.stdin.take().expect("piped").write_all(body.to_string().as_bytes()).map_err(|e| e.to_string())?;        }        let out = child.wait_with_output().map_err(|e| e.to_string())?;        if !out.status.success() {            let said = String::from_utf8_lossy(&out.stderr);            let last = said.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no word");            return Err(format!("the engine stopped: {last}"));        }        serde_json::from_slice(&out.stdout).map_err(|e| format!("the engine's answer did not read: {e}"))    }}#[derive(Debug, Deserialize)]struct Speech {    duration_ms: i64,    speech: Vec<Span>,}#[derive(Debug, Deserialize)]struct Heard {    by: String,    windows: Vec<WindowHeard>,    #[serde(default)]    seconds: Value,}/// What one transcription took, besides the transcript.#[derive(Debug, Clone, Default, serde::Serialize)]pub struct Took {    pub audio_s: f64,    pub wall_s: f64,    pub windows: usize,    pub engine: Value,    /// The models the run read, by part (`vad`, `segmentation`, `embedding`, `lid`?, `second:<lang>`).    pub models: Value,}/// The one step: a recording's audio file (any container the engine reads)/// in, the transcript out.pub fn transcribe(engine: &Engine, audio: &Path) -> Result<(Transcript, Took), String> {    let started = std::time::Instant::now();    let chosen = engine.check()?;    let path = audio.to_string_lossy().to_string();    let speech: Speech = serde_json::from_value(engine.run(&["speech", &path, "--threads", &engine.threads.to_string()], None)?).map_err(|e| e.to_string())?;    let windows = rules::windows(speech.duration_ms, &speech.speech, rules::WINDOW_MS, rules::OVERLAP_MS);    let ask = json!({        "windows": windows,        "speech": speech.speech,        "languages": engine.languages,        "threads": engine.threads,        "per_line_language": engine.per_line_language,    });    let heard: Heard = serde_json::from_value(engine.run(&["hear", &path, "-"], Some(&ask))?).map_err(|e| e.to_string())?;    let by = format!("{}:{}", engine.place, heard.by);    let transcript = rules::merge(&by, &heard.windows);    let took = Took { audio_s: speech.duration_ms as f64 / 1000.0, wall_s: started.elapsed().as_secs_f64(), windows: windows.len(), engine: heard.seconds, models: chosen["models"].clone() };    Ok((transcript, took))}// ── the queue ───────────────────────────────────────────────────────────────/// One recording drained, said for the run's summary.#[derive(Debug, Clone, serde::Serialize)]pub struct Drained {    pub meeting: String,    pub status: String,    pub why: Option<String>,    pub lines: usize,    pub speakers: usize,    pub took: Option<Took>,}fn str_of<'a>(row: &'a Value, key: &str) -> &'a str {    row["data"][key].as_str().unwrap_or_default()}/// The rows waiting for a transcriber the Mac may be, oldest asked first.pub fn waiting(rows: &[Value]) -> Vec<Value> {    let mut out: Vec<Value> = rows        .iter()        .filter(|row| str_of(row, "status") == "waiting" && matches!(str_of(row, "transcribe_on"), "any" | "mac" | "") && !str_of(row, "audio").is_empty())        .cloned()        .collect();    out.sort_by(|a, b| str_of(a, "asked_at").cmp(str_of(b, "asked_at")).then(str_of(a, "started_at").cmp(str_of(b, "started_at"))));    out}/// Drain every waiting recording once (at most `most`), as `film:import --queue` does.pub fn drain(object: &ObjectClient, engine: &Engine, work: &Path, most: usize, each: &mut dyn FnMut(&Drained)) -> Result<Vec<Drained>, String> {    // Before any claim: a Mac lacking a model leaves every recording waiting    // for a transcriber that has it (a phone on charge, or this Mac once fetched).    engine.check()?;    let rows = object.device_rows(MEETING).ok_or("this run holds no data key: sign this Mac in with seal-device")?.map_err(|e| e.to_string())?;    let mut out = Vec::new();    for row in waiting(&rows).into_iter().take(most) {        let done = one(object, engine, work, &row);        each(&done);        out.push(done);    }    Ok(out)}fn one(object: &ObjectClient, engine: &Engine, work: &Path, row: &Value) -> Drained {    let id = row["id"].as_str().unwrap_or_default().to_string();    let fail = |why: &str| {        let _ = object.post_act("meeting_failed", &json!({ "id": id, "why": why }));        Drained { meeting: id.clone(), status: "failed".into(), why: Some(why.into()), lines: 0, speakers: 0, took: None }    };    // The object's claim is the one truth: a phone on charge may have taken it.    if object.post_act("meeting_claim", &json!({ "id": id, "by": "mac" })).is_err() {        return Drained { meeting: id.clone(), status: "waiting".into(), why: Some("not_claimed".into()), lines: 0, speakers: 0, took: None };    }    let key = str_of(row, "audio").to_string();    let ext = key.rsplit('.').next().unwrap_or("wav");    let local = work.join(format!("{id}.{ext}"));    if let Err(why) = crate::files::fetch_opened(object, &key, &local) {        eprintln!("meetings: {id}: {why}");        return fail("no_audio");    }    let result = transcribe(engine, &local);    let _ = std::fs::remove_file(&local);    let (transcript, took) = match result {        Ok(done) => done,        Err(why) => {            eprintln!("meetings: {id}: {why}");            return fail("engine_failed");        }    };    match land(object, &id, &transcript) {        Ok((lines, speakers)) => Drained { meeting: id, status: "ready".into(), why: None, lines, speakers, took: Some(took) },        Err(why) => {            eprintln!("meetings: {id}: {why}");            fail("engine_failed")        }    }}/// The transcript's speakers and lines at the object, the meeting `ready` last./// Old lines go; a line a person corrected stays; a name stays with its label.pub fn land(object: &ObjectClient, meeting: &str, fresh: &Transcript) -> Result<(usize, usize), String> {    let mine = |table: &str| -> Result<Vec<Value>, String> {        let rows = object.device_rows(table).ok_or("no data key")?.map_err(|e| e.to_string())?;        Ok(rows.into_iter().filter(|r| str_of(r, "meeting") == meeting).collect())    };    let old_speakers = mine(SPEAKER)?;    let old_lines = mine(LINE)?;    let label_of = |speaker: &str| old_speakers.iter().find(|s| s["id"].as_str() == Some(speaker)).map(|s| str_of(s, "label").to_string()).unwrap_or_default();    let held: Vec<rules::HeldLine> = old_lines        .iter()        .filter(|l| l["data"]["edited"].as_bool() == Some(true))        .map(|l| rules::HeldLine {            start_ms: l["data"]["start_ms"].as_i64().unwrap_or(0),            end_ms: l["data"]["end_ms"].as_i64().unwrap_or(0),            text: str_of(l, "text").to_string(),            speaker: label_of(str_of(l, "speaker")),            language: l["data"]["language"].as_str().map(str::to_string),        })        .collect();    let transcript = rules::keep_corrections(&rules::as_written(fresh), &held);    let e = |r: Result<Value, crate::object::ObjectError>| r.map(|_| ()).map_err(|e| e.to_string());    for old in &old_lines {        e(object.act(Act::Delete, LINE, old["id"].as_str().unwrap_or_default(), &json!({})))?;    }    let figures = rules::speaker_figures(&transcript);    let mut ids: Vec<(String, String)> = Vec::new();    for f in &figures {        let data = json!({ "meeting": meeting, "label": f.label, "lines": f.lines, "talk_ms": f.talk_ms, "first_ms": f.first_ms });        let id = match old_speakers.iter().find(|s| str_of(s, "label") == f.label) {            Some(s) => {                let id = s["id"].as_str().unwrap_or_default().to_string();                e(object.act(Act::Update, SPEAKER, &id, &json!({ "lines": f.lines, "talk_ms": f.talk_ms, "first_ms": f.first_ms })))?;                id            }            None => {                let id = new_id();                e(object.act(Act::Create, SPEAKER, &id, &data))?;                id            }        };        ids.push((f.label.clone(), id));    }    for gone in old_speakers.iter().filter(|s| !figures.iter().any(|f| f.label == str_of(s, "label"))) {        e(object.act(Act::Delete, SPEAKER, gone["id"].as_str().unwrap_or_default(), &json!({})))?;    }    for (n, l) in transcript.lines.iter().enumerate() {        let speaker = ids.iter().find(|(label, _)| label == &l.speaker).map(|(_, id)| id.clone());        let was_held = held.iter().any(|h| h.start_ms == l.start_ms && h.text == l.text);        e(object.act(            Act::Create,            LINE,            &new_id(),            &json!({ "meeting": meeting, "speaker": speaker, "position": n + 1, "start_ms": l.start_ms, "end_ms": l.end_ms, "text": l.text, "language": l.language, "edited": was_held }),        ))?;    }    let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    e(object.act(        Act::Update,        MEETING,        meeting,        &json!({            "status": "ready", "status_why": null,            "languages": transcript.languages.join(","),            "speakers": figures.len(), "lines": transcript.lines.len(),            "transcribed_by": transcript.by, "transcribed_at": now,        }),    ))?;    Ok((transcript.lines.len(), figures.len()))}/// A fresh row id (UUID v4 form).pub fn new_id() -> String {    let mut b: [u8; 16] = rand::random();    b[6] = (b[6] & 0x0f) | 0x40;    b[8] = (b[8] & 0x3f) | 0x80;    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();    format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])}#[cfg(test)]#[path = "meetings_tests.rs"]mod tests;