Cotton code
151 lines · 6.5 KB · RustRaw
//! Person or machine, measured: an invented inbox (`who_corpus.txt`) and the answer a person would give for each//! sender, held to the rule. Run with `--nocapture` to see the accuracy by kind and every miss.use std::collections::BTreeMap;use super::*;pub(super) struct Case {    pub(super) line: usize,    pub(super) kind: String,    pub(super) name: Option<String>,    pub(super) address: String,    pub(super) subject: String,    pub(super) facts: Vec<String>,    pub(super) text: String,    pub(super) answer: Who,}pub(super) fn corpus(source: &str) -> Vec<Case> {    let mut out = Vec::new();    for (i, line) in source.lines().enumerate() {        let line_no = i + 1;        let line = line.trim();        if line.is_empty() || line.starts_with('#') {            continue;        }        let cols: Vec<&str> = line.split('|').map(str::trim).collect();        assert_eq!(cols.len(), 6, "line {line_no}: six columns: {line}");        let from = cols[1];        let (name, address) = match from.rsplit_once('<') {            Some((name, rest)) => (Some(name.trim().to_string()).filter(|n| !n.is_empty()), rest.trim_end_matches('>').to_string()),            None => (None, from.to_string()),        };        let answer = match cols[5] {            "person" => Who::Person,            "machine" => Who::Machine,            "junk" => Who::Junk,            other => panic!("line {line_no}: answer {other}"),        };        out.push(Case {            line: line_no,            kind: cols[0].to_string(),            name,            address,            subject: cols[2].to_string(),            facts: cols[3].split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect(),            text: cols[4].replace("\\n", "\n"),            answer,        });    }    out}fn fact<'a>(case: &'a Case, key: &str) -> Option<&'a str> {    case.facts.iter().find_map(|f| f.strip_prefix(key).and_then(|rest| rest.strip_prefix('=')))}fn has(case: &Case, key: &str) -> bool {    case.facts.iter().any(|f| f == key)}const OWNER: &str = "you@owner.example";fn judged(case: &Case) -> Who {    let address = case.address.to_lowercase();    // The mail went to `to=` when the corpus says so, else to the owner.    let to = fact(case, "to").unwrap_or(OWNER);    who(&Facts {        address: &address,        blocked: has(case, "blocked"),        owner_verdict: fact(case, "owner"),        in_people: has(case, "people"),        written_to: has(case, "written"),        stored_kind: fact(case, "stored"),        name: case.name.as_deref(),        subject: Some(case.subject.as_str()).filter(|s| !s.is_empty()),        text: Some(case.text.as_str()),        to_a_list: to != OWNER && is_list_address(to),    })    .0}/// How the rule did over a set: right by kind, and each miss with the way it went wrong.fn measure<'a>(set: &str, cases: &'a [Case]) -> (usize, Vec<(&'a Case, Who)>) {    let mut by_kind: BTreeMap<&str, (usize, usize)> = BTreeMap::new();    let mut misses = Vec::new();    for case in cases {        let got = judged(case);        let tally = by_kind.entry(case.kind.as_str()).or_default();        tally.1 += 1;        if got == case.answer {            tally.0 += 1;        } else {            misses.push((case, got));        }    }    let right: usize = by_kind.values().map(|t| t.0).sum();    let hidden = misses.iter().filter(|(c, got)| c.answer == Who::Person && *got != Who::Person).count();    let cluttered = misses.iter().filter(|(c, got)| c.answer != Who::Person && *got == Who::Person).count();    println!("{set}: {right}/{} right ({:.1}%); a person called a machine {hidden}, a machine called a person {cluttered}", cases.len(), 100.0 * right as f64 / cases.len() as f64);    for (kind, (ok, all)) in &by_kind {        println!("  {kind:<14} {ok:>3}/{all:<3} {:>5.1}%", 100.0 * *ok as f64 / *all as f64);    }    for (case, got) in &misses {        println!("  miss: line {} {} {} <{}> \"{}\": said {}, a person says {}", case.line, case.kind, case.name.as_deref().unwrap_or(""), case.address, case.subject, got.as_str(), case.answer.as_str());    }    (right, misses)}/// The misses the rule cannot answer from what the phone holds, each with why. A new miss fails the test.const KNOWN: &[(&str, &str)] = &[    ("me@kavya.io", "one name, a domain of her own and `me@`: nothing but the words says a person"),    ("k.iyer@iyerconsulting.example", "\"Dad\" is no one's full name, and his firm's domain is not a webmail"),    ("info@jobakerphoto.example", "a one-person business at a role mailbox, written to: the shape is above writing to it, as for a support desk"),    ("team@imrancodes.example", "the same, at team@"),];/// RULE (MAIL.md "Person or machine"): over the invented inbox the rule was made against (210 senders) it answers/// as a person would for at least 97 in 100, and misses only where the phone holds nothing that could tell/// ([`KNOWN`]). Before it read the mail a sender wrote (cde4c29ea3: the address and the owner's acts alone) it was/// 162 of 210.#[test]fn the_rule_over_an_invented_inbox() {    let cases = corpus(include_str!("who_corpus.txt"));    assert!(cases.len() >= 200, "{} senders", cases.len());    let (right, misses) = measure("tuned set", &cases);    let unknown: Vec<String> = misses        .iter()        .filter(|(case, _)| !KNOWN.iter().any(|(address, _)| *address == case.address))        .map(|(case, got)| format!("line {} <{}>: said {}", case.line, case.address, got.as_str()))        .collect();    assert!(unknown.is_empty(), "new misses: {unknown:#?}");    assert!(right * 100 >= cases.len() * 97, "{right}/{}", cases.len());}/// RULE: over a second inbox written apart from the rule and never tuned on (`who_holdout.txt`, 131 senders by a/// writer who saw only the kinds and the facts), the rule holds a floor. A change that lowers it is a worse rule,/// however well it does on the tuned set; a change made to pass a single held-out sender is not allowed. Measured/// first at 117 of 131 (cde4c29ea3's rule: 94); 119 after the two general misses it showed were fixed (any automated/// reminder or alert, and a greeting to many, "Dear customers").#[test]fn the_rule_over_a_held_out_inbox() {    let cases = corpus(include_str!("who_holdout.txt"));    assert!(cases.len() >= 100, "{} senders", cases.len());    let (right, _) = measure("held-out set", &cases);    assert!(right * 100 >= cases.len() * HELD_OUT_FLOOR, "{right}/{}", cases.len());}/// The held-out set's floor, in percent: 119 of 131 is 90.8.const HELD_OUT_FLOOR: usize = 90;