Cotton code
108 lines · 5.8 KB · RustRaw
//! Recordings turned into text on this Mac.//!//!   pnpm meetings:transcribe --queue --base <url> --device-id <id> --token-file <path> [--key-file <path>] [--languages en,hi] [--most N]//!   pnpm meetings:transcribe --file <audio> [--languages en,hi] [--per-line-language|--per-window-language] [--out transcript.json]//!//! --queue   drains the person's recordings waiting for a transcriber the Mac//!           may be (`transcribe_on` any or mac), once, as `film:import --queue`//!           does: each claimed, its sealed audio opened here, transcribed and//!           landed (speakers, lines, the meeting `ready` last). launchd//!           runs the same drain on its own: `pnpm -s meetings:job:install`//!           (the meetings job script, cotton_mac::meetings_job).//! --file    one audio file here, nothing sent anywhere: the transcript as JSON//!           on stdout (or --out), and what it took on stderr. How the box//!           measures the step.//! --languages  the person's languages, in order (one to three); the//!           catalogue's first when not given.//! --no-summaries  with --queue, do not summarise afterwards. Otherwise the//!           run then summarises every ready meeting that wants it on this//!           Mac's local model (`meetings:summarise --queue`)://!           on by default once the model is fetched;//!           until then each such meeting says why (`model_missing`).//!//! The engine is sherpa-onnx under `$MEETINGS_PYTHON` (else `$VOICE_PYTHON`),//! its models under `$MEETINGS_MODELS` (else `$VOICE_MODELS`): see//! scripts/meetings/engine.py.use std::path::PathBuf;use std::process::ExitCode;use cotton_mac::device::DeviceArgs;use cotton_mac::meetings::{self, Engine};use serde_json::json;const USAGE: &str = "meetings-transcribe (--queue <device flags> | --file <audio> [--out <path>]) [--languages en,hi] [--per-line-language|--per-window-language] [--most N] [--place mac] [--no-summaries] [--summary-model <id>]";fn repo() -> PathBuf {    std::env::var_os("COTTON_REPO").map(PathBuf::from).unwrap_or_else(|| cotton_store::manifest_dir().join("../.."))}fn main() -> ExitCode {    let argv: Vec<String> = std::env::args().skip(1).collect();    let mut device = DeviceArgs::default();    let (mut queue, mut file, mut out, mut languages, mut per_line, mut most, mut place) = (false, None, None, Vec::new(), None, 20usize, "mac".to_string());    let (mut summaries, mut summary_model) = (true, None::<String>);    let mut at = 0;    while at < argv.len() {        let flag = argv[at].as_str();        let value = argv.get(at + 1).cloned().unwrap_or_default();        match flag {            "--queue" => queue = true,            "--no-summaries" => summaries = false,            "--summary-model" => { summary_model = Some(value.clone()); at += 1; }            "--per-line-language" => per_line = Some(true),            "--per-window-language" => per_line = Some(false),            "--file" => { file = Some(PathBuf::from(&value)); at += 1; }            "--out" => { out = Some(PathBuf::from(&value)); at += 1; }            "--languages" => { languages = value.split(',').map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect(); at += 1; }            "--most" => { most = value.parse().unwrap_or(most); at += 1; }            "--place" => { place = value.clone(); at += 1; }            "-h" | "--help" => { println!("{USAGE}"); return ExitCode::SUCCESS; }            _ if device.take(flag, &value) => at += 1,            other => { eprintln!("unknown flag {other}\n{USAGE}"); return ExitCode::from(2); }        }        at += 1;    }    let mut engine = Engine::from_env(&repo(), languages);    engine.per_line_language = per_line;    engine.place = place;    if let Some(audio) = file {        return match meetings::transcribe(&engine, &audio) {            Ok((transcript, took)) => {                let body = serde_json::to_string_pretty(&json!({ "transcript": transcript, "took": took })).unwrap_or_default();                match out {                    Some(path) => { if let Err(e) = std::fs::write(&path, body) { eprintln!("{}: {e}", path.display()); return ExitCode::FAILURE; } }                    None => println!("{body}"),                }                eprintln!("{:.1} s of audio in {:.1} s: {:.2} minutes of audio a minute", took.audio_s, took.wall_s, took.audio_s / took.wall_s.max(0.001));                ExitCode::SUCCESS            }            Err(why) => { eprintln!("{why}"); ExitCode::FAILURE }        };    }    if !queue {        eprintln!("{USAGE}");        return ExitCode::from(2);    }    let device = match device.open() {        Ok(device) => device,        Err(why) => { eprintln!("{why}"); return ExitCode::FAILURE; }    };    let work = match tempfile::tempdir() { Ok(dir) => dir, Err(e) => { eprintln!("{e}"); return ExitCode::FAILURE; } };    let drained = match meetings::drain(&device.object, &engine, work.path(), most, &mut |done| eprintln!("meetings: {} {}{}", done.meeting, done.status, done.why.as_deref().map(|w| format!(" ({w})")).unwrap_or_default())) {        Ok(done) => done,        Err(why) => { eprintln!("{why}"); return ExitCode::FAILURE; }    };    // The same job then writes the summaries, on this Mac's local model.    let summarised = if summaries {        let id = summary_model.unwrap_or_else(|| cotton_mac::summarise::catalogue().default);        match cotton_mac::summarise::drain(&device.object, &id, most, &mut |s| eprintln!("meetings: {} {}{}", s.meeting, if s.done { "summarised" } else { "not summarised" }, s.why.as_deref().map(|w| format!(" ({w})")).unwrap_or_default())) {            Ok(done) => done,            Err(why) => { eprintln!("meetings: summaries: {why}"); Vec::new() }        }    } else {        Vec::new()    };    println!("{}", json!({ "drained": drained, "summarised": summarised }));    ExitCode::SUCCESS}