diff --git a/crates/bibclean/README.md b/crates/bibclean/README.md index 87b3c23..c95ccc3 100644 --- a/crates/bibclean/README.md +++ b/crates/bibclean/README.md @@ -175,6 +175,9 @@ bibclean books.ndjson | jq -c 'select(.slug_proposal.tier | IN("placeholder-auth |---|---|---| | `placeholder_title` | 4 | The whole title is "Untitled", "Document", "N/A" | | `placeholder_author` | 4 | The same, in the author field | +| `mojibake_title` | 3 | UTF-8 read as Windows-1252: "américain" | +| `mojibake_author` | 3 | The same, in the author field | +| `placeholder_suffix` | 2 | A placeholder author left on the end of the title: "… - Unknown" | | `path_title` | 4 | A file path sitting in the title | | `numeric_author` | 4 | An author field opening with a bare year or series number | | `unknown_author` | 3 | "Unknown", "Anonymous", empty | @@ -201,6 +204,14 @@ an author field is wrong while "Oxford, Michael" is a person. | `underscore_title` | A trailing format name comes off, an underscore before a subtitle becomes a colon, the rest become spaces | | `allcaps_title` | Title-cased, keeping small words small, hyphenated parts cased on both sides, and accented first letters capitalised rather than skipped | | `missing_isbn` | Filled from the filename, if a checksum-valid ISBN is in it | +| `mojibake_title`, `mojibake_author` | Read again as the UTF-8 it was, when every character makes the trip back | +| `junk_title` | "Microsoft Word - " and the like come off the front | +| `filename_title` | A document extension comes off the end | +| `placeholder_suffix` | The "- Unknown" comes off the end | + +The last three are made only when what is left is still a title: "Microsoft +Word - Document2" and "0195152972.pdf" stay as they are, flagged, because a +shorter placeholder is not a repair. Everything else is named and left alone, because the fix needs a lookup and a wrong guess in a catalogue is harder to find than a missing value. diff --git a/crates/bibclean/src/fix.rs b/crates/bibclean/src/fix.rs index a1a201d..de8d4f6 100644 --- a/crates/bibclean/src/fix.rs +++ b/crates/bibclean/src/fix.rs @@ -24,6 +24,23 @@ static SPACE_RUN: LazyLock = /// A run of letters, by Python's definition of a letter. static LETTERS: LazyLock = LazyLock::new(|| Regex::new(r"\p{L}+").expect("a valid pattern")); +/// The name of the program a document was made in, put in front of the title +/// by the program and carried into the catalogue by whatever read it. +static PRODUCER_PREFIX: LazyLock = LazyLock::new(|| { + Regex::new(&format!( + r"(?i)^{SPACE}*microsoft{SPACE}+(?:office{SPACE}+)?(?:word|powerpoint|excel|publisher){SPACE}*[-–—:]{SPACE}*" + )) + .expect("a valid pattern") +}); + +/// A document's file extension on the end of its title. +static DOCUMENT_EXTENSION: LazyLock = LazyLock::new(|| { + Regex::new(&format!( + r"(?i)\.(?:pdf|epub|mobi|azw3?|txt|wpd|docx?|odt|rtf|tex|qxd|indd|pm\d|djvu){SPACE}*$" + )) + .expect("a valid pattern") +}); + /// Words that stay lowercase inside a title. const SMALL_WORDS: &[&str] = &[ "a", "an", "and", "as", "at", "but", "by", "for", "from", "in", "into", "nor", "of", "on", @@ -112,6 +129,45 @@ pub fn clean_underscores(title: &str) -> String { .to_string() } +/// A title without the name of the program that made the file. +/// +/// "Microsoft Word - The Virgin.doc" is "The Virgin.doc"; the extension is a +/// separate fault with its own repair. `None` when there is no such prefix, +/// or when what is left would be no title at all ("Microsoft Word - +/// Document2" is a placeholder either way, and a shorter placeholder is not a +/// repair). +pub fn strip_producer(title: &str) -> Option { + let found = PRODUCER_PREFIX.find(title)?; + worth_keeping(title, &title[found.end()..]) +} + +/// A title without the file extension a filename left on it. +/// +/// `None` when there is none, or when what is left is not a title: a bare +/// number such as an ISBN used as the filename stays as it is, so the fault +/// stays visible. +pub fn strip_extension(title: &str) -> Option { + let found = DOCUMENT_EXTENSION.find(title)?; + worth_keeping(title, &title[..found.start()]) +} + +/// A title without the placeholder author a "Title - Author" filename left on +/// its end: "The Birth of Purgatory - Unknown" is "The Birth of Purgatory". +pub fn strip_placeholder_suffix(title: &str) -> Option { + let found = crate::reasons::PLACEHOLDER_SUFFIX.find(title)?; + worth_keeping(title, &title[..found.start()]) +} + +/// The stripped title, if it is a different title and still a title. +fn worth_keeping(original: &str, stripped: &str) -> Option { + let stripped = stripped + .trim_matches(|c: char| textkit::is_space(c) || c == '-' || c == ':' || c == ',') + .to_string(); + let has_letters = stripped.chars().any(char::is_alphabetic); + (has_letters && stripped != original && !crate::reasons::is_placeholder_title(&stripped)) + .then_some(stripped) +} + /// Capitalise the first letter and lowercase the rest. fn capitalise(word: &str) -> String { let lowered = word.to_lowercase(); diff --git a/crates/bibclean/src/lib.rs b/crates/bibclean/src/lib.rs index 0592425..49ad3e3 100644 --- a/crates/bibclean/src/lib.rs +++ b/crates/bibclean/src/lib.rs @@ -135,6 +135,50 @@ pub fn clean(book: &Book) -> Cleaned { book.isbn.as_deref(), ); + // Mojibake before anything that reads the text: every other repair + // matches on characters, and these are the wrong characters. + for (field, why) in [("title", "mojibake_title"), ("author", "mojibake_author")] { + let slot = if field == "title" { + &mut cleaned.title + } else { + &mut cleaned.author + }; + if let Some(value) = slot.clone() + && let Some(fixed) = textkit::mojibake::repair(&value) + { + changes.push(Change { + field: field.into(), + from: value, + to: fixed.clone(), + why: why.into(), + }); + *slot = Some(fixed); + } + } + + // The wrappers a file puts around a title, outermost first: the program's + // name in front, then the extension, which a filename writes after the + // placeholder author ("Title - Unknown.pdf"), then that author. + type Strip = fn(&str) -> Option; + let wrappers: [(Strip, &str); 3] = [ + (fix::strip_producer, "junk_title"), + (fix::strip_extension, "filename_title"), + (fix::strip_placeholder_suffix, "placeholder_suffix"), + ]; + for (strip, why) in wrappers { + if let Some(title) = cleaned.title.clone() + && let Some(fixed) = strip(&title) + { + changes.push(Change { + field: "title".into(), + from: title, + to: fixed.clone(), + why: why.into(), + }); + cleaned.title = Some(fixed); + } + } + // Underscores first: a title mangled by a filename may also be shouting, // and title-casing it before the underscores come out would case the // format suffix as though it were a word. @@ -247,6 +291,90 @@ mod tests { assert_eq!(cleaned.severity, 0); } + fn whys(cleaned: &Cleaned) -> Vec<&str> { + cleaned + .changes + .iter() + .map(|change| change.why.as_str()) + .collect() + } + + #[test] + fn a_word_processor_title_loses_its_wrappers() { + let cleaned = clean(&book( + "Microsoft Word - The Yoga of Hesychasm.doc", + "William Stoddart", + )); + assert_eq!(cleaned.book.title.as_deref(), Some("The Yoga of Hesychasm")); + assert_eq!(whys(&cleaned), ["junk_title", "filename_title"]); + } + + #[test] + fn a_placeholder_author_on_the_end_of_a_title_comes_off() { + let cleaned = clean(&book("The Birth of Purgatory - Unknown", "Unknown")); + assert_eq!( + cleaned.book.title.as_deref(), + Some("The Birth of Purgatory") + ); + assert_eq!(whys(&cleaned), ["placeholder_suffix"]); + // The author is still unknown, and still said to be. + assert!( + cleaned + .reasons + .iter() + .any(|reason| reason == "unknown_author") + ); + + let cleaned = clean(&book("Illuminati 666 - Unknown.pdf", "Unknown")); + assert_eq!(cleaned.book.title.as_deref(), Some("Illuminati 666")); + assert_eq!(whys(&cleaned), ["filename_title", "placeholder_suffix"]); + } + + #[test] + fn a_misread_title_and_author_are_read_again() { + let cleaned = clean(&book("L'impérialisme américain", "Henri Hausér")); + assert_eq!( + cleaned.book.title.as_deref(), + Some("L'impérialisme américain") + ); + assert_eq!(cleaned.book.author.as_deref(), Some("Henri Hausér")); + assert_eq!(whys(&cleaned), ["mojibake_title", "mojibake_author"]); + assert!( + cleaned + .reasons + .iter() + .any(|reason| reason == "mojibake_title") + ); + } + + #[test] + fn a_wrapper_around_nothing_is_left_for_a_person() { + // What is inside the wrappers is no title either, so taking them off + // would only hide the fault. + for title in [ + "Microsoft Word - Document2", + "0195152972.pdf", + "Untitled - Unknown", + ] { + let cleaned = clean(&book(title, "Someone")); + assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}"); + } + } + + #[test] + fn titles_that_only_look_wrapped_are_left_alone() { + for title in [ + "Word and Object", + "Gödel, Escher, Bach - An Eternal Golden Braid", + "The Pdf Primer", + "Cafe Society", + "A Title Left Trailing -", + ] { + let cleaned = clean(&book(title, "Someone")); + assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}"); + } + } + #[test] fn a_shouting_title_is_cased_and_the_change_is_recorded() { let cleaned = clean(&book("THE HUMAN CONDITION", "Arendt, Hannah")); diff --git a/crates/bibclean/src/reasons.rs b/crates/bibclean/src/reasons.rs index e9b82ab..7fd08d8 100644 --- a/crates/bibclean/src/reasons.rs +++ b/crates/bibclean/src/reasons.rs @@ -44,7 +44,7 @@ static PATH_TITLE: LazyLock = /// placeholder. static PLACEHOLDER_TITLE: LazyLock = LazyLock::new(|| { pattern( - r"(?i)^\W*(?:some[\s_-]*title|no[\s_-]*title|untitled|unnamed|title|document|documento|test|sample|default|placeholder|tbd|todo|draft|temp|new[\s_-]*document|book\d*|file\d*|scan\d*|doc\d*|n/?a|null|none|x{3,}|unknown)\W*$", + r"(?i)^\W*(?:some[\s_-]*title|no[\s_-]*title|untitled|unnamed|title|document\d*|documento|test|sample|default|placeholder|tbd|todo|draft|temp|new[\s_-]*document|book\d*|file\d*|scan\d*|doc\d*|n/?a|null|none|x{3,}|unknown)\W*$", ) }); @@ -57,6 +57,14 @@ static PLACEHOLDER_AUTHOR: LazyLock = LazyLock::new(|| { /// An author field that opens with a bare three or four digit number is a /// publication year or a series index in the wrong column, never a person. /// Anchored, so a real name containing a number is untouched. +/// A placeholder author left on the end of a title, the way a "Title - Author" +/// filename writes a book whose author nobody knew. +pub(crate) static PLACEHOLDER_SUFFIX: LazyLock = LazyLock::new(|| { + pattern(&format!( + r"(?i){SPACE}+[-–—]{SPACE}+(?:unknown(?:{SPACE}+author)?|anonymous|n/?a){SPACE}*$" + )) +}); + static NUMERIC_AUTHOR: LazyLock = LazyLock::new(|| pattern(&format!(r"^{SPACE}*\d{{3,4}}{SPACE}*(?:$|[{SPACE}.\-–—])"))); @@ -148,9 +156,12 @@ const WEIGHTS: &[(&str, u32)] = &[ ("junk_title", 3), ("lowercase_title", 2), ("missing_apostrophe", 2), + ("mojibake_author", 3), + ("mojibake_title", 3), ("numeric_author", 4), ("path_title", 4), ("placeholder_author", 4), + ("placeholder_suffix", 2), ("placeholder_title", 4), ("possible_swap", 2), ("publisher_as_author", 3), @@ -199,6 +210,15 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) - { reasons.push("numeric_author"); } + if textkit::mojibake::is_mojibake(title) { + reasons.push("mojibake_title"); + } + if textkit::mojibake::is_mojibake(author) { + reasons.push("mojibake_author"); + } + if PLACEHOLDER_SUFFIX.is_match(title) { + reasons.push("placeholder_suffix"); + } if title.contains('_') { reasons.push("underscore_title"); } @@ -260,6 +280,11 @@ pub fn worth_fixing(reasons: &[String]) -> bool { reasons.iter().any(|reason| reason != "missing_isbn") } +/// Whether a title is a placeholder rather than a work's name. +pub(crate) fn is_placeholder_title(title: &str) -> bool { + PLACEHOLDER_TITLE.is_match(title.trim_matches(textkit::is_space)) +} + /// Whether the title field is a placeholder and the author field is holding /// the real title. /// diff --git a/crates/textkit/README.md b/crates/textkit/README.md index 49dcb6d..5dfa964 100644 --- a/crates/textkit/README.md +++ b/crates/textkit/README.md @@ -115,6 +115,24 @@ fires on one side and not the other: The boundary forms are lookarounds, so a pattern using them needs an engine that has them. +## Mojibake + +UTF-8 text that something decoded as Windows-1252 on the way, put back: + +```rust +assert_eq!( + textkit::mojibake::repair("L'impérialisme américain").as_deref(), + Some("L'impérialisme américain"), +); +assert_eq!(textkit::mojibake::repair("café"), None); +``` + +The repair turns each character back into the byte it was decoded from and +reads the bytes as UTF-8. Real text almost never survives that trip — a +genuine "café" becomes a lone `0xe9`, which is not UTF-8 — so a string that +does was misread, and the answer is certain rather than guessed. Text misread +twice is unwound twice; text that is only partly repairable is left alone. + ## See also - [`corpus-core`](../corpus-core/README.md) — the records these help produce. diff --git a/crates/textkit/src/lib.rs b/crates/textkit/src/lib.rs index acd2ce5..b2c63f1 100644 --- a/crates/textkit/src/lib.rs +++ b/crates/textkit/src/lib.rs @@ -10,6 +10,7 @@ //! chunk ends and a chunk boundary that moves is a chunk that no longer //! matches what is already in an index. +pub mod mojibake; pub mod number; pub mod pattern; pub mod segment; diff --git a/crates/textkit/src/mojibake.rs b/crates/textkit/src/mojibake.rs new file mode 100644 index 0000000..e4f25d2 --- /dev/null +++ b/crates/textkit/src/mojibake.rs @@ -0,0 +1,119 @@ +//! UTF-8 text that was read as Windows-1252 somewhere along the way. +//! +//! "américain" stored as UTF-8 and decoded one byte at a time comes out as +//! "américain". The repair is the reverse trip: turn each character back into +//! the Windows-1252 byte it was decoded from and read those bytes as UTF-8. +//! It is certain rather than guessed, because ordinary text almost never +//! survives that trip: a real "café" becomes the lone byte `0xe9`, which is not +//! UTF-8, and is left alone. + +/// The text as it was before it was misread, or `None` if it was not misread. +/// +/// Text misread twice is unwound twice. Anything that cannot make the trip +/// cleanly, every character back to a byte and every byte into valid UTF-8, +/// is returned as `None` rather than half-repaired. +pub fn repair(text: &str) -> Option { + let mut current = once(text)?; + // Twice-misread text is common enough; three times is not, and the bound + // keeps a pathological input from looping. + for _ in 0..2 { + match once(¤t) { + Some(again) => current = again, + None => break, + } + } + Some(current) +} + +/// Whether the text reads as UTF-8 misread as Windows-1252. +pub fn is_mojibake(text: &str) -> bool { + once(text).is_some() +} + +fn once(text: &str) -> Option { + if text.is_ascii() { + return None; + } + let bytes = text.chars().map(byte_of).collect::>>()?; + let repaired = String::from_utf8(bytes).ok()?; + (repaired != text).then_some(repaired) +} + +/// The Windows-1252 byte a character decodes from, if there is one. +/// +/// The five positions Windows-1252 leaves undefined are taken as themselves, +/// the way browsers and most decoders leave them. +fn byte_of(c: char) -> Option { + let code = u32::from(c); + if code < 0x80 || (0xa0..=0xff).contains(&code) { + return u8::try_from(code).ok(); + } + HIGH_CONTROLS + .iter() + .position(|&high| high == c) + .and_then(|at| u8::try_from(0x80 + at).ok()) +} + +/// What Windows-1252 decodes the bytes 0x80 to 0x9f as. +const HIGH_CONTROLS: [char; 32] = [ + '\u{20ac}', '\u{81}', '\u{201a}', '\u{192}', '\u{201e}', '\u{2026}', '\u{2020}', '\u{2021}', + '\u{2c6}', '\u{2030}', '\u{160}', '\u{2039}', '\u{152}', '\u{8d}', '\u{17d}', '\u{8f}', + '\u{90}', '\u{2018}', '\u{2019}', '\u{201c}', '\u{201d}', '\u{2022}', '\u{2013}', '\u{2014}', + '\u{2dc}', '\u{2122}', '\u{161}', '\u{203a}', '\u{153}', '\u{9d}', '\u{17e}', '\u{178}', +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accented_latin_comes_back() { + assert_eq!( + repair("L'impérialisme américain").as_deref(), + Some("L'impérialisme américain") + ); + assert_eq!( + repair("Onvriers du temps passé [XVe-XVIe siècles]").as_deref(), + Some("Onvriers du temps passé [XVe-XVIe siècles]") + ); + } + + #[test] + fn punctuation_from_the_high_controls_comes_back() { + // U+2019 is E2 80 99, and 0x80 and 0x99 are among the bytes + // Windows-1252 decodes to something other than themselves. + assert_eq!(repair("Don’t Look").as_deref(), Some("Don\u{2019}t Look")); + assert_eq!(repair("Über Kant").as_deref(), Some("Über Kant")); + } + + #[test] + fn misread_twice_is_unwound_twice() { + assert_eq!(repair("café").as_deref(), Some("café")); + } + + #[test] + fn real_text_is_left_alone() { + for text in [ + "café", + "Été", + "Ægypt", + "Ångström", + "naïve résumé", + "Œuvres complètes", + "plain ascii", + "Москва", + "東京", + "", + ] { + assert_eq!(repair(text), None, "{text}"); + assert!(!is_mojibake(text), "{text}"); + } + } + + #[test] + fn half_repairable_text_is_left_alone() { + // The Cyrillic cannot be a Windows-1252 character, so the misread + // half cannot be undone without guessing about the rest. + assert_eq!(repair("américain Москва"), None); + } +}