diff --git a/crates/bibclean/README.md b/crates/bibclean/README.md index c95ccc3..43867ea 100644 --- a/crates/bibclean/README.md +++ b/crates/bibclean/README.md @@ -99,8 +99,9 @@ through this and back into whatever it came from. ## Recovering a missing author A book says who wrote it on its own copyright page. Hand in the opening pages -as `front_matter` and a record whose author is missing gets a name proposed, -with the evidence and how far it is worth trusting: +as `front_matter` and a record whose author is missing, a placeholder, a login, +or the title copied into the field gets a name proposed, with the evidence and +how far it is worth trusting: ``` $ bibclean authors.ndjson @@ -183,6 +184,8 @@ bibclean books.ndjson | jq -c 'select(.slug_proposal.tier | IN("placeholder-auth | `unknown_author` | 3 | "Unknown", "Anonymous", empty | | `filename_title` | 3 | A bare filename, extension and all | | `junk_title` | 3 | The name of the tool that made the file, not the work | +| `author_is_title` | 4 | The title copied into the author field | +| `account_author` | 3 | The login of whoever made the file: "mymarasigan", "HP_Administrator" | | `publisher_as_author` | 3 | An imprint in the author field | | `title_in_author` | 3 | The title is a placeholder and the real title is in the author field | | `allcaps_title` | 2 | Shouting | diff --git a/crates/bibclean/src/author.rs b/crates/bibclean/src/author.rs index ce83f13..5ae85ef 100644 --- a/crates/bibclean/src/author.rs +++ b/crates/bibclean/src/author.rs @@ -21,7 +21,7 @@ fn pattern(source: &str) -> Regex { /// person. Without them the looser heuristics propose the imprint. static NOT_A_PERSON: LazyLock = LazyLock::new(|| { Boundaried::new(&format!( - r"(?i){WORD_START}(press|edition|introduction|university|volume|reprint|copyright|published|printed|rights|reserved|library|congress|isbn|inc|ltd|company|regents|trustees|foundation|institute|society|association|board|council|committee|department|ministry|editors?|trust|publishing|publishers|books|publications|sons|llc|gmbh|verlag|all|limited){WORD_END}" + r"(?i){WORD_START}(press|edition|introduction|university|volume|reprint|copyright|published|printed|rights|reserved|library|congress|isbn|inc|ltd|company|regents|trustees|foundation|institute|society|association|board|council|committee|department|ministry|editors?|trust|publishing|publishers|books|publications|sons|llc|gmbh|verlag|all|limited|house|media|editions|éditions|center|centre|seminary|classics|wiley|gruyter|brill|siebeck|seuil|gallimard|payot|routledge|springer|elsevier|macmillan|penguin|blackwell|norton|knopf|doubleday|vintage|bantam|harpercollins|nv|bv){WORD_END}" )) .expect("a valid pattern") }); @@ -55,12 +55,21 @@ static ISBN: LazyLock = LazyLock::new(|| { }); /// The strongest thing a book says about who wrote it. +/// +/// The word "Copyright" is often left off: "© 2004 by Stanley Hauerwas". static COPYRIGHT: LazyLock = LazyLock::new(|| { pattern(&format!( - r"(?i)Copyright{SPACE}*(?:©|\(c\))?{SPACE}*\d{{4}}{SPACE}+by{SPACE}+(.{{2,90}})" + r"(?i)(?:Copyright{SPACE}*(?:©|\(c\))?|©|\(c\)){SPACE}*\d{{4}}{SPACE}+by{SPACE}+(.{{2,90}})" )) }); +/// What a notice can be for besides the work itself. +static SUBSIDIARY: LazyLock = LazyLock::new(|| { + pattern( + r"(?i)\b(?:translat\w*|introduction|notes|foreword|afterword|preface|editorial|selection|compilation|illustrations?|cover|map|maps|abridg\w*|chronology)\b", + ) +}); + /// The cataloguing block a national library prints on the copyright page. static CATALOGUING: LazyLock = LazyLock::new(|| { pattern(&format!( @@ -177,7 +186,15 @@ pub fn from_front_matter(text: &str) -> Vec { let mut out = Vec::new(); // Strongest: the book saying who holds its copyright. - if let Some(found) = COPYRIGHT.captures(text) + // A notice for a translation, an introduction or the notes names whoever + // wrote those, not the book: "Translation copyright © 2014 by Oliver + // Ready" is in front of Dostoevsky. + let for_the_work = COPYRIGHT.captures_iter(text).find(|found| { + let at = found.get(0).map_or(0, |whole| whole.start()); + let line_start = text[..at].rfind('\n').map_or(0, |n| n + 1); + !SUBSIDIARY.is_match(&text[line_start..at]) + }); + if let Some(found) = for_the_work && let Some(name) = clean(&name_prefix(&found[1])) && name.split_whitespace().count() >= 2 { @@ -271,6 +288,16 @@ pub fn name_prefix(text: &str) -> String { break; } } + // A particle belongs to the surname after it. Left on the end, it means + // the run stopped at a firm's name: "Walter de" from "Walter de Gruyter". + while tokens.last().is_some_and(|last| { + [ + "de", "van", "von", "der", "den", "du", "da", "di", "la", "le", + ] + .contains(last) + }) { + tokens.pop(); + } tokens.join(" ") } @@ -398,6 +425,38 @@ mod tests { assert_eq!(found[0].confidence, 0.9); } + #[test] + fn a_notice_without_the_word_copyright_names_the_author() { + let text = "\u{a9} 2004 by Stanley Hauerwas and Samuel Wells\n350 Main Street"; + let found = from_front_matter(text); + assert_eq!(found[0].method, "front_matter_copyright"); + assert!( + found[0].author.starts_with("Stanley Hauerwas"), + "{}", + found[0].author + ); + } + + #[test] + fn a_publisher_holding_the_copyright_is_not_an_author() { + for text in [ + "Copyright \u{a9} 1990 by John Wiley & Sons", + "\u{a9} 2004 by Random House, Inc.", + "Copyright \u{a9} 2011 by Walter de Gruyter", + "Copyright \u{a9} 2014 by Arktos Media Ltd.", + ] { + assert!(from_front_matter(text).is_empty(), "{text}"); + } + } + + #[test] + fn a_translators_notice_is_passed_over() { + let text = "Translation copyright \u{a9} 2014 by Oliver Ready\nIntroduction copyright \u{a9} 2014 by Someone Else"; + assert!(from_front_matter(text).is_empty()); + let text = "Translation copyright \u{a9} 2014 by Oliver Ready\nCopyright \u{a9} 1999 by James H. Billington"; + assert_eq!(from_front_matter(text)[0].author, "James H. Billington"); + } + #[test] fn a_cataloguing_block_names_the_author_surname_first() { let text = "Library of Congress Cataloging-in-Publication Data\n\ diff --git a/crates/bibclean/src/lib.rs b/crates/bibclean/src/lib.rs index 49ad3e3..61ed0b3 100644 --- a/crates/bibclean/src/lib.rs +++ b/crates/bibclean/src/lib.rs @@ -237,11 +237,17 @@ pub fn clean(book: &Book) -> Cleaned { _ => None, }; - // Only for a record that has no author to overwrite. A name recovered - // from the text is evidence, not an improvement on one somebody entered. + // Only for a record that has no real author to overwrite: none, a + // placeholder, the title copied into the field, or a login. A name recovered from + // the text is evidence, not an improvement on one somebody entered. let author_proposal = reasons .iter() - .any(|reason| reason == "unknown_author" || reason == "placeholder_author") + .any(|reason| { + reason == "unknown_author" + || reason == "placeholder_author" + || reason == "author_is_title" + || reason == "account_author" + }) .then(|| { author::best( book.title.as_deref().unwrap_or(""), diff --git a/crates/bibclean/src/reasons.rs b/crates/bibclean/src/reasons.rs index 7fd08d8..0758e15 100644 --- a/crates/bibclean/src/reasons.rs +++ b/crates/bibclean/src/reasons.rs @@ -148,7 +148,9 @@ const PERSON_SUFFIXES: &[&str] = &["ed", "eds", "ii", "iii", "iv", "jr", "md", " /// What each fault is worth when the worst records are wanted first. const WEIGHTS: &[(&str, u32)] = &[ + ("account_author", 3), ("allcaps_title", 2), + ("author_is_title", 4), ("author_last_first", 1), ("author_role_suffix", 2), ("edited_volume", 1), @@ -248,6 +250,12 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) - { reasons.push("possible_swap"); } + if is_account_name(author) { + reasons.push("account_author"); + } + if author_is_title(title, author) { + reasons.push("author_is_title"); + } if title_in_author(Some(title), Some(author)) { reasons.push("title_in_author"); } @@ -280,6 +288,65 @@ pub fn worth_fixing(reasons: &[String]) -> bool { reasons.iter().any(|reason| reason != "missing_isbn") } +/// Whether the author field holds the title, copied there by whatever made +/// the record: "Cultural Imperialism" by "Cultural Imperialism". +/// +/// The author has to be the whole title, or the whole of the title before its +/// subtitle or a bracketed aside, compared without case or punctuation. A +/// person whose name merely opens the title ("Plato" for "Plato and the +/// Republic") is not caught, because the name is not all of the title, and +/// nor is a person named before the subtitle: "Isaac Newton: Philosophical +/// Writings" is by Isaac Newton. +pub fn author_is_title(title: &str, author: &str) -> bool { + let bare_author = author.split('(').next().unwrap_or(""); + let folded = fold(bare_author); + if folded.is_empty() { + return false; + } + if folded == fold(title.split('(').next().unwrap_or("")) { + return true; + } + folded == fold(title.split([':', '(']).next().unwrap_or("")) && !looks_like_person(bare_author) +} + +/// Whether the author field is the login of whoever made the file: +/// "mymarasigan", "HP_Administrator", "SaravanakumarCS", "user42". +/// +/// One word, and a shape no published name has: all lowercase, an underscore, +/// digits among letters, or capitals run on after lowercase. A capitalised +/// single name ("Plato", "Voltaire") is a name and is left alone. +pub fn is_account_name(author: &str) -> bool { + let author = author.trim_matches(textkit::is_space); + if author.chars().count() < 4 || author.chars().any(textkit::is_space) { + return false; + } + if !author.chars().any(char::is_alphabetic) { + return false; + } + let lowercase = author + .chars() + .all(|c| c.is_lowercase() || c.is_ascii_digit() || c == '.'); + let underscored = author.contains('_'); + let digits = author.chars().any(|c| c.is_ascii_digit()); + let run_on_capitals = author + .chars() + .collect::>() + .windows(3) + .any(|w| w[0].is_lowercase() && w[1].is_uppercase() && w[2].is_uppercase()); + lowercase || underscored || digits || run_on_capitals +} + +/// Lowercase words, punctuation dropped. +fn fold(text: &str) -> String { + text.chars() + .map(|c| if c.is_alphanumeric() { c } else { ' ' }) + .collect::() + .to_lowercase() + .split_whitespace() + .collect::>() + .join(" ") +} + /// 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)) @@ -384,6 +451,95 @@ fn is_publisher(author: &str) -> bool { .is_ok() } +#[cfg(test)] +mod account_name_tests { + use super::*; + + #[test] + fn a_login_is_named() { + for author in [ + "mymarasigan", + "HP_Administrator", + "SaravanakumarCS", + "user42", + "pubassist", + "vitzliputzli", + ] { + assert!(is_account_name(author), "{author}"); + } + } + + #[test] + fn a_name_is_not() { + for author in [ + "Plato", + "Voltaire", + "Hannah Arendt", + "bell hooks", + "McLuhan", + "DeLillo", + "Joe", + "", + "Anonymous", + ] { + assert!(!is_account_name(author), "{author}"); + } + } +} + +#[cfg(test)] +mod author_is_title_tests { + use super::*; + + #[test] + fn a_title_in_the_author_field_is_named() { + for (title, author) in [ + ("Cultural Imperialism", "Cultural Imperialism"), + ("Consciousness Reconsidered", "Consciousness Reconsidered"), + ("The Brain", "The Brain (1979)"), + ( + "A Slim Book About Narrow Content", + "A Slim Book About Narrow Content (Contem", + ), + ( + "Neural Correlates of Consciousness: Empirical and Conceptual Questions", + "Neural Correlates Of Consciousness", + ), + ("Reed", "Reed"), + ] { + assert!(author_is_title(title, author), "{title} / {author}"); + assert!( + problems(Some(title), Some(author), None).contains(&"author_is_title".to_string()) + ); + } + } + + #[test] + fn a_person_who_shares_words_with_the_title_is_not() { + for (title, author) in [ + ("Plato and the Republic", "Plato"), + ("Kant: A Very Short Introduction", "Roger Scruton"), + ("Hegel and Aristotle", "Alfredo Ferrarin"), + ("Aristotle", "Jonathan Barnes"), + ("Isaac Newton: Philosophical Writings", "Isaac Newton"), + ( + "Margaret Cavendish: Observations Upon Experimental Philosophy", + "Margaret Cavendish", + ), + // Two capitalised words read as a name, so before a subtitle they + // are given the benefit of the doubt even when they are a title. + ( + "Cultural Imperialism: A Critical Introduction", + "Cultural Imperialism", + ), + ("", "Someone"), + ("Untitled", ""), + ] { + assert!(!author_is_title(title, author), "{title} / {author}"); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/colophon/src/title.rs b/crates/colophon/src/title.rs index 8f6d1c7..f5c69f8 100644 --- a/crates/colophon/src/title.rs +++ b/crates/colophon/src/title.rs @@ -58,6 +58,39 @@ static CATALOGUE_ENTRY: LazyLock = LazyLock::new(|| { static DEDICATION: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)^\s*(to|for|in memory of)\s+\S.*,\s*$").expect("a valid pattern") }); +/// Front matter that is about the book rather than the book: the cover's +/// credit, a dedication set without its comma, the list of the author's other +/// books, the page of praise, a library's stamp, a scanner's watermark. +static ABOUT_THE_BOOK: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r"(?i)^\s*(?:", + r"(?:cover|jacket)\s+(?:design|art|artwork|illustration|photograph|photo|image|painting)s?\b", + r"|(?:interior|book|text)\s+design(?:ed)?\s+by\b", + r"|(?:to|for)\s+(?:my|our)\s+\S+(?:\s+\S+){0,3}\s*[,.]?\s*$", + r"|also\s+by\b|by\s+the\s+same\s+author\b|other\s+(?:books|titles|works)\s+by\b", + r"|praise\s+for\b", + r"|(?:brought\s+to\s+you|digiti[sz]ed|scanned)\s+by\b|brought\s+to\s+you\s*$", + r")", + )) + .expect("a valid pattern") +}); +/// "BOOK ONE", "Part II", "Book 3": the page opens a part of the book, and +/// the name set under it is the part's, not the book's. +static PART_OPENER: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)^\W*(?:book|part)\s+(?:one|two|three|four|five|six|seven|eight|nine|ten|first|second|third|[ivxlc]+|\d{1,2})\W*$") + .expect("a valid pattern") +}); +/// A library's ownership stamp: "Trent University Library". +static LIBRARY_STAMP: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)\b(?:university|college|seminary)\b.*\blibrar(?:y|ies)\s*$") + .expect("a valid pattern") +}); +/// The slug a layout program prints at the foot of a proof page: the file's +/// name, or the date and time it was output. +static LAYOUT_SLUG: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)\.(?:qxd|qxp|indd|pmd)\b|\b\d{1,2}/\d{1,2}/\d{2,4}\s+\d{1,2}:\d{2}\s*[ap]m\b") + .expect("a valid pattern") +}); static COPYRIGHT_NOTICE: LazyLock = LazyLock::new(|| { // The year need not follow the symbol directly: "(c) Alfredo Ferrarin // 2004" puts the holder between them, and was read as a title. @@ -184,7 +217,9 @@ fn strip_folio(norm: &str) -> &str { /// edition's own list of volumes. fn is_furniture(line: &str) -> bool { let t = line.trim(); - if t.starts_with('[') || t.starts_with('\\') { + // A line that opens on the copyright sign is a credit or a notice even + // when it carries no year: "© Vladimir Pcholkin / FPG International". + if t.starts_with('[') || t.starts_with('\\') || t.starts_with('\u{a9}') { return true; } // A converter that left its markup in. Nothing printed on a title page is @@ -224,7 +259,18 @@ fn is_furniture(line: &str) -> bool { return true; } } - if DEDICATION.is_match(t) { + if DEDICATION.is_match(t) + || ABOUT_THE_BOOK.is_match(t) + || LIBRARY_STAMP.is_match(t) + || LAYOUT_SLUG.is_match(t) + { + return true; + } + // A trademark sign on the end marks a brand: "A Forthright Edition™", + // printed beside the title, never inside one. A converter that dropped + // the superscript leaves the letters run on: "EditionTM". + let run_on_mark = t.ends_with("TM") && t.chars().rev().nth(2).is_some_and(char::is_lowercase); + if t.ends_with('™') || run_on_mark { return true; } let lower = t.to_lowercase(); @@ -304,6 +350,14 @@ fn could_be_a_person(line: &str) -> bool { if tokens.len() > 4 { return false; } + // "A Bradford Book", "A Scientific American Book": the imprint's own + // line, set where a byline would be. + let lowered = line.to_lowercase(); + if (lowered.starts_with("a ") || lowered.starts_with("an ")) + && (lowered.ends_with(" book") || lowered.ends_with(" books")) + { + return false; + } !tokens.iter().any(|token| { let word = token.trim_end_matches('.').to_lowercase(); word.len() > 4 && NOT_A_NAME.iter().any(|end| word.ends_with(end)) @@ -370,6 +424,11 @@ pub fn read(lines: &[String]) -> Option { continue; } } + // Above everything else on the page, a part marker means the page + // opens a part of the book, and what follows is the part's name. + if block.is_empty() && PART_OPENER.is_match(line) { + return None; + } if is_structural(line) || is_furniture(line) || BARE_DATE.is_match(line) { if block.is_empty() { continue; @@ -467,6 +526,25 @@ mod furniture_tests { "Vol. 11. HENRY JAMES, JR.", "All rights reserved", "First published 1971", + "Cover design by David Ferris (www.davidferrisdesign.com).", + "Cover art", + "Jacket photograph © Getty Images", + "Book design by Jane Doe", + "To my family", + "For my parents", + "Also by Fyodor Dostoyevsky", + "By the same author", + "Other books by Anne Rice", + "Praise for *The Singularity Is Near", + "Hond_FM.qxd 7/12/04 12:48 PM Page iii", + "M956 LEVENTIS PRE M/UP.qxd 3/10/07 1:42 PM Page i", + "Trent University Library", + "The University of Chicago Libraries", + "brought to you", + "Digitized by Google", + "A Forthright EditionTM", + "A Forthright Edition\u{2122}", + "\u{a9} Vladimir Pcholkin / FPG International", ] { assert!( is_structural(line) || is_furniture(line), @@ -486,6 +564,15 @@ mod furniture_tests { "Contents of Consciousness", "August 1914", "Copyright and Its Discontents", + "Book Design", + "Cover Story", + "To Kill a Mockingbird", + "For Whom the Bell Tolls", + "In Praise of Folly", + "The Library of Babel", + "University Libraries in Transition", + "The Public Library", + "Atomic Habits", ] { assert!( !(is_structural(line) || is_furniture(line)), @@ -505,6 +592,52 @@ mod furniture_tests { } } +#[cfg(test)] +mod part_tests { + use super::*; + + fn lines(text: &[&str]) -> Vec { + text.iter().map(|line| (*line).to_string()).collect() + } + + #[test] + fn a_part_opener_is_not_the_title_page() { + assert!(read(&lines(&["BOOK ONE", "The Stitch Service"])).is_none()); + assert!(read(&lines(&["Part II", "The War Years"])).is_none()); + } + + #[test] + fn a_title_that_begins_with_book_is_still_a_title() { + let page = + read(&lines(&["The Book of Disquiet", "Fernando Pessoa"])).expect("a title page"); + assert_eq!(page.title.as_deref(), Some("The Book of Disquiet")); + let page = read(&lines(&["Book One of the Trilogy", "Someone Else"])); + assert!(page.is_some()); + let page = + read(&lines(&["The Great Ideas of Psychology", "Part I"])).expect("a title page"); + assert_eq!(page.title.as_deref(), Some("The Great Ideas of Psychology")); + } +} + +#[cfg(test)] +mod person_tests { + use super::*; + + #[test] + fn an_imprint_line_is_not_a_person() { + for line in ["A SCIENTIFIC Book", "A Bradford Book", "An Owl Book"] { + assert!(!could_be_a_person(line), "{line}"); + } + } + + #[test] + fn initials_are_still_a_person() { + for line in ["A. J. Ayer", "A.J. Ayer", "Anne Carson"] { + assert!(could_be_a_person(line), "{line}"); + } + } +} + #[cfg(test)] mod conversion_tests { use super::*;