Cotton code
463 lines · 18.5 KB · RustRaw
//! A meeting's summary and actions, made from its transcript by a model on the//! person's own Mac (owner's decision, 17 Nov 2026://! no cloud model is called by Cotton). These are the RULES, the same for any//! model and any machine that runs one://!//! * [`parts`]: a long transcript is read in parts, each a run of whole//!   lines under a size, numbered so a model can say which line it read a//!   task in;//! * [`SYSTEM`], [`part_prompt`], [`merge_prompt`] and their schemas: what//!   the model is asked, and the JSON it must answer in;//! * [`check`]: what the model says is kept only where the transcript bears//!   it out. An owner is a speaker of the meeting or a name the transcript//!   says; a day is kept only when the words it came from are in the//!   transcript, and the day is worked out HERE from those words and the//!   meeting's own day ([`due_day`]), never taken from the model. The//!   summary never invents an owner or a date;//! * [`same_task`]: the parts' actions as one list, a task said twice once;//! * [`summary_text`] and [`actions_text`]: the meeting row's `summary`//!   (markdown points) and `actions` (one to do a line) columns.use chrono::{Datelike, Duration, NaiveDate, Weekday};use serde::{Deserialize, Serialize};use serde_json::{json, Value};use crate::meetings::Line;/// How many characters of transcript one part holds, by default: about three/// thousand tokens of English, so a 16 GB Mac's model reads a part with room/// for the question and the answer.pub const PART_CHARS: usize = 12_000;/// The most points one part's notes and the whole summary hold: the schema/// says so, so a model that would list every remark cannot (a 60-minute/// meeting's merge gave 29 before).pub const PART_POINTS: usize = 8;pub const SUMMARY_POINTS: usize = 10;/// How long one point and one task may be: a point is a sentence, not the/// rest of the meeting run on (a capped merge once put nine points in one).pub const POINT_CHARS: usize = 240;pub const TASK_CHARS: usize = 120;/// A speaker as the transcript knows them: a label (`S1`) and, where the/// person gave one, a name.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Voice {    pub label: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,}/// One part of a transcript, its lines rendered for the model.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Part {    pub index: usize,    /// The first and last line numbers in it (1-based, the transcript's own).    pub first: usize,    pub last: usize,    pub text: String,}fn clock(ms: i64) -> String {    let s = ms.max(0) / 1000;    if s >= 3600 {        format!("{}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60)    } else {        format!("{:02}:{:02}", s / 60, s % 60)    }}fn who_is(label: &str, voices: &[Voice]) -> String {    match voices.iter().find(|v| v.label == label).and_then(|v| v.name.as_deref()).filter(|n| !n.trim().is_empty()) {        Some(name) => format!("{name} ({label})"),        None => label.to_string(),    }}/// One line as the model reads it: `17 [03:12] Asha (S2): words`.pub fn render(n: usize, line: &Line, voices: &[Voice]) -> String {    format!("{n} [{}] {}: {}", clock(line.start_ms), who_is(&line.speaker, voices), line.text.trim())}/// The transcript in parts of whole lines, each at most `chars` long (a/// single longer line is a part of its own).pub fn parts(lines: &[Line], voices: &[Voice], chars: usize) -> Vec<Part> {    let mut out: Vec<Part> = Vec::new();    let mut text = String::new();    let mut first = 1;    for (i, line) in lines.iter().enumerate() {        let n = i + 1;        let row = render(n, line, voices);        if !text.is_empty() && text.len() + row.len() + 1 > chars {            out.push(Part { index: out.len(), first, last: n - 1, text: std::mem::take(&mut text) });            first = n;        }        if !text.is_empty() {            text.push('\n');        }        text.push_str(&row);    }    if !text.is_empty() {        out.push(Part { index: out.len(), first, last: lines.len(), text });    }    out}/// What the model is told, every time. The model's words are data beside/// this module (`meetings_summary/*.txt`), filled by [`fill`]: no person reads/// them, so they are not lines, and a rewording is a file, not a format string.pub const SYSTEM: &str = include_str!("meetings_summary/system.txt");const ABOUT: &str = include_str!("meetings_summary/about.txt");const WHICH: &str = include_str!("meetings_summary/which.txt");const PART: &str = include_str!("meetings_summary/part.txt");const MERGE: &str = include_str!("meetings_summary/merge.txt");/// `template` with each `{name}` replaced by its value, in one pass: a value/// (a transcript line, a title) that itself holds `{about}` is never read/// again as a placeholder.fn fill(template: &str, values: &[(&str, &str)]) -> String {    let mut out = String::with_capacity(template.len());    let mut rest = template;    while let Some(open) = rest.find('{') {        out.push_str(&rest[..open]);        let after = &rest[open + 1..];        match after.find('}').and_then(|close| values.iter().find(|(name, _)| *name == &after[..close]).map(|(_, v)| (close, v))) {            Some((close, value)) => {                out.push_str(value);                rest = &after[close + 1..];            }            None => {                out.push('{');                rest = after;            }        }    }    out.push_str(rest);    out}/// The line naming the meeting, or nothing when it has no title.fn about(title: Option<&str>) -> String {    title.filter(|t| !t.trim().is_empty()).map(|t| fill(ABOUT, &[("title", t.trim())])).unwrap_or_default()}/// The question for one part.pub fn part_prompt(title: Option<&str>, part: &Part, of: usize) -> String {    let which = if of > 1 {        fill(WHICH, &[("part", &(part.index + 1).to_string()), ("of", &of.to_string()), ("first", &part.first.to_string()), ("last", &part.last.to_string())])    } else {        String::new()    };    fill(PART, &[("about", &about(title)), ("which", &which), ("transcript", &part.text), ("unit", if of > 1 { "part" } else { "meeting" })])}/// The JSON a part's answer must be.pub fn part_schema() -> Value {    json!({        "type": "object",        "properties": {            "summary": { "type": "array", "items": { "type": "string", "maxLength": POINT_CHARS }, "maxItems": PART_POINTS },            "actions": {                "type": "array",                "items": {                    "type": "object",                    "properties": {                        "words": { "type": "string", "maxLength": TASK_CHARS },                        "who": { "type": ["string", "null"] },                        "due_said": { "type": ["string", "null"] },                        "line": { "type": ["integer", "null"] }                    },                    "required": ["words", "who", "due_said", "line"]                }            }        },        "required": ["summary", "actions"]    })}/// The question that makes the parts' points one summary.pub fn merge_prompt(title: Option<&str>, points: &[Vec<String>]) -> String {    let mut body = String::new();    for (i, p) in points.iter().enumerate() {        body.push_str(&format!("Part {}:\n", i + 1));        for point in p {            body.push_str(&format!("- {}\n", point.trim()));        }    }    fill(MERGE, &[("about", &about(title)), ("body", &body)])}pub fn merge_schema() -> Value {    json!({        "type": "object",        "properties": { "summary": { "type": "array", "items": { "type": "string", "maxLength": POINT_CHARS }, "maxItems": SUMMARY_POINTS } },        "required": ["summary"]    })}/// A part's answer, as the model gave it.#[derive(Debug, Clone, Default, Deserialize)]pub struct Heard {    #[serde(default)]    pub summary: Vec<String>,    #[serde(default)]    pub actions: Vec<HeardAction>,}#[derive(Debug, Clone, Default, Deserialize)]pub struct HeardAction {    #[serde(default)]    pub words: String,    #[serde(default)]    pub who: Option<String>,    #[serde(default)]    pub due_said: Option<String>,    #[serde(default)]    pub line: Option<i64>,}/// One action as the meeting keeps it: data, never prose.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Action {    /// The task, short, starting with a verb.    pub words: String,    /// Who will do it: a speaker's label (`S2`) or a name the transcript    /// says; none when nobody took it on.    #[serde(default)]    pub who: Option<String>,    /// The day it is due (`YYYY-MM-DD`), worked out from `due_said` and the    /// meeting's day; none when no day was said or the words name no one day.    #[serde(default)]    pub due: Option<String>,    /// The transcript's own words for when (`by Thursday`).    #[serde(default)]    pub due_said: Option<String>,    /// Where in the recording it was said.    #[serde(default)]    pub at_ms: Option<i64>,}fn fold(s: &str) -> String {    s.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()}/// Whether `name` is said in the transcript as a word (not inside another).fn said_as_word(name: &str, said: &str) -> bool {    let name = fold(name);    if name.chars().count() < 2 {        return false;    }    let mut from = 0;    while let Some(at) = said[from..].find(&name) {        let start = from + at;        let end = start + name.len();        let before = said[..start].chars().next_back();        let after = said[end..].chars().next();        if !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric) {            return true;        }        from = start + name.len().max(1);    }    false}/// The model's actions, kept only where the transcript bears them out (see/// the module's rules). `day` is the meeting's own day, where it was held.pub fn check(heard: &[HeardAction], lines: &[Line], voices: &[Voice], day: NaiveDate) -> Vec<Action> {    let said: String = fold(&lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n"));    let mut out = Vec::new();    for a in heard {        let words = a.words.split_whitespace().collect::<Vec<_>>().join(" ");        let mut chars = words.chars();        let words = match chars.next() {            Some(first) => first.to_uppercase().chain(chars).collect::<String>(),            None => continue,        };        let who = a.who.as_deref().map(str::trim).filter(|w| !w.is_empty() && !matches!(w.to_lowercase().as_str(), "null" | "none" | "nobody" | "unknown" | "-")).and_then(|w| {            let bare = w.trim_end_matches(')').rsplit('(').next().unwrap_or(w).trim();            if let Some(v) = voices.iter().find(|v| v.label.eq_ignore_ascii_case(bare) || v.label.eq_ignore_ascii_case(w)) {                return Some(v.label.clone());            }            let name = w.split('(').next().unwrap_or(w).trim();            if let Some(v) = voices.iter().find(|v| v.name.as_deref().is_some_and(|n| n.trim().eq_ignore_ascii_case(name))) {                return Some(v.label.clone());            }            said_as_word(name, &said).then(|| name.to_string())        });        let due_said = a.due_said.as_deref().map(str::trim).filter(|d| !d.is_empty() && !d.eq_ignore_ascii_case("null")).filter(|d| said.contains(&fold(d))).map(str::to_string);        let due = due_said.as_deref().and_then(|d| due_day(d, day)).map(|d| d.format("%Y-%m-%d").to_string());        let at_ms = a.line.and_then(|n| usize::try_from(n).ok()).filter(|n| *n >= 1).and_then(|n| lines.get(n - 1)).map(|l| l.start_ms);        out.push(Action { words, who, due, due_said, at_ms });    }    out}/// The words naming a day (`meetings_summary/days.json`): counted from the/// meeting's day, longest offset first, and the weekdays.#[derive(Deserialize)]struct DaysAfter {    days: i64,    words: Vec<String>,}#[derive(Deserialize)]struct WeekdayWords {    day: String,    words: Vec<String>,}#[derive(Deserialize)]struct Days {    days_after: Vec<DaysAfter>,    weekdays: Vec<WeekdayWords>,}fn days() -> &'static Days {    static DAYS: std::sync::OnceLock<Days> = std::sync::OnceLock::new();    DAYS.get_or_init(|| serde_json::from_str(include_str!("meetings_summary/days.json")).expect("meetings_summary/days.json parses"))}/// Whether `word` starts a word in `said` (both folded): a day word keeps its/// endings ("repatiki", "mondays") but is never the inside of another word.fn starts_a_word(word: &str, said: &str) -> bool {    let word = fold(word);    said.match_indices(&word).any(|(at, _)| !said[..at].chars().next_back().is_some_and(char::is_alphanumeric))}const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];/// The one day `said` names, counted from the meeting's `day`: today,/// tomorrow, the day after (English, Telugu, Hindi), a weekday (the next one/// after the meeting's day), the 25th (this month, or the next once it has/// passed), 25 November or November 25, or a written date. Words that name no/// one day ("this week", "early December") answer none.pub fn due_day(said: &str, day: NaiveDate) -> Option<NaiveDate> {    let s = fold(&crate::script::in_latin_letters(said));    if let Some(iso) = regex::Regex::new(r"\b(\d{4})-(\d{2})-(\d{2})\b").ok()?.captures(&s) {        return NaiveDate::from_ymd_opt(iso[1].parse().ok()?, iso[2].parse().ok()?, iso[3].parse().ok()?);    }    if let Some(after) = days().days_after.iter().find(|d| d.words.iter().any(|w| starts_a_word(w, &s))) {        return Some(day + Duration::days(after.days));    }    for named in &days().weekdays {        let Ok(weekday) = named.day.parse::<Weekday>() else { continue };        if named.words.iter().any(|w| starts_a_word(w, &s)) {            let ahead = (weekday.num_days_from_monday() as i64 - day.weekday().num_days_from_monday() as i64).rem_euclid(7);            return Some(day + Duration::days(if ahead == 0 { 7 } else { ahead }));        }    }    let month_of = |word: &str| MONTHS.iter().position(|m| word.starts_with(m) && word.len() >= 3).map(|i| i as u32 + 1);    let date = regex::Regex::new(r"\b(\d{1,2})(?:st|nd|rd|th)?(?:\s+of)?\s+([a-z]{3,9})\b").ok()?;    if let Some(c) = date.captures(&s) {        if let Some(m) = month_of(&c[2]) {            return in_year(day, m, c[1].parse().ok()?);        }    }    let date = regex::Regex::new(r"\b([a-z]{3,9})\s+(\d{1,2})(?:st|nd|rd|th)?\b").ok()?;    if let Some(c) = date.captures(&s) {        if let Some(m) = month_of(&c[1]) {            return in_year(day, m, c[2].parse().ok()?);        }    }    let nth = regex::Regex::new(r"\b(\d{1,2})(?:st|nd|rd|th)\b").ok()?;    if let Some(c) = nth.captures(&s) {        let d: u32 = c[1].parse().ok()?;        if let Some(this) = NaiveDate::from_ymd_opt(day.year(), day.month(), d).filter(|t| *t >= day) {            return Some(this);        }        let (y, m) = if day.month() == 12 { (day.year() + 1, 1) } else { (day.year(), day.month() + 1) };        return NaiveDate::from_ymd_opt(y, m, d);    }    None}/// Month `m`, day `d` on or after the meeting's day (this year, else next).fn in_year(day: NaiveDate, m: u32, d: u32) -> Option<NaiveDate> {    NaiveDate::from_ymd_opt(day.year(), m, d).filter(|t| *t >= day).or_else(|| NaiveDate::from_ymd_opt(day.year() + 1, m, d))}fn content_words(s: &str) -> Vec<String> {    const STOP: &[&str] = &["the", "a", "an", "to", "for", "of", "and", "on", "in", "with", "by", "about", "it", "this", "that"];    s.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty() && !STOP.contains(w)).map(str::to_string).collect()}/// Whether two actions are one task said twice: the same owner and most of/// the shorter one's words in the other.pub fn same_task(a: &Action, b: &Action) -> bool {    if a.who != b.who {        return false;    }    let (x, y) = (content_words(&a.words), content_words(&b.words));    let (short, long) = if x.len() <= y.len() { (&x, &y) } else { (&y, &x) };    if short.is_empty() {        return false;    }    let shared = short.iter().filter(|w| long.contains(w)).count();    shared * 3 >= short.len() * 2}/// The parts' actions as one list, in order, each task once (the first/// telling kept, a day from a later one filled in where the first had none).pub fn one_list(actions: Vec<Action>) -> Vec<Action> {    let mut out: Vec<Action> = Vec::new();    for a in actions {        match out.iter_mut().find(|k| same_task(k, &a)) {            Some(kept) => {                if kept.due.is_none() && a.due.is_some() {                    kept.due = a.due;                    kept.due_said = a.due_said;                }            }            None => out.push(a),        }    }    out}/// The `summary` column: one markdown point a line, each ending on a whole/// sentence (a point the length cap cut mid-sentence goes back to its last/// full stop).pub fn summary_text(points: &[String]) -> String {    points.iter().map(|p| whole_sentences(&p.split_whitespace().collect::<Vec<_>>().join(" "))).filter(|p| !p.is_empty()).map(|p| format!("- {p}")).collect::<Vec<_>>().join("\n")}fn whole_sentences(point: &str) -> String {    let ends = |c: char| matches!(c, '.' | '!' | '?' | '।');    if point.is_empty() || point.ends_with(ends) {        return point.to_string();    }    match point.char_indices().filter(|(i, c)| ends(*c) && point[i + c.len_utf8()..].starts_with(' ')).last() {        Some((i, c)) => point[..i + c.len_utf8()].to_string(),        None => point.to_string(),    }}/// The `actions` column: one to do a line, the owner and day after it where/// the meeting said them (`Send the quote — Ben (S2), by Thursday 19 Nov`).pub fn actions_text(actions: &[Action], voices: &[Voice]) -> String {    actions        .iter()        .map(|a| {            let mut line = a.words.clone();            let mut tail = Vec::new();            if let Some(w) = &a.who {                tail.push(if voices.iter().any(|v| &v.label == w) { who_is(w, voices) } else { w.clone() });            }            if let Some(d) = a.due.as_deref().and_then(|d| NaiveDate::parse_from_str(d, "%Y-%m-%d").ok()) {                tail.push(format!("by {}", d.format("%a %-d %b")));            } else if let Some(s) = &a.due_said {                tail.push(s.clone());            }            if !tail.is_empty() {                line.push_str(" — ");                line.push_str(&tail.join(", "));            }            line        })        .collect::<Vec<_>>()        .join("\n")}#[cfg(test)]#[path = "meetings_summary_tests.rs"]mod tests;