Merge pull request 'bibclean: name_in_title, and catalogue headings as bylines' (#16) from bibclean-name-in-title into main

This commit is contained in:
funkpower committed 2026-11-24 08:40:37 -05:00
commit a77df8515e
6 files changed
+670 -4

No files matched your search

+7
View File
@@ -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
@@ -179,12 +180,16 @@ bibclean books.ndjson | jq -c 'select(.slug_proposal.tier | IN("placeholder-auth
| `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" |
| `url_title` | 4 | A web address saved as the title |
| `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 |
| `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 |
| `author_role_suffix` | 2 | A catalogue heading's dates, role or fuller form in the author field: "Lossky, Vladimir, 1903-1958", "Vico, Giambattista (Author)" |
| `author_list_commas` | 1 | Several authors joined with commas or semicolons rather than "&" |
| `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 +216,8 @@ 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 |
| `author_role_suffix`, `author_list_commas` | The heading put as a byline: dates, roles and fuller forms off, each name given names first, the names joined with "&". A field that is only "Surname, Given" is left alone, since some catalogues keep that order on purpose; `bibclean::heading::as_byline` turns it round for a caller that wants bylines |
| `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
+74 -4
View File
@@ -21,7 +21,7 @@ fn pattern(source: &str) -> Regex {
/// person. Without them the looser heuristics propose the imprint.
static NOT_A_PERSON: LazyLock<Boundaried> = 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,13 +90,64 @@ static TITLE_BY: LazyLock<Boundaried> = 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<Regex> = LazyLock::new(|| {
let name = r"[A-Z][\p{L}.'’]*(?:\s+[A-Z][\p{L}.'’]*){1,4}";
pattern(&format!(
r"^(?:\([^)]{{2,80}}\){SPACE}*)?(?P<names>{name}(?:{SPACE}*(?:,|\band\b|&){SPACE}*{name})*)(?:{SPACE}*\((?:Eds?|eds?)\.?{SPACE}*\))?{SPACE}*-{SPACE}*(?P<rest>\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>, 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<String> = 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<Regex> = LazyLock::new(|| pattern(r"^([A-Z][a-z]+[A-Z][a-z]+)[-\s]"));
static CAMEL_PARTS: LazyLock<Regex> = LazyLock::new(|| pattern(r"[A-Z][a-z]+"));
/// Roman numerals that are a suffix on a name rather than shouting.
const ROMAN_SUFFIXES: &[&str] = &["II", "III", "IV", "V", "VI"];
/// Characters trimmed from the ends of a candidate.
const EDGES: &[char] = &[' ', '.', ',', ';', ':', '—', '-', '\t', '\n'];
@@ -249,6 +300,16 @@ pub fn from_title(title: &str) -> Vec<Suggestion> {
});
}
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])
{
@@ -346,6 +407,13 @@ pub fn normalise(raw: &str) -> Option<String> {
}
/// Fix shouting and bare initials within one name.
/// "RR", "JC", "JRR": initials run together, which casing as a word would
/// turn into "Rr". Two capitals, or three with no vowel among them.
fn looks_like_initials(core: &str) -> bool {
let n = core.chars().count();
n == 2 || n == 3 && !core.chars().any(|c| "AEIOUY".contains(c))
}
fn normalise_tokens(segment: &str) -> String {
segment
.split_whitespace()
@@ -356,7 +424,9 @@ fn normalise_tokens(segment: &str) -> String {
&& core.chars().all(|c| !c.is_lowercase())
&& core.chars().any(char::is_uppercase)
&& core.chars().count() > 1
&& !ROMAN_SUFFIXES.contains(&core);
// A regnal or generational number: "Leo XIII", "Henry VIII".
&& !core.chars().all(|c| "IVXLC".contains(c))
&& !looks_like_initials(core);
if shouting {
let mut fixed = capitalise(core);
if token.ends_with('.') {
+26
View File
@@ -158,6 +158,32 @@ pub fn strip_placeholder_suffix(title: &str) -> Option<String> {
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<Regex> = 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<String> {
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<String> {
let stripped = stripped
+385
View File
@@ -0,0 +1,385 @@
//! An author field written as a library catalogue writes its headings, put
//! the way a title page would print the names.
//!
//! A catalogue files a person under the surname, adds dates of birth and
//! death to tell namesakes apart, and notes the person's role: "Lossky,
//! Vladimir, 1903-1958", "Vico, Giambattista (Author)". All of that is
//! right for a card and wrong for a byline, and it survives every export
//! that copies the heading into an author field.
use std::sync::LazyLock;
use regex::Regex;
use textkit::pattern::SPACE;
use crate::reasons::looks_like_person;
fn pattern(source: &str) -> Regex {
Regex::new(source).expect("a valid pattern")
}
/// A role in brackets, or after a comma at the end: "(Author)", ", editor".
static ROLE: LazyLock<Regex> = LazyLock::new(|| {
pattern(&format!(
r"(?i){SPACE}*\({SPACE}*(?:author|editor|edt|eds?\.?|translator|trans\.?|compiler|illustrator){SPACE}*\)|,?{SPACE}+(?:author|editor|translator)\.?{SPACE}*$|{SPACE}*&{SPACE}*(?:editor|translator)s?{SPACE}*$"
))
});
/// Dates a catalogue adds to a heading: ", 1903-1958", ", 1973-",
/// ", b. 1950", ", d. 1622", ", fl. 1200".
static DATES: LazyLock<Regex> = LazyLock::new(|| {
pattern(&format!(
r"(?i),?{SPACE}*(?:(?:b|d|fl|ca?)\.{SPACE}*)?\b(?:1\d{{3}}|20\d{{2}})\b(?:{SPACE}*[-–]{SPACE}*(?:(?:1\d{{3}}|20\d{{2}})\b)?)?\.?"
))
});
/// An initial run into the surname: "J.Dostal", "P.COPENHAVER".
static GLUED_INITIAL: LazyLock<Regex> =
LazyLock::new(|| pattern(r"\b(\p{Lu}\.)(\p{Lu}[\p{L}'-]{2,})"));
/// The fuller form of a name a catalogue adds after initials:
/// "Smith, Robert O. (Robert Owen)". Only after an initial, so a name given
/// in brackets for another reason, "Archimandrite Tikhon (Shevkunov)", stays.
static FULLER_FORM: LazyLock<Regex> = LazyLock::new(|| {
pattern(&format!(
r"(\b\p{{Lu}}\.){SPACE}*\([\p{{Lu}}][\p{{L}}.' ]+\)"
))
});
/// What follows the comma in "Kenyon, Jr." or "Copleston, S.J." is part of
/// the name, not given names to put in front of it.
const SUFFIXES: &[&str] = &[
"fils", "ii", "iii", "iv", "jr", "m.d", "md", "o.p", "o.s.b", "op", "osb", "pere", "phd",
"père", "s.j", "sj", "sr",
];
/// Words a person's name does not contain. A field holding them is a title
/// or a sentence that a comma happens to split.
const NOT_IN_A_NAME: &[&str] = &[
"a",
"an",
"and",
"are",
"be",
"chapter",
"collected",
"do",
"for",
"how",
"in",
"is",
"need",
"of",
"on",
"the",
"to",
"volume",
"we",
"what",
"why",
"with",
"works",
];
/// The names in a catalogue heading, printed as a title page prints them,
/// and what was wrong with the heading.
///
/// `None` when the field is already a byline, or when it cannot be read
/// with confidence: a field that is not names at all is not this function's
/// to rearrange.
///
/// A plain "Arendt, Hannah" comes back turned round, with only
/// `author_last_first` against it. Some catalogues keep authors in that
/// order on purpose, so [`crate::clean`] leaves such a field alone; a caller
/// whose author field is a byline can use this directly.
pub fn as_byline(author: &str) -> Option<(String, Vec<&'static str>)> {
let original = author.trim_matches(textkit::is_space);
if original.is_empty() || original.to_lowercase().contains("z-lib") {
return None;
}
let mut faults = Vec::new();
let mut text = GLUED_INITIAL.replace_all(original, "$1 $2").to_string();
// A role between two names was what separated them: "Brian Leiter
// (eds.) Michael Rosen (eds.)".
let without_roles = ROLE.replace_all(&text, ";").to_string();
let without_dates = DATES.replace_all(&without_roles, "").to_string();
let without_fuller = FULLER_FORM.replace_all(&without_dates, "$1").to_string();
if without_fuller.trim_end_matches([';', ' ']) != text.trim_end_matches([';', ' ']) {
faults.push("author_role_suffix");
}
text = without_fuller;
let text = text
.trim_matches(|c: char| textkit::is_space(c) || c == ',' || c == ';')
.to_string();
let segments: Vec<String> = text
.split([';', '&'])
.map(|segment| split_segment(segment.trim_matches(textkit::is_space)))
.collect::<Option<Vec<Vec<String>>>>()?
.into_iter()
.flatten()
.collect();
if segments.is_empty() {
return None;
}
let mut names: Vec<String> = Vec::new();
for segment in &segments {
let (name, inverted) = turn_round(segment)?;
if inverted && !faults.contains(&"author_last_first") {
faults.push("author_last_first");
}
// The same person twice: "Ehrlich; Holdren & Ehrlich & Holdren".
if !names.iter().any(|seen| seen.eq_ignore_ascii_case(&name)) {
names.push(name);
}
}
for name in &names {
let words: Vec<&str> = name.split_whitespace().collect();
if words.is_empty()
|| words.len() > 5
|| name.chars().any(|c| c.is_ascii_digit())
|| words
.iter()
.any(|word| NOT_IN_A_NAME.contains(&word.trim_matches('.').to_lowercase().as_str()))
|| !name.chars().next().is_some_and(char::is_uppercase)
|| !looks_like_person(name)
{
return None;
}
}
for name in &names {
crate::author::clean(name)?;
}
let byline = crate::author::normalise(&names.join(" & "))?;
if byline == original {
return None;
}
// A bracket left in the middle of a byline is a qualifier the rules did
// not place: "Andrew (Physician) Baldwin".
if byline.contains('(') {
return None;
}
// A word still in capitals after normalising was not a name the rules
// understood: "GARY'S MAC".
if byline
.split_whitespace()
.any(|word| word.chars().filter(|c| c.is_uppercase()).count() >= 4 && !is_roman(word))
{
return None;
}
// Only the separator changed: "Patrick Laude, Barry McDonald".
if faults.is_empty() {
faults.push("author_list_commas");
}
Some((byline, faults))
}
/// One segment between semicolons or ampersands, as the names in it.
///
/// "Laude, Patrick" is one name turned round; "Patrick Laude, Barry
/// McDonald" is two in order; "Kohut, Heinz, Ornstein, Paul H." is two
/// turned round and run together. `None` when it is none of these.
fn split_segment(segment: &str) -> Option<Vec<String>> {
let parts: Vec<&str> = segment
.split(',')
.map(|part| part.trim_matches(textkit::is_space))
.filter(|part| !part.is_empty())
.collect();
// "John F., M.D. Greden": a suffix opening a part means the commas are
// not separating names at all.
if parts
.iter()
.skip(1)
.any(|part| part.split_whitespace().next().is_some_and(is_suffix) && !is_suffix(part))
{
return None;
}
match parts.len() {
0 => Some(Vec::new()),
1 => Some(vec![parts[0].to_string()]),
2 if is_suffix(parts[1]) => Some(vec![format!("{}, {}", parts[0], parts[1])]),
2 if is_suffix(parts[0]) => None,
2 if words(parts[0]) >= 2 && words(parts[1]) >= 2 && !ends_in_initial(parts[1]) => {
// Two names in order, unless the second is someone's given
// names: "Martin Luther King, Martin" does not happen, but
// "van Gogh, Vincent Willem" does, so a lowercase particle
// opening the first part keeps it a turned-round name.
if parts[0].starts_with(char::is_lowercase) {
Some(vec![format!("{}, {}", parts[0], parts[1])])
} else {
Some(parts.iter().map(|part| (*part).to_string()).collect())
}
}
2 => Some(vec![format!("{}, {}", parts[0], parts[1])]),
n if parts
.iter()
.all(|part| words(part) >= 2 && !ends_in_initial(part)) =>
{
let _ = n;
Some(parts.iter().map(|part| (*part).to_string()).collect())
}
n if n % 2 == 0 && parts.iter().step_by(2).all(|surname| words(surname) <= 2) => Some(
parts
.chunks(2)
.map(|pair| format!("{}, {}", pair[0], pair[1]))
.collect(),
),
_ => None,
}
}
/// A name with its given names put first, and whether it had to be turned.
fn turn_round(name: &str) -> Option<(String, bool)> {
let Some((surname, given)) = name.split_once(',') else {
return Some((name.trim_matches(textkit::is_space).to_string(), false));
};
let surname = surname.trim_matches(textkit::is_space);
let given = given.trim_matches(|c: char| textkit::is_space(c) || c == ',');
if is_suffix(given) {
return Some((format!("{surname}, {given}"), false));
}
// "Heinz." from "Kohut, Heinz.": the full stop closed the heading, not
// an initial, and has no place in the middle of a byline.
let given = match given.split_whitespace().last() {
Some(last)
if last.ends_with('.')
&& last.trim_end_matches('.').chars().count() > 1
&& !last.trim_end_matches('.').contains('.') =>
{
given.trim_end_matches('.')
}
_ => given,
};
if surname.is_empty()
|| given.is_empty()
|| words(surname) > 3
|| words(given) > 4
|| surname.eq_ignore_ascii_case(given.trim_end_matches('.'))
// "Ian Fleming, Ian": the given name already in front.
|| surname
.split_whitespace()
.next()
.is_some_and(|first| first.eq_ignore_ascii_case(given.trim_end_matches('.')))
{
return None;
}
Some((format!("{given} {surname}"), true))
}
fn is_roman(word: &str) -> bool {
!word.is_empty() && word.chars().all(|c| "IVXLC".contains(c))
}
fn words(text: &str) -> usize {
text.split_whitespace().count()
}
fn ends_in_initial(text: &str) -> bool {
text.split_whitespace()
.last()
.is_some_and(|last| last.trim_end_matches('.').chars().count() == 1)
}
fn is_suffix(text: &str) -> bool {
// "Md/phd": degrees run together.
text.split('/').all(|part| {
SUFFIXES.contains(
&part
.trim_matches(|c: char| textkit::is_space(c) || c == '.')
.to_lowercase()
.as_str(),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn byline(author: &str) -> Option<String> {
as_byline(author).map(|(name, _)| name)
}
#[test]
fn a_heading_is_turned_round() {
for (heading, want) in [
("Tolkien, J. R. R.", "J. R. R. Tolkien"),
("Borella, Jean", "Jean Borella"),
("Aurelius, Marcus", "Marcus Aurelius"),
("Raya, Joseph M", "Joseph M. Raya"),
("Lossky, Vladimir, 1903-1958", "Vladimir Lossky"),
("Hamilton, Kevin, 1973- author", "Kevin Hamilton"),
("Vico, Giambattista(Author)", "Giambattista Vico"),
("Smith, Robert O. (Robert Owen), 1974-", "Robert O. Smith"),
("Swinburne, Richard.", "Richard Swinburne"),
(
"Kohut, Heinz.,Ornstein, Paul H.",
"Heinz Kohut & Paul H. Ornstein",
),
(
"Goodin, Robert E. & Pettit, Philip",
"Robert E. Goodin & Philip Pettit",
),
("Mills, Robert;", "Robert Mills"),
("Martin, George RR", "George RR Martin"),
("Hauser, Henri, 1866-1946", "Henri Hauser"),
(
"Sheen, Fulton J. (Fulton John), 1895-1979",
"Fulton J. Sheen",
),
] {
assert_eq!(byline(heading).as_deref(), Some(want), "{heading}");
}
}
#[test]
fn a_list_in_order_is_joined() {
for (heading, want) in [
(
"Patrick Laude, Barry McDonald",
"Patrick Laude & Barry McDonald",
),
(
"Eleonore Stump (Editor), Norman Kretzmann (Editor)",
"Eleonore Stump & Norman Kretzmann",
),
(
"Brian Leiter (eds.) Michael Rosen (eds.)",
"Brian Leiter & Michael Rosen",
),
("KENNETH HAYNES (edt)", "Kenneth Haynes"),
] {
assert_eq!(byline(heading).as_deref(), Some(want), "{heading}");
}
}
#[test]
fn what_is_already_a_byline_or_not_a_name_is_left_alone() {
for author in [
"Hannah Arendt",
"Ralph E. Kenyon, Jr.",
"Frederick Copleston, S.J.",
"Chapter 1, Do We Need Philosophy",
"The Club of Rome, 2008",
"Volume 4 in the Collected Works of Georges Florovsky. (Florovsky, Georges) (z-library.sk, 1lib.sk, z-lib.sk)",
"Jr., Robert P. Granacher",
"Scientific American, Inc.",
"Alexandre Dumas, Pere",
"Onasander , Onasander",
"John F., M.D. Greden",
"Archimandrite Tikhon (Shevkunov)",
"JC Beall",
"Experience & Judgment 001-396",
"GARY'S MAC",
"Pope Leo XIII",
"Baldwin, Andrew (Physician), author",
"Gibbs Smith, Publisher",
"Ian Fleming, Ian",
"",
] {
assert_eq!(byline(author), None, "{author}");
}
}
}
+121
View File
@@ -15,6 +15,7 @@ pub mod abstracts;
pub mod author;
mod entities4;
pub mod fix;
pub mod heading;
pub mod isbn;
pub mod matching;
pub mod reasons;
@@ -179,11 +180,51 @@ 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);
}
// A catalogue heading in the author field, put as a byline: the names
// are the same, only their order and the card's dates and roles change.
if reasons.iter().any(|reason| {
matches!(
reason.as_str(),
"author_last_first" | "author_role_suffix" | "author_list_commas"
)
}) && let Some(author) = cleaned.author.clone()
&& let Some((byline, faults)) = heading::as_byline(&author)
{
changes.push(Change {
field: "author".into(),
from: author,
to: byline.clone(),
why: faults[0].into(),
});
cleaned.author = Some(byline);
}
// 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.
// Not in an address or a path, where the underscores are the name and
// taking them out leaves something that is neither title nor address.
if let Some(title) = cleaned.title.clone()
&& reasons.iter().any(|reason| reason == "underscore_title")
&& !reasons
.iter()
.any(|reason| reason == "url_title" || reason == "path_title")
{
let fixed = fix::clean_underscores(&title);
if fixed != title {
@@ -381,6 +422,86 @@ 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 an_address_is_named_and_left_alone() {
for title in [
"http://www.voxfux.com/features/stranger_than_fiction.htm",
"file://D:\\Books\\white_paper",
"www.example.org/some_page",
] {
let cleaned = clean(&book(title, "Someone"));
assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}");
assert!(
cleaned.reasons.iter().any(|reason| reason == "url_title"),
"{title}"
);
}
}
#[test]
fn a_shouting_title_is_cased_and_the_change_is_recorded() {
let cleaned = clean(&book("THE HUMAN CONDITION", "Arendt, Hannah"));
+57
View File
@@ -34,6 +34,10 @@ static JUNK_TITLE: LazyLock<Boundaried> = LazyLock::new(|| {
/// A path sitting in the title field. Distinct from a filename, which is a
/// bare name ending in an extension.
/// A web address saved as the title: "http://www.voxfux.com/features/…".
static URL_TITLE: LazyLock<Regex> =
LazyLock::new(|| pattern(r"(?i)^\W*(?:https?://|file://|www\.)\S"));
static PATH_TITLE: LazyLock<Regex> =
LazyLock::new(|| pattern(r"(^[A-Za-z]:[\\/])|(\\\\[^\\]+\\)|(^/(?:home|users|mnt|tmp|var)/)"));
@@ -152,6 +156,7 @@ const WEIGHTS: &[(&str, u32)] = &[
("allcaps_title", 2),
("author_is_title", 4),
("author_last_first", 1),
("author_list_commas", 1),
("author_role_suffix", 2),
("edited_volume", 1),
("filename_title", 3),
@@ -160,6 +165,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),
@@ -171,6 +177,7 @@ const WEIGHTS: &[(&str, u32)] = &[
("title_in_author", 3),
("underscore_title", 1),
("unknown_author", 3),
("url_title", 4),
];
/// Everything wrong with a record, named.
@@ -197,6 +204,9 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) -
if PATH_TITLE.is_match(title) {
reasons.push("path_title");
}
if URL_TITLE.is_match(title) {
reasons.push("url_title");
}
if FILENAME_TITLE.is_match(title) {
reasons.push("filename_title");
}
@@ -250,9 +260,26 @@ 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");
}
// A heading turned round and nothing else is a choice some catalogues
// make; dates, roles and comma-joined lists are what a byline never has.
if !author_is_missing(title, author)
&& let Some((_, faults)) = crate::heading::as_byline(author)
&& faults != ["author_last_first"]
{
reasons.extend(faults);
}
if author_is_title(title, author) {
reasons.push("author_is_title");
}
@@ -336,6 +363,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<String> = names.iter().map(|name| fold(name)).collect();
let mut theirs: Vec<String> = 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()