use std::collections::{BTreeSet, HashMap}; use std::io::{BufWriter, Write}; const SENTENCE_ENDERS: [char; 3] = ['.', '!', '?']; const CLAUSE_ENDERS: [char; 3] = [',', ';', ':']; /// How many of the 5 books of Cicero's "De finibus bonorum et malorum" in corpus.txt to train on, counted from the first. /// Every book adds variety to the generated text at the cost of binary size (about 30 KB per book). const BOOKS_INCLUDED: usize = 5; fn main() { println!("cargo::rerun-if-changed=corpus.txt"); let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir = std::env::var("OUT_DIR").unwrap(); let corpus = std::fs::read_to_string(format!("{manifest_dir}/corpus.txt")).expect("Failed to read corpus.txt"); let prose = select_books(&corpus, BOOKS_INCLUDED); let normalized = normalize(&prose); assert!(normalized.is_ascii(), "The corpus must normalize to plain ASCII so that character counts equal byte counts"); // Cicero's paragraphing is discarded, since the runtime draws paragraph lengths suited to English body placeholder text instead let token_strings = tokenize(&normalized); assert!(token_strings.len() <= u16::MAX as usize, "Corpus has {} tokens but positions must fit in a u16", token_strings.len()); // The vocabulary is kept in lexicographic order so that neighboring words share prefixes for front coding let vocabulary: Vec<&str> = token_strings.iter().map(String::as_str).collect::>().into_iter().collect(); assert!(vocabulary.len() <= u16::MAX as usize, "Vocabulary has {} words but indices must fit in a u16", vocabulary.len()); let index_of: HashMap<&str, u16> = vocabulary.iter().enumerate().map(|(index, &word)| (word, index as u16)).collect(); let tokens: Vec = token_strings.iter().map(|word| index_of[word.as_str()]).collect(); let coded_vocabulary = front_code(&vocabulary); let out_path = format!("{out_dir}/corpus_data.rs"); let file = std::fs::File::create(&out_path).expect("Failed to create corpus_data.rs"); let mut out = BufWriter::new(file); writeln!(out, "// Auto-generated by build.rs from corpus.txt. Do not edit.").unwrap(); writeln!(out).unwrap(); // The corpus as vocabulary indices, in reading order writeln!(out, "static TOKENS: &[u16] = &[").unwrap(); for chunk in tokens.chunks(32) { write!(out, " ").unwrap(); for &token in chunk { write!(out, " {token},").unwrap(); } writeln!(out).unwrap(); } writeln!(out, "];").unwrap(); writeln!(out).unwrap(); // The front-coded vocabulary, decoded at runtime by `Corpus::build` writeln!(out, "const VOCABULARY_LEN: usize = {};", vocabulary.len()).unwrap(); write!(out, "static VOCABULARY: &[u8] = b\"").unwrap(); for &byte in &coded_vocabulary { write!(out, "{}", std::ascii::escape_default(byte)).unwrap(); } writeln!(out, "\";").unwrap(); } /// Keeps the prose of the first `books` books. Book boundaries are the "Liber ..." heading lines. /// The headings and anything before the first one (the work's title) are not prose and are dropped. fn select_books(corpus: &str, books: usize) -> String { let mut prose = String::new(); let mut book_number = 0; for line in corpus.lines() { if is_book_heading(line) { book_number += 1; continue; } if book_number == 0 || book_number > books { continue; } prose.push_str(line); prose.push('\n'); } assert!(book_number >= books, "corpus.txt has {book_number} book headings but BOOKS_INCLUDED is {books}"); prose } fn is_book_heading(line: &str) -> bool { let mut words = line.split_whitespace(); words.next() == Some("Liber") && words.next().is_some() && words.next().is_none() } /// Turns the corpus into lowercase prose whose only punctuation trails words. Quotation marks and brackets are dropped, /// ellipses become periods, and em-dashes become spaces (or vanish before punctuation, which joins the preceding word). fn normalize(text: &str) -> String { let mut normalized = text.replace(['\'', '(', ')', '[', ']'], "").replace("...", "."); for punctuation in SENTENCE_ENDERS.into_iter().chain(CLAUSE_ENDERS) { normalized = normalized.replace(&format!("\u{2014}{punctuation}"), &punctuation.to_string()); } normalized.replace('\u{2014}', " ").to_lowercase() } /// Splits the prose into word tokens, dropping name abbreviations and `POTENTIALLY_OBJECTIONABLE_WORDS`, /// and thinning the punctuation to English density (see `CLAUSE_WORDS` and `MAX_QUESTION_WORDS`). fn tokenize(text: &str) -> Vec { /// Latin puts a comma before every subordinate, relative, and coordinated clause where English mostly has none, /// so a comma is dropped when one of these words follows it. #[rustfmt::skip] const CLAUSE_WORDS: &[&str] = &[ // Subordinating conjunctions "ut", "uti", "ne", "si", "nisi", "cum", "quod", "quia", "quoniam", "quam", "quamquam", "quamvis", "quin", "dum", "donec", "ubi", "quando", "cur", "utrum", "an", "sive", "seu", "etsi", "tamquam", "velut", "quasi", // Relative and interrogative pronouns "qui", "quae", "quem", "quos", "quas", "quibus", "quo", "qua", "cuius", "quorum", "quarum", "quid", "quis", "quicquid", "quidquid", "quicquam", "quisquis", "quantum", "quanta", "quanto", "quot", "qualis", "quale", "quales", "quotiens", // Coordinating conjunctions "et", "atque", "ac", "aut", "vel", "nec", "neque", ]; /// Questions and exclamations longer than this many words become statements, /// since Cicero's dialogue asks a question an order of magnitude more often than in English. const MAX_QUESTION_WORDS: usize = 4; /// Abbreviated Roman first names, as in "Q. Tuberonem", whose period would otherwise read as a sentence end. const NAME_ABBREVIATIONS: &[&str] = &["a.", "ap.", "c.", "cn.", "d.", "f.", "l.", "m.", "mam.", "n.", "p.", "q.", "ser.", "sex.", "sp.", "t.", "ti.", "v."]; /// Inevitably some client will notice one of these generated words, get offended, and throw the designer under the bus, /// even though it's just Latin (and even in English, these aren't even inherently offensive depending on context). But it's /// better to err on the safe side for the sake of users to avoid accidentally causing anyone professional embarrassment. const POTENTIALLY_OBJECTIONABLE_WORDS: &[&str] = &["cum", "homo", "rectum", "sex"]; let is_abbreviation = |word: &str| NAME_ABBREVIATIONS.contains(&word.trim_end_matches(CLAUSE_ENDERS)); let words: Vec<&str> = text.split_whitespace().filter(|word| !is_abbreviation(word)).collect(); let mut tokens: Vec = Vec::with_capacity(words.len()); let mut words_in_sentence = 0; for (index, &word) in words.iter().enumerate() { // A quotation that ended inside a sentence leaves marks like "?," of which only the last belongs to the prose let letters = word.trim_end_matches(|c: char| c.is_ascii_punctuation()); let last_mark = word[letters.len()..].chars().last(); let mut word: String = letters.chars().chain(last_mark).collect(); let next_is_clause_word = words .get(index + 1) .is_some_and(|next| CLAUSE_WORDS.contains(&next.trim_end_matches(|c: char| c.is_ascii_punctuation()))); if word.ends_with(',') && next_is_clause_word { word.pop(); } words_in_sentence += 1; if word.ends_with(['?', '!']) && words_in_sentence > MAX_QUESTION_WORDS { word.pop(); word.push('.'); } if word.ends_with(SENTENCE_ENDERS) { words_in_sentence = 0; } // An objectionable word is dropped only now, so the punctuation around it was thinned as if it were there. // Its own mark passes to the word before it, where a sentence end outranks a clause mark. if POTENTIALLY_OBJECTIONABLE_WORDS.contains(&letters) { let mark = word.chars().last().filter(|c| c.is_ascii_punctuation()); if let Some(mark) = mark && let Some(previous) = tokens.last_mut() { if SENTENCE_ENDERS.contains(&mark) && previous.ends_with(CLAUSE_ENDERS) { previous.pop(); } if !previous.ends_with(|c: char| c.is_ascii_punctuation()) { previous.push(mark); } } words_in_sentence = words_in_sentence.saturating_sub(1); continue; } tokens.push(word); } tokens } /// Front-codes the sorted vocabulary as (shared prefix length, suffix length, suffix bytes) per word. /// Sorted Latin word forms share long stems, so this roughly halves the vocabulary bytes. fn front_code(vocabulary: &[&str]) -> Vec { let mut coded = Vec::new(); let mut previous = ""; for &word in vocabulary { let shared = previous.bytes().zip(word.bytes()).take_while(|(a, b)| a == b).count().min(u8::MAX as usize); let suffix = &word[shared..]; assert!(suffix.len() <= u8::MAX as usize, "Word {word:?} is too long to front-code"); coded.push(shared as u8); coded.push(suffix.len() as u8); coded.extend_from_slice(suffix.as_bytes()); previous = word; } coded }