Merge pull request 'bibclean: decode HTML character references' (#20) from bibclean-html-entities into main

This commit is contained in:
funkpower committed 2026-11-24 08:56:48 -05:00
commit 3360de29ae
4 files changed
+78

No files matched your search

+2
View File
@@ -177,6 +177,7 @@ bibclean books.ndjson | jq -c 'select(.slug_proposal.tier | IN("placeholder-auth
|---|---|---| |---|---|---|
| `placeholder_title` | 4 | The whole title is "Untitled", "Document", "N/A" | | `placeholder_title` | 4 | The whole title is "Untitled", "Document", "N/A" |
| `placeholder_author` | 4 | The same, in the author field | | `placeholder_author` | 4 | The same, in the author field |
| `html_entity` | 2 | An HTML character reference in the title or author: "Master & Apprentice" |
| `mojibake_title` | 3 | UTF-8 read as Windows-1252: "américain" | | `mojibake_title` | 3 | UTF-8 read as Windows-1252: "américain" |
| `mojibake_author` | 3 | The same, in the author field | | `mojibake_author` | 3 | The same, in the author field |
| `placeholder_suffix` | 2 | A placeholder author left on the end of the title: "… - Unknown" | | `placeholder_suffix` | 2 | A placeholder author left on the end of the title: "… - Unknown" |
@@ -214,6 +215,7 @@ 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 | | `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 | | `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 | | `missing_isbn` | Filled from the filename, if a checksum-valid ISBN is in it |
| `html_entity` | Decoded: the named references a catalogue meets, and every numeric one |
| `mojibake_title`, `mojibake_author` | Read again as the UTF-8 it was, when every character makes the trip back | | `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 | | `junk_title` | "Microsoft Word - " and the like come off the front |
| `filename_title` | A document extension comes off the end | | `filename_title` | A document extension comes off the end |
+39
View File
@@ -220,6 +220,45 @@ pub fn strip_release_tags(title: &str) -> Option<String> {
worth_keeping(title, &title[..found.start()]) worth_keeping(title, &title[..found.start()])
} }
/// HTML character references a web page left in a field: "Master &amp;
/// Apprentice". The named ones a catalogue meets, and every numeric one.
pub fn decode_entities(text: &str) -> Option<String> {
static ENTITY: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|([a-zA-Z]{2,8}));")
.expect("a valid pattern")
});
if !ENTITY.is_match(text) {
return None;
}
let decoded = ENTITY.replace_all(text, |caps: &regex::Captures| {
let found = if let Some(n) = caps.get(1) {
n.as_str().parse::<u32>().ok().and_then(char::from_u32)
} else if let Some(h) = caps.get(2) {
u32::from_str_radix(h.as_str(), 16)
.ok()
.and_then(char::from_u32)
} else {
match &caps[3] {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some(' '),
"ndash" => Some('–'),
"mdash" => Some('—'),
"rsquo" => Some('’'),
"lsquo" => Some('‘'),
"rdquo" => Some('”'),
"ldquo" => Some('“'),
_ => None,
}
};
found.map_or_else(|| caps[0].to_string(), |c| c.to_string())
});
(decoded != text).then(|| decoded.into_owned())
}
/// The stripped title, if it is a different title and still a title. /// The stripped title, if it is a different title and still a title.
fn worth_keeping(original: &str, stripped: &str) -> Option<String> { fn worth_keeping(original: &str, stripped: &str) -> Option<String> {
let stripped = stripped let stripped = stripped
+32
View File
@@ -136,6 +136,26 @@ pub fn clean(book: &Book) -> Cleaned {
book.isbn.as_deref(), book.isbn.as_deref(),
); );
// Character references first: "&amp;" is a word to every rule after.
for field in ["title", "author"] {
let slot = if field == "title" {
&mut cleaned.title
} else {
&mut cleaned.author
};
if let Some(value) = slot.clone()
&& let Some(fixed) = fix::decode_entities(&value)
{
changes.push(Change {
field: field.into(),
from: value,
to: fixed.clone(),
why: "html_entity".into(),
});
*slot = Some(fixed);
}
}
// Mojibake before anything that reads the text: every other repair // Mojibake before anything that reads the text: every other repair
// matches on characters, and these are the wrong characters. // matches on characters, and these are the wrong characters.
for (field, why) in [("title", "mojibake_title"), ("author", "mojibake_author")] { for (field, why) in [("title", "mojibake_title"), ("author", "mojibake_author")] {
@@ -546,6 +566,18 @@ mod tests {
} }
} }
#[test]
fn a_character_reference_is_decoded() {
let cleaned = clean(&book("Master &amp; Apprentice", "Claudia Gray"));
assert_eq!(cleaned.book.title.as_deref(), Some("Master & Apprentice"));
assert_eq!(whys(&cleaned), ["html_entity"]);
let cleaned = clean(&book("Don&#39;t Look &#x2014; Now", "Someone"));
assert_eq!(cleaned.book.title.as_deref(), Some("Don't Look — Now"));
// An ampersand that is not a reference stays.
let cleaned = clean(&book("Faith & Reason; & More", "Someone"));
assert!(!whys(&cleaned).contains(&"html_entity"));
}
#[test] #[test]
fn a_shouting_title_is_cased_and_the_change_is_recorded() { fn a_shouting_title_is_cased_and_the_change_is_recorded() {
let cleaned = clean(&book("THE HUMAN CONDITION", "Arendt, Hannah")); let cleaned = clean(&book("THE HUMAN CONDITION", "Arendt, Hannah"));
+5
View File
@@ -160,6 +160,7 @@ const WEIGHTS: &[(&str, u32)] = &[
("author_role_suffix", 2), ("author_role_suffix", 2),
("edited_volume", 1), ("edited_volume", 1),
("filename_title", 3), ("filename_title", 3),
("html_entity", 2),
("junk_title", 3), ("junk_title", 3),
("lowercase_title", 2), ("lowercase_title", 2),
("missing_apostrophe", 2), ("missing_apostrophe", 2),
@@ -230,6 +231,10 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) -
{ {
reasons.push("numeric_author"); reasons.push("numeric_author");
} }
if crate::fix::decode_entities(title).is_some() || crate::fix::decode_entities(author).is_some()
{
reasons.push("html_entity");
}
if textkit::mojibake::is_mojibake(title) { if textkit::mojibake::is_mojibake(title) {
reasons.push("mojibake_title"); reasons.push("mojibake_title");
} }