diff --git a/crates/bibclean/README.md b/crates/bibclean/README.md index 43867ea..5f80254 100644 --- a/crates/bibclean/README.md +++ b/crates/bibclean/README.md @@ -116,6 +116,7 @@ Four signals, cheapest and most trustworthy first: | `front_matter_copyright` | 0.9 | "Copyright © 1966 by …" | | `front_matter_loc` | 0.8 | The cataloguing block's main entry, written surname first | | `title_by` | 0.7 | "… by Author Name" at the end of the title | +| `title_prefix` | 0.75 | Names in front of the title, filename fashion | | `title_camel` | 0.5 | A run-together name at the front of the title | An ISBN found on the same page rides along with the name, because the two are @@ -185,6 +186,7 @@ bibclean books.ndjson | jq -c 'select(.slug_proposal.tier | IN("placeholder-auth | `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 | +| `name_in_title` | 2 | The author's name in front of the title, filename fashion: "Wilfred R Bion-Cogitations-Karnac Books (1991)" | | `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 | @@ -211,6 +213,7 @@ an author field is wrong while "Oxford, Michael" is a person. | `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 | +| `name_in_title` | The names come off the front, and the publisher, year and series off the end; the names are proposed as the author. Made only when the record has no real author, or already has the same one | 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 diff --git a/crates/bibclean/src/author.rs b/crates/bibclean/src/author.rs index 5ae85ef..19a159d 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|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}" + 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|microsoft|adobe|acrobat){WORD_END}" )) .expect("a valid pattern") }); @@ -90,6 +90,59 @@ static TITLE_BY: LazyLock = LazyLock::new(|| { }); /// A title that opens with the author's name run together. +/// "Wilfred R Bion-Cogitations-Karnac Books (1991)": a filename that put the +/// author in front of the title with a hyphen, as shadow libraries name +/// their downloads. An optional series in brackets may come first, and the +/// names may be several, joined by commas or "and", marked "(Eds)". +static NAME_PREFIX: LazyLock = LazyLock::new(|| { + let name = r"[A-Z][\p{L}.'’]*(?:\s+[A-Z][\p{L}.'’]*){1,4}"; + pattern(&format!( + r"^(?:\([^)]{{2,80}}\){SPACE}*)?(?P{name}(?:{SPACE}*(?:,|\band\b|&){SPACE}*{name})*)(?:{SPACE}*\((?:Eds?|eds?)\.?{SPACE}*\))?{SPACE}*-{SPACE}*(?P\S.*)$" + )) +}); + +/// The names a title opens with, and the title after them. +/// +/// `None` unless every name reads as a person, so "Evidence-Based Technical +/// Analysis" and "Anglo-Saxon England" are left alone. +pub fn name_prefix_of_title(title: &str) -> Option<(Vec, String)> { + let found = NAME_PREFIX.captures(title.trim_matches(textkit::is_space))?; + // "Socio-technical", "Non-Reductive": a hyphen inside a word, not after a + // name. A title after a name starts with a capital; a number there is a + // series counting its volumes ("Known Space-038-The Soft Weapon"). + if !found["rest"].chars().next().is_some_and(char::is_uppercase) { + return None; + } + // "Can Physicalism Be Non-Reductive?", "Alfred Willener The Action-Image": + // the words that make a run of capitals a sentence rather than a name. + const NOT_IN_A_NAME: &[&str] = &[ + "a", "an", "are", "be", "can", "for", "how", "in", "is", "non", "of", "on", "the", "to", + "towards", "what", "why", "with", + ]; + if found["names"] + .split_whitespace() + .any(|word| NOT_IN_A_NAME.contains(&word.to_lowercase().as_str())) + { + return None; + } + let names: Vec = AUTHOR_SEPARATOR + .split(&found["names"].replace(" and ", " & ").replace(',', " &")) + .map(|name| name.trim_matches(textkit::is_space).to_string()) + .filter(|name| !name.is_empty()) + .collect(); + if names.is_empty() { + return None; + } + let mut people = Vec::new(); + for name in &names { + if NOT_A_PERSON.is_match(name).unwrap_or(true) { + return None; + } + people.push(normalise(name)?); + } + Some((people, found["rest"].to_string())) +} + static TITLE_CAMEL: LazyLock = LazyLock::new(|| pattern(r"^([A-Z][a-z]+[A-Z][a-z]+)[-\s]")); static CAMEL_PARTS: LazyLock = LazyLock::new(|| pattern(r"[A-Z][a-z]+")); @@ -249,6 +302,16 @@ pub fn from_title(title: &str) -> Vec { }); } + if let Some((names, _)) = name_prefix_of_title(title) { + out.push(Suggestion { + author: names.join(" & "), + method: "title_prefix".into(), + confidence: 0.75, + evidence: title.chars().take(120).collect(), + isbn: None, + }); + } + if let Some(found) = TITLE_CAMEL.captures(title) && let Some(split) = split_camel(&found[1]) { diff --git a/crates/bibclean/src/fix.rs b/crates/bibclean/src/fix.rs index de8d4f6..dfaba72 100644 --- a/crates/bibclean/src/fix.rs +++ b/crates/bibclean/src/fix.rs @@ -158,6 +158,32 @@ pub fn strip_placeholder_suffix(title: &str) -> Option { worth_keeping(title, &title[..found.start()]) } +/// What a shadow-library filename leaves after the title: "-Karnac Books +/// (1991)", the series in brackets, whole or cut off, a stub of a publisher. +static FILENAME_TAIL: LazyLock = LazyLock::new(|| { + Regex::new(&format!( + r"(?i)(?:{SPACE}*-{SPACE}*[^-]{{2,60}}\((?:1[5-9]|20)\d{{2}}\)|{SPACE}*\([^)]*|{SPACE}*\([^)]*\b(?:series|library|classics)\)|{SPACE}+-{SPACE}*\S{{0,3}}){SPACE}*$" + )) + .expect("a valid pattern") +}); + +/// A title without the author's name a filename put in front of it, and +/// without the publisher and year it put after: +/// "Wilfred R Bion-Cogitations-Karnac Books (1991)" is "Cogitations". +pub fn strip_name_prefix(title: &str) -> Option { + let (_, rest) = crate::author::name_prefix_of_title(title)?; + let mut rest = rest; + // A tail can hide another: "(Maresfield Library)-Karnac (1984)". + for _ in 0..3 { + let shorter = FILENAME_TAIL.replace(&rest, "").to_string(); + if shorter == rest || !shorter.chars().any(char::is_alphabetic) { + break; + } + rest = shorter; + } + worth_keeping(title, &rest) +} + /// The stripped title, if it is a different title and still a title. fn worth_keeping(original: &str, stripped: &str) -> Option { let stripped = stripped diff --git a/crates/bibclean/src/lib.rs b/crates/bibclean/src/lib.rs index 61ed0b3..ede48f1 100644 --- a/crates/bibclean/src/lib.rs +++ b/crates/bibclean/src/lib.rs @@ -179,6 +179,22 @@ pub fn clean(book: &Book) -> Cleaned { } } + // The author's name in front of the title, filename fashion. Taken off + // only when the record has no real author to show for it, or already has + // the same one: otherwise the prefix may be all that names the book. + if let Some(title) = cleaned.title.clone() + && reasons.iter().any(|reason| reason == "name_in_title") + && let Some(fixed) = fix::strip_name_prefix(&title) + { + changes.push(Change { + field: "title".into(), + from: title, + to: fixed.clone(), + why: "name_in_title".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. @@ -381,6 +397,70 @@ mod tests { } } + #[test] + fn a_filename_title_gives_up_its_author() { + for (title, want_title, want_author) in [ + ( + "Wilfred R Bion-Cogitations-Karnac Books (1991)", + "Cogitations", + "Wilfred R. Bion", + ), + ( + "(Harris Meltzer Trust Series) Donald Meltzer-The Psycho-Analytical Process -Karnac Books (2008)", + "The Psycho-Analytical Process", + "Donald Meltzer", + ), + ( + "Wilfred R Bion-Transformations (Maresfield Library)-Karnac (1984)", + "Transformations", + "Wilfred R. Bion", + ), + ( + "David Campbell, Tim Coldicott-Systemic Work With Organizations A New Model (Syst", + "Systemic Work With Organizations A New Model", + "David Campbell & Tim Coldicott", + ), + ( + "Judy Cooper - ASSESSMENT IN PSYCHOTHERAPY", + "Assessment in Psychotherapy", + "Judy Cooper", + ), + ] { + let cleaned = clean(&book(title, "Unknown")); + assert_eq!(cleaned.book.title.as_deref(), Some(want_title), "{title}"); + let proposal = cleaned.author_proposal.expect("an author"); + assert_eq!(proposal.author, want_author, "{title}"); + assert_eq!(proposal.method, "title_prefix"); + } + } + + #[test] + fn a_title_that_only_looks_prefixed_is_left_alone() { + for title in [ + "Evidence-Based Technical Analysis", + "Anglo-Saxon England", + "The Cambridge Companion to Plotinus", + "Jean-Paul Sartre", + "Can Physicalism Be Non-Reductive?", + "Towards Non-Being: The Logic and Metaphysics of Intentionality", + "Known Space-038-The Soft Weapon", + "Phiip G Herbst Socio-technical Design Strategies", + "Alfred Willener The Action-Image of Society", + ] { + let cleaned = clean(&book(title, "Unknown")); + assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}"); + } + // A real author keeps the prefix as the record has it. + let cleaned = clean(&book( + "Donald Meltzer-Sexual States of Mind", + "Someone Else", + )); + assert_eq!( + cleaned.book.title.as_deref(), + Some("Donald Meltzer-Sexual States of Mind") + ); + } + #[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 0758e15..82e3935 100644 --- a/crates/bibclean/src/reasons.rs +++ b/crates/bibclean/src/reasons.rs @@ -160,6 +160,7 @@ const WEIGHTS: &[(&str, u32)] = &[ ("missing_apostrophe", 2), ("mojibake_author", 3), ("mojibake_title", 3), + ("name_in_title", 2), ("numeric_author", 4), ("path_title", 4), ("placeholder_author", 4), @@ -250,6 +251,15 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) - { reasons.push("possible_swap"); } + // Named only where it can be acted on: the record has no real author to + // set against the prefix, or the prefix is the author it already has. + // "Known Space-038-The Soft Weapon" by Larry Niven is a series and a + // number, and is none of this fault's business. + if let Some((names, _)) = crate::author::name_prefix_of_title(title) + && (author_is_missing(title, author) || same_people(&names, author)) + { + reasons.push("name_in_title"); + } if is_account_name(author) { reasons.push("account_author"); } @@ -336,6 +346,36 @@ pub fn is_account_name(author: &str) -> bool { lowercase || underscored || digits || run_on_capitals } +/// Whether the author field has no real author in it. +pub(crate) fn author_is_missing(title: &str, author: &str) -> bool { + UNKNOWN_AUTHORS + .binary_search(&author.to_lowercase().as_str()) + .is_ok() + || PLACEHOLDER_AUTHOR.is_match(author) + || is_account_name(author) + || author_is_title(title, author) +} + +/// Whether an author field names exactly these people, ignoring case and +/// punctuation. +pub(crate) fn same_people(names: &[String], author: &str) -> bool { + let fold = |s: &str| -> String { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() + }; + let mut ours: Vec = names.iter().map(|name| fold(name)).collect(); + let mut theirs: Vec = author + .split('&') + .map(fold) + .filter(|s| !s.is_empty()) + .collect(); + ours.sort(); + theirs.sort(); + !ours.is_empty() && ours == theirs +} + /// Lowercase words, punctuation dropped. fn fold(text: &str) -> String { text.chars()