//! `pnpm ink:corpus` (scripts/ink/corpus-harness.sh): an ink corpus — the //! phone's kept groups, `*.jsonl`, and `labels.json` — replayed through the //! core's reader on this Mac, in seconds (`cotton_core::ink::replay`). The //! letter model is Core ML, which only Apple's platforms run, so it answers //! from a child process (`scripts/ink/corpus-harness/main.swift`, built by //! the script and named by INK_MODEL_CLI): one group's features a line in, //! its 62 probabilities a line out, each group asked once. //! //! ink_corpus the report: each group as kept, then regrouped on its timings; //! a held-out folder's expected.json and contract fixtures checked too //! ink_corpus --floors 0,0.1 the curve `letter_confidence` is chosen on //! ink_corpus --band the model's best scores, right, wrong and noise //! ink_corpus --lag each letter's wait, on the synthetic walk and the 24 traces //! (INK_FIXTURES: crates/cotton-core/tests/fixtures/ink) use std::collections::{BTreeMap, HashMap}; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use cotton_core::ink::input::Features; use cotton_core::ink::reader::{Model, Reader}; use cotton_core::ink::replay; /// The Core ML child, every answer kept by the group's key. struct CoreMl { child: Child, input: ChildStdin, output: BufReader, answers: HashMap>, } impl CoreMl { fn start(path: &Path) -> Result { let mut child = Command::new(path) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .map_err(|error| format!("{}: {error}", path.display()))?; let input = child.stdin.take().ok_or("the model child has no stdin")?; let output = BufReader::new(child.stdout.take().ok_or("the model child has no stdout")?); Ok(Self { child, input, output, answers: HashMap::new() }) } } impl Model for CoreMl { fn probabilities(&mut self, features: &Features) -> Option> { let key = features.key(); if let Some(held) = self.answers.get(&key) { return Some(held.clone()); } let ask = serde_json::json!({ "points": features.points, "strokes": features.strokes }); writeln!(self.input, "{ask}").ok()?; self.input.flush().ok()?; let mut line = String::new(); self.output.read_line(&mut line).ok()?; let probabilities: Vec = serde_json::from_str(&line).ok()?; self.answers.insert(key, probabilities.clone()); Some(probabilities) } } impl Drop for CoreMl { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } } fn read(path: &Path) -> Result { std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display())) } fn run() -> Result { let arguments: Vec = std::env::args().skip(1).collect(); let cli = std::env::var("INK_MODEL_CLI").map_err(|_| "INK_MODEL_CLI names no model child (run it through pnpm ink:corpus)".to_string())?; let mut model = CoreMl::start(Path::new(&cli))?; let reader = Reader::shipped(); if arguments.first().map(String::as_str) == Some("--lag") { let fixtures = PathBuf::from(std::env::var("INK_FIXTURES").unwrap_or_else(|_| ".".into())); let measured = replay::lag(&read(&fixtures.join("ink-synthetic.json"))?, &read(&fixtures.join("ink-traces.json"))?, &reader, &mut model)?; return Ok(measured.iter().map(|set| set.line() + "\n").collect()); } let floors: Option> = arguments .iter() .position(|argument| argument == "--floors") .map(|at| arguments.get(at + 1).map(|list| list.split(',').filter_map(|floor| floor.parse().ok()).collect()).unwrap_or_default()); let folder = match arguments.first() { Some(folder) if !folder.starts_with("--") && floors.as_ref().is_none_or(|floors| !floors.is_empty()) => PathBuf::from(folder), _ => return Err("usage: ink_corpus [--floors 0,0.1,… | --band] | ink_corpus --lag".into()), }; let mut files = Vec::new(); let mut own = BTreeMap::new(); for entry in std::fs::read_dir(&folder).map_err(|error| format!("{}: {error}", folder.display()))? { let path = entry.map_err(|error| error.to_string())?.path(); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default().to_string(); if let Some(stem) = name.strip_suffix(".labels.json") { own.insert(format!("{stem}.jsonl"), read(&path)?); } else if name.ends_with(".jsonl") { files.push((name, read(&path)?)); } } let labels = folder.join("labels.json"); let labels = if labels.exists() { Some(read(&labels)?) } else { None }; let (groups, left_out) = replay::load(&files, labels.as_deref(), &own)?; for name in left_out { eprintln!("ink corpus: {name} holds no strokes, left out"); } if arguments.iter().any(|argument| argument == "--band") { return replay::band(&groups, &[0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.50], &replay::scrawls(500, 7), &mut model); } if let Some(floors) = floors { return replay::curve(&groups, &floors, &mut model); } let mut text = replay::report(&groups, &reader, &mut model).text; // A held-out folder (`pnpm ink:heldout`) says what the model read on it // and carries the input contract's fixtures: both must hold. let mut holds = true; let said = folder.join("expected.json"); if said.exists() { let (lines, held) = replay::expected(&groups, &read(&said)?, &mut model)?; text += &format!("\n{lines}"); holds &= held; } let fixtures = folder.join("contract/fixtures.jsonl"); if fixtures.exists() { let (line, held) = replay::contract(&read(&fixtures)?)?; text += &line; holds &= held; } if holds { Ok(text) } else { print!("{text}"); Err("the corpus does not read as it says (expected.json or the contract's fixtures)".into()) } } fn main() { match run() { Ok(text) => print!("{text}"), Err(error) => { eprintln!("ink-corpus: {error}"); std::process::exit(1); } } }