mirror of
https://git.pumpin.online/funkpower/catena.git
synced 2026-11-24 19:32:56 +00:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a05181907f | ||
|
|
798acb07db | ||
|
|
2dc90ea28d | ||
|
|
470e9a9e38 | ||
|
|
f50971a29c | ||
|
|
6b37dccbc0 | ||
|
|
9f202ba766 | ||
|
|
29d64ae8c2 | ||
|
|
eb27662f69 | ||
|
|
1c7005460a | ||
|
|
da7df1aaea | ||
|
|
12c42dc4dc | ||
|
|
d203dedb64 | ||
|
|
3fcacc4b44 | ||
|
|
1670753b2d | ||
|
|
43f60e7cfc | ||
|
|
bd933157c9 | ||
|
|
6f876e8052 | ||
|
|
3360de29ae | ||
|
|
f0cc4a854a | ||
|
|
a5f6872175 | ||
|
|
f8336b22b2 | ||
|
|
5acdb60e5c | ||
|
|
f46f4fbc95 | ||
|
|
a8f0800192 | ||
|
|
5aa6f4d1d2 | ||
|
|
a77df8515e | ||
|
|
14133c9be5 | ||
|
|
894a64add2 | ||
|
|
12e9fdfd31 | ||
|
|
34fa3cc04b | ||
|
|
4a2a4b6170 | ||
|
|
dad30ae7b0 | ||
|
|
b01c31483e | ||
|
|
c2990904a0 | ||
|
|
6f636f894e | ||
|
|
15b92d7457 | ||
|
|
2d885b5afc | ||
|
|
99f4f198af | ||
|
|
038b0c70ba | ||
|
|
6b5d9c20ee | ||
|
|
dd41a93c9b | ||
|
|
e9f9e75c1d | ||
|
|
65fd4adaad | ||
|
|
58573399e7 | ||
|
|
d06e13e2f3 | ||
|
|
8ecc4766ee | ||
|
|
3bd3ea11ae | ||
|
|
b7feefb704 | ||
|
|
f43b9d4900 | ||
|
|
6844f10e0e | ||
|
|
4aae5b6ac0 | ||
|
|
3fd48d4999 | ||
|
|
0e83c6ffc1 | ||
|
|
48478fe84e | ||
|
|
de23a7abad | ||
|
|
5f2a471f58 | ||
|
|
7aa1783a3e | ||
|
|
4d21cc5927 | ||
|
|
6510973850 | ||
|
|
897b2210b6 | ||
|
|
03c19c7293 | ||
|
|
ce8332d6d8 | ||
|
|
bd104834ed | ||
|
|
57ce9137e6 | ||
|
|
b4000b9b67 | ||
|
|
23969269e8 | ||
|
|
452102639a | ||
|
|
a105b1c9aa | ||
|
|
1abed4632d | ||
|
|
130324bbe0 | ||
|
|
19e5f3ddc3 | ||
|
|
b7d98e9d1a |
No files matched your search
Generated
+26
-26
@@ -101,7 +101,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "avplan"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -126,7 +126,7 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "bibclean"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -143,7 +143,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bibfetch"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -196,7 +196,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bookmeta"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -210,7 +210,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "booksniff"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -250,7 +250,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "catena"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"bibclean",
|
||||
"bibfetch",
|
||||
@@ -277,7 +277,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "catena-cli"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_mangen",
|
||||
@@ -312,7 +312,7 @@ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "chunkmd"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -334,7 +334,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "citefind"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"chunkmd",
|
||||
@@ -399,7 +399,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "colophon"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"bibclean",
|
||||
"catena-cli",
|
||||
@@ -448,7 +448,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "corpus-core"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
@@ -492,7 +492,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cuekit"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"corpus-core",
|
||||
"regex",
|
||||
@@ -504,7 +504,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cuenorm"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -514,7 +514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cuepack"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -525,7 +525,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cueseg"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -612,7 +612,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "emb"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -876,7 +876,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "idnorm"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"bibclean",
|
||||
"catena-cli",
|
||||
@@ -942,7 +942,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "langid"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1022,7 +1022,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mdscrub"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1034,7 +1034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mdsplit"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1113,7 +1113,7 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "pdfgutter"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1126,7 +1126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdftriage"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1370,7 +1370,7 @@ checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "rrf"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1517,7 +1517,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "seriesof"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -1634,7 +1634,7 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
||||
|
||||
[[package]]
|
||||
name = "textkit"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"tiktoken-rs",
|
||||
@@ -1724,7 +1724,7 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tocfind"
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
|
||||
+27
-27
@@ -3,39 +3,39 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.1"
|
||||
version = "0.6.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://git.pumpin.online/funkpower/catena"
|
||||
|
||||
[workspace.dependencies]
|
||||
catena-cli = { path = "crates/catena-cli", version = "0.3.1" }
|
||||
corpus-core = { path = "crates/corpus-core", version = "0.3.1" }
|
||||
cuekit = { path = "crates/cuekit", version = "0.3.1" }
|
||||
textkit = { path = "crates/textkit", version = "0.3.1" }
|
||||
chunkmd = { path = "crates/chunkmd", version = "0.3.1" }
|
||||
mdscrub = { path = "crates/mdscrub", version = "0.3.1" }
|
||||
mdsplit = { path = "crates/mdsplit", version = "0.3.1" }
|
||||
pdftriage = { path = "crates/pdftriage", version = "0.3.1" }
|
||||
cuenorm = { path = "crates/cuenorm", version = "0.3.1" }
|
||||
cueseg = { path = "crates/cueseg", version = "0.3.1" }
|
||||
rrf = { path = "crates/rrf", version = "0.3.1" }
|
||||
cuepack = { path = "crates/cuepack", version = "0.3.1" }
|
||||
bibclean = { path = "crates/bibclean", version = "0.3.1" }
|
||||
avplan = { path = "crates/avplan", version = "0.3.1" }
|
||||
pdfgutter = { path = "crates/pdfgutter", version = "0.3.1" }
|
||||
catena = { path = "crates/bindings", version = "0.3.1" }
|
||||
seriesof = { path = "crates/seriesof", version = "0.3.1" }
|
||||
idnorm = { path = "crates/idnorm", version = "0.3.1" }
|
||||
bibfetch = { path = "crates/bibfetch", version = "0.3.1" }
|
||||
bookmeta = { path = "crates/bookmeta", version = "0.3.1" }
|
||||
langid = { path = "crates/langid", version = "0.3.1" }
|
||||
tocfind = { path = "crates/tocfind", version = "0.3.1" }
|
||||
booksniff = { path = "crates/booksniff", version = "0.3.1" }
|
||||
citefind = { path = "crates/citefind", version = "0.3.1" }
|
||||
colophon = { path = "crates/colophon", version = "0.3.1" }
|
||||
emb = { path = "crates/emb", version = "0.3.1" }
|
||||
catena-cli = { path = "crates/catena-cli", version = "0.6.0" }
|
||||
corpus-core = { path = "crates/corpus-core", version = "0.6.0" }
|
||||
cuekit = { path = "crates/cuekit", version = "0.6.0" }
|
||||
textkit = { path = "crates/textkit", version = "0.6.0" }
|
||||
chunkmd = { path = "crates/chunkmd", version = "0.6.0" }
|
||||
mdscrub = { path = "crates/mdscrub", version = "0.6.0" }
|
||||
mdsplit = { path = "crates/mdsplit", version = "0.6.0" }
|
||||
pdftriage = { path = "crates/pdftriage", version = "0.6.0" }
|
||||
cuenorm = { path = "crates/cuenorm", version = "0.6.0" }
|
||||
cueseg = { path = "crates/cueseg", version = "0.6.0" }
|
||||
rrf = { path = "crates/rrf", version = "0.6.0" }
|
||||
cuepack = { path = "crates/cuepack", version = "0.6.0" }
|
||||
bibclean = { path = "crates/bibclean", version = "0.6.0" }
|
||||
avplan = { path = "crates/avplan", version = "0.6.0" }
|
||||
pdfgutter = { path = "crates/pdfgutter", version = "0.6.0" }
|
||||
catena = { path = "crates/bindings", version = "0.6.0" }
|
||||
seriesof = { path = "crates/seriesof", version = "0.6.0" }
|
||||
idnorm = { path = "crates/idnorm", version = "0.6.0" }
|
||||
bibfetch = { path = "crates/bibfetch", version = "0.6.0" }
|
||||
bookmeta = { path = "crates/bookmeta", version = "0.6.0" }
|
||||
langid = { path = "crates/langid", version = "0.6.0" }
|
||||
tocfind = { path = "crates/tocfind", version = "0.6.0" }
|
||||
booksniff = { path = "crates/booksniff", version = "0.6.0" }
|
||||
citefind = { path = "crates/citefind", version = "0.6.0" }
|
||||
colophon = { path = "crates/colophon", version = "0.6.0" }
|
||||
emb = { path = "crates/emb", version = "0.6.0" }
|
||||
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap_mangen = "0.3"
|
||||
|
||||
@@ -34,7 +34,7 @@ Each tool installs by name, so you can take one without taking the rest.
|
||||
| [`vocabmerge`](crates/bibclean/README.md#vocabmerge--the-other-command) | The near-duplicate headings in a catalogue's vocabulary |
|
||||
| [`seriesof`](crates/seriesof/README.md) | The series a book belongs to, and which volume this is |
|
||||
| [`idnorm`](crates/idnorm/README.md) | DOIs, ISSNs, ISBNs and arXiv ids, read and checked |
|
||||
| [`bibfetch`](crates/bibfetch/README.md) | What a register says about an identifier |
|
||||
| [`bibfetch`](crates/bibfetch/README.md) | What a register says about an identifier, and which books it has under a title |
|
||||
| [`citefind`](crates/citefind/README.md) | The references in a bibliography or a page of notes |
|
||||
| [`mdscrub`](crates/mdscrub/README.md) | Converted markdown in, clean markdown out |
|
||||
| [`mdsplit`](crates/mdsplit/README.md) | One markdown file into the works inside it |
|
||||
|
||||
@@ -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
|
||||
@@ -115,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
|
||||
@@ -175,18 +177,35 @@ 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 |
|
||||
| `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_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 "&" |
|
||||
| `title_punctuation` | 1 | A space before a colon, double spaces, a dangling separator or full stop, "Jesuits, The" |
|
||||
| `numbered_title` | 1 | A set's number in front of the title: "01 - The Three Musketeers" |
|
||||
| `release_tags` | 1 | A release group's tags after the title: "(v4 0) (lit)", "(Scan, OCR)" |
|
||||
| `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 |
|
||||
| `allcaps_title` | 2 | Shouting |
|
||||
| `allcaps_author` | 2 | The same, in the author field: "STEVEN BOX" |
|
||||
| `lowercase_title` | 2 | A filename stub: "heidegger areopagite" |
|
||||
| `missing_apostrophe` | 2 | "Lossky s Argument" |
|
||||
| `possible_swap` | 2 | Title and author look to be the wrong way round |
|
||||
| `underscore_title` | 1 | Underscores standing in for spaces and colons |
|
||||
| `invalid_isbn` | 3 | A stored ISBN whose check digit disagrees |
|
||||
| `placeholder_isbn` | 3 | A run of one digit standing in for an ISBN: "000-0-000-00000-0" |
|
||||
| `isbn_with_label` | 3 | Ten digits beginning `13978`: the label of an ISBN-13 read as part of the number, cut short and given a fresh check digit |
|
||||
| `missing_isbn` | 0 | Reported, but not a reason to do anything |
|
||||
|
||||
Each test is deliberately conservative. A real book called "The Document" or
|
||||
@@ -201,6 +220,19 @@ 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 |
|
||||
| `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 |
|
||||
| `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`, `allcaps_author` | 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 |
|
||||
| `title_punctuation` | Set as a title page sets it; a full stop after an initial or abbreviation stays |
|
||||
| `numbered_title`, `release_tags` | The number comes off the front, the tags off the end. A series named in front as well ("Known Space-038-…") is `seriesof`'s, which keeps the series |
|
||||
| `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
|
||||
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.
|
||||
@@ -341,6 +373,18 @@ count against a heading, and spaced initials count for one.
|
||||
A respelling is trusted further than an inversion: `strict_norm` at 0.95,
|
||||
`last_first` at 0.9, a publisher family at 0.8, a junk subject at 0.92.
|
||||
|
||||
Authors left standing after that are matched once more, as fuller forms of
|
||||
one another (`fuller_form`): "G. W. F. Hegel" and "Georg Wilhelm Friedrich
|
||||
Hegel", "Murray Rothbard" and "Murray N. Rothbard". The surname and the first
|
||||
given name must agree, written out or as an initial, and every other given
|
||||
name of the shorter heading must appear in the longer one in order. A heading
|
||||
that fits two longer ones which do not fit each other — "David Smith" beside
|
||||
"David Livingstone Smith" and "David Woodruff Smith" — could be either person,
|
||||
and the set is left alone. The heading kept is the one most works are under,
|
||||
so fifty books by "Bertrand Russell" do not move to "B. Russell". Two people
|
||||
can share a first name and a surname, so these are for a person to check:
|
||||
0.8 when the shorter heading is two or more initials, 0.6 when it is a name.
|
||||
|
||||
## Abstracts that arrived inside out
|
||||
|
||||
Some catalogues publish an abstract as an inverted index — each word mapped to
|
||||
|
||||
@@ -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){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")
|
||||
});
|
||||
@@ -55,12 +55,21 @@ static ISBN: LazyLock<Regex> = 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<Regex> = 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<Regex> = 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<Regex> = LazyLock::new(|| {
|
||||
pattern(&format!(
|
||||
@@ -81,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'];
|
||||
|
||||
@@ -177,7 +237,15 @@ pub fn from_front_matter(text: &str) -> Vec<Suggestion> {
|
||||
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
|
||||
{
|
||||
@@ -232,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])
|
||||
{
|
||||
@@ -271,6 +349,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(" ")
|
||||
}
|
||||
|
||||
@@ -319,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()
|
||||
@@ -329,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('.') {
|
||||
@@ -398,6 +495,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\
|
||||
|
||||
@@ -24,6 +24,23 @@ static SPACE_RUN: LazyLock<Regex> =
|
||||
/// A run of letters, by Python's definition of a letter.
|
||||
static LETTERS: LazyLock<Regex> = 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<Regex> = 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<Regex> = 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,181 @@ 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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
let found = crate::reasons::PLACEHOLDER_SUFFIX.find(title)?;
|
||||
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)
|
||||
}
|
||||
|
||||
/// "01 - The Three Musketeers": a number in front of the title, where a
|
||||
/// filename counted the volumes of a set without naming it.
|
||||
static LEADING_NUMBER: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"^{SPACE}*(\d{{1,3}}){SPACE}*[-–—.]{SPACE}+(\p{{Lu}}.*)$"
|
||||
))
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
|
||||
/// The tags a release group puts after a title: "(v4 0)", "(lit)", "(BD)".
|
||||
static RELEASE_TAGS: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"(?i)(?:{SPACE}*\((?:v{SPACE}?\d+(?:[ ._]\d+)*|lit|html?|rtf|txt|pdb|bd|retail|scan(?:,{SPACE}*ocr)?|no{SPACE}ocr|ocr)\))+{SPACE}*$"
|
||||
))
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
|
||||
/// The number a set put in front of the title, and the title without it.
|
||||
///
|
||||
/// Only a small number: "911 - Decent into Tyranny" is a date, not volume
|
||||
/// nine hundred and eleven, and a year in front ("2003 - …") is the year.
|
||||
pub fn strip_leading_number(title: &str) -> Option<(u32, String)> {
|
||||
let found = LEADING_NUMBER.captures(title)?;
|
||||
let number: u32 = found[1].parse().ok()?;
|
||||
if number > 200 {
|
||||
return None;
|
||||
}
|
||||
worth_keeping(title, &found[2]).map(|rest| (number, rest))
|
||||
}
|
||||
|
||||
/// A title without the tags a release group put after it.
|
||||
pub fn strip_release_tags(title: &str) -> Option<String> {
|
||||
let found = RELEASE_TAGS.find(title)?;
|
||||
worth_keeping(title, &title[..found.start()])
|
||||
}
|
||||
|
||||
/// HTML character references a web page left in a field: "Master &
|
||||
/// 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: ®ex::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())
|
||||
}
|
||||
|
||||
/// A title's punctuation set the way a title page sets it: no space before
|
||||
/// a colon ("Sex Wars : Sexual Dissent" is a catalogue's), one space between
|
||||
/// words, no dangling separator or full stop at the end, and an article put
|
||||
/// back in front ("Jesuits, The" is a filing form).
|
||||
pub fn tidy_punctuation(title: &str) -> Option<String> {
|
||||
static BEFORE_COLON: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(&format!(r"{SPACE}+:{SPACE}*")).expect("a valid pattern"));
|
||||
static INVERTED_ARTICLE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"^(?P<head>[^:,]+),{SPACE}*(?P<article>The|A|An)(?P<tail>{SPACE}*:.*)?$"
|
||||
))
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
let mut out = BEFORE_COLON.replace_all(title, ": ").into_owned();
|
||||
out = SPACE_RUN.replace_all(&out, " ").into_owned();
|
||||
let trimmed = out.trim_matches(textkit::is_space);
|
||||
// A full stop ends a title only when it ends an initial or an
|
||||
// abbreviation: "Crusade for Pan-Europe. Autobiography of a man." loses
|
||||
// it, "Martin Luther King Jr." keeps it.
|
||||
let last_word = trimmed.split_whitespace().last().unwrap_or("");
|
||||
let keep_stop =
|
||||
last_word.trim_end_matches('.').chars().count() <= 3 || trimmed.ends_with("...");
|
||||
let mut cleaned = trimmed
|
||||
.trim_end_matches([',', ';', ':', '-', '–', '—', ' '])
|
||||
.to_string();
|
||||
if cleaned.ends_with('.') && !keep_stop {
|
||||
cleaned.pop();
|
||||
}
|
||||
if let Some(found) = INVERTED_ARTICLE.captures(&cleaned) {
|
||||
let tail = found.name("tail").map_or("", |t| t.as_str()).trim_start();
|
||||
cleaned = format!("{} {}{}", &found["article"], found["head"].trim(), tail);
|
||||
}
|
||||
worth_keeping(title, &cleaned).filter(|fixed| fixed != title)
|
||||
}
|
||||
|
||||
/// 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
|
||||
.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();
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! 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;
|
||||
}
|
||||
// Shouting, put in the case a title page prints names in: "STEVEN BOX".
|
||||
if faults.is_empty()
|
||||
&& original.chars().any(char::is_alphabetic)
|
||||
&& !original.chars().any(char::is_lowercase)
|
||||
{
|
||||
faults.push("allcaps_author");
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
pub(crate) 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_name_in_capitals_is_named_as_shouting() {
|
||||
assert_eq!(
|
||||
as_byline("STEVEN BOX"),
|
||||
Some(("Steven Box".to_string(), vec!["allcaps_author"]))
|
||||
);
|
||||
assert_eq!(
|
||||
as_byline("Patrick Laude, Barry McDonald").map(|(_, faults)| faults),
|
||||
Some(vec!["author_list_commas"])
|
||||
);
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use textkit::pattern::SPACE;
|
||||
/// An ISBN announced as one, in running text or a catalogue field.
|
||||
static ANNOUNCED: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(&format!(
|
||||
r"(?i)ISBN[-{SPACE}:]*((?:97[89][{SPACE}-]?)?(?:[0-9][{SPACE}-]?){{9}}[0-9Xx])"
|
||||
r"(?i)ISBN(?:[-{SPACE}]?1[03]\b)?[-{SPACE}:]*((?:97[89][{SPACE}-]?)?(?:[0-9][{SPACE}-]?){{9}}[0-9Xx])"
|
||||
))
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
@@ -70,11 +70,39 @@ pub fn digits(text: &str) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An ISBN announced in a piece of text, if it is the right length.
|
||||
/// The first ISBN announced in a piece of text whose check digit agrees.
|
||||
///
|
||||
/// The form's own label is not part of the number: "ISBN-13 978-0-521-65706-8"
|
||||
/// is 9780521657068, never the ten digits 1397805216 that start it.
|
||||
pub fn from_text(text: &str) -> Option<String> {
|
||||
let found = ANNOUNCED.captures(text)?;
|
||||
let digits = digits(&found[1]);
|
||||
matches!(digits.len(), 10 | 13).then_some(digits)
|
||||
ANNOUNCED
|
||||
.captures_iter(text)
|
||||
.map(|found| digits(&found[1]))
|
||||
.find(|digits| matches!(digits.len(), 10 | 13) && valid(digits))
|
||||
}
|
||||
|
||||
/// What is wrong with a stored ISBN, if anything.
|
||||
///
|
||||
/// `invalid_isbn` when the check digit disagrees; `placeholder_isbn` for a
|
||||
/// run of one digit, which a publisher's template prints before the number
|
||||
/// is assigned; `isbn_with_label` for ten digits that begin `13978` or
|
||||
/// `13979`, the label of an ISBN-13 read as part of the number, cut short to
|
||||
/// ten and given a fresh check digit.
|
||||
pub fn fault(text: &str) -> Option<&'static str> {
|
||||
let digits = digits(text);
|
||||
if digits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if digits.chars().all(|c| c == digits.as_bytes()[0] as char) {
|
||||
return Some("placeholder_isbn");
|
||||
}
|
||||
if !valid(&digits) {
|
||||
return Some("invalid_isbn");
|
||||
}
|
||||
if digits.len() == 10 && (digits.starts_with("13978") || digits.starts_with("13979")) {
|
||||
return Some("isbn_with_label");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A checksum-valid ISBN embedded in a filename.
|
||||
@@ -123,6 +151,40 @@ mod tests {
|
||||
assert_eq!(from_text("no identifier here"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_an_isbn_13_is_not_part_of_it() {
|
||||
assert_eq!(
|
||||
from_text("ISBN-13 978-0-521-65706-8 paperback"),
|
||||
Some("9780521657068".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
from_text("ISBN 13: 9780521657068"),
|
||||
Some("9780521657068".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
from_text("ISBN-10: 0-521-52888-7 (pbk.)"),
|
||||
Some("0521528887".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_with_a_wrong_check_digit_gives_way_to_the_next() {
|
||||
assert_eq!(
|
||||
from_text("ISBN 0-19-823790-2 ISBN 0-19-823790-1"),
|
||||
Some("0198237901".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_isbn_that_cannot_be_right_is_named() {
|
||||
assert_eq!(fault("9780198237907"), None);
|
||||
assert_eq!(fault("0198237902"), Some("invalid_isbn"));
|
||||
assert_eq!(fault("0000000000000"), Some("placeholder_isbn"));
|
||||
assert_eq!(fault("000-0-000-00000-0"), Some("placeholder_isbn"));
|
||||
assert_eq!(fault("1397805218"), Some("isbn_with_label"));
|
||||
assert_eq!(fault(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filename_that_is_an_isbn_gives_it_up() {
|
||||
assert_eq!(
|
||||
|
||||
+386
-3
@@ -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;
|
||||
@@ -135,11 +136,132 @@ pub fn clean(book: &Book) -> Cleaned {
|
||||
book.isbn.as_deref(),
|
||||
);
|
||||
|
||||
// Character references first: "&" 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
|
||||
// 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<String>;
|
||||
fn strip_number(title: &str) -> Option<String> {
|
||||
fix::strip_leading_number(title).map(|(_, rest)| rest)
|
||||
}
|
||||
let wrappers: [(Strip, &str); 5] = [
|
||||
(fix::strip_producer, "junk_title"),
|
||||
(fix::strip_extension, "filename_title"),
|
||||
(fix::strip_placeholder_suffix, "placeholder_suffix"),
|
||||
(fix::strip_release_tags, "release_tags"),
|
||||
(strip_number, "numbered_title"),
|
||||
];
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
if let Some(title) = cleaned.title.clone()
|
||||
&& let Some(fixed) = fix::tidy_punctuation(&title)
|
||||
{
|
||||
changes.push(Change {
|
||||
field: "title".into(),
|
||||
from: title,
|
||||
to: fixed.clone(),
|
||||
why: "title_punctuation".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.
|
||||
// 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 {
|
||||
@@ -193,11 +315,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(""),
|
||||
@@ -247,6 +375,261 @@ 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",
|
||||
] {
|
||||
let cleaned = clean(&book(title, "Someone"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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_counted_title_and_release_tags_come_off() {
|
||||
for (title, want, why) in [
|
||||
(
|
||||
"01 - The Three Musketeers",
|
||||
"The Three Musketeers",
|
||||
"numbered_title",
|
||||
),
|
||||
(
|
||||
"06 - The Man in the Iron Mask",
|
||||
"The Man in the Iron Mask",
|
||||
"numbered_title",
|
||||
),
|
||||
(
|
||||
"A Clash of Kings (BD) (v4 0) (lit)",
|
||||
"A Clash of Kings",
|
||||
"release_tags",
|
||||
),
|
||||
(
|
||||
"Orpheus and the Roots of Platonism (no OCR)",
|
||||
"Orpheus and the Roots of Platonism",
|
||||
"release_tags",
|
||||
),
|
||||
] {
|
||||
let cleaned = clean(&book(title, "Someone Else"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some(want), "{title}");
|
||||
assert!(whys(&cleaned).contains(&why), "{title}");
|
||||
}
|
||||
for title in [
|
||||
"911 - Decent into Tyranny",
|
||||
"2003 - Uprising! The Hungarian Revolution of 1956",
|
||||
"1984",
|
||||
"The Book of Lit",
|
||||
] {
|
||||
let cleaned = clean(&book(title, "Someone Else"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dangling_separator_is_punctuation_not_a_wrapper() {
|
||||
let cleaned = clean(&book("A Title Left Trailing -", "Someone"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some("A Title Left Trailing"));
|
||||
assert_eq!(whys(&cleaned), ["title_punctuation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_titles_punctuation_is_set_as_printed() {
|
||||
for (title, want) in [
|
||||
(
|
||||
"Sex Wars : Sexual Dissent and Political Culture",
|
||||
"Sex Wars: Sexual Dissent and Political Culture",
|
||||
),
|
||||
("Jesuits, The", "The Jesuits"),
|
||||
(
|
||||
"Bible Made Impossible, The: Moving from Biblicism",
|
||||
"The Bible Made Impossible: Moving from Biblicism",
|
||||
),
|
||||
("Wissenschaft Der Logik -", "Wissenschaft Der Logik"),
|
||||
(
|
||||
"Crusade for Pan-Europe. Autobiography of a man and a movement.",
|
||||
"Crusade for Pan-Europe. Autobiography of a man and a movement",
|
||||
),
|
||||
("Passions of Christ", "Passions of Christ"),
|
||||
] {
|
||||
let cleaned = clean(&book(title, "Someone"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some(want), "{title}");
|
||||
}
|
||||
for title in [
|
||||
"Martin Luther King Jr.",
|
||||
"Wait...",
|
||||
"Being and Time",
|
||||
"Me, Myself and I",
|
||||
"Hegel: The Phenomenology",
|
||||
] {
|
||||
let cleaned = clean(&book(title, "Someone"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some(title), "{title}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_reference_is_decoded() {
|
||||
let cleaned = clean(&book("Master & Apprentice", "Claudia Gray"));
|
||||
assert_eq!(cleaned.book.title.as_deref(), Some("Master & Apprentice"));
|
||||
assert_eq!(whys(&cleaned), ["html_entity"]);
|
||||
let cleaned = clean(&book("Don't Look — 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]
|
||||
fn a_shouting_title_is_cased_and_the_change_is_recorded() {
|
||||
let cleaned = clean(&book("THE HUMAN CONDITION", "Arendt, Hannah"));
|
||||
|
||||
@@ -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)/)"));
|
||||
|
||||
@@ -44,7 +48,7 @@ static PATH_TITLE: LazyLock<Regex> =
|
||||
/// placeholder.
|
||||
static PLACEHOLDER_TITLE: LazyLock<Regex> = 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 +61,14 @@ static PLACEHOLDER_AUTHOR: LazyLock<Regex> = 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<Regex> = LazyLock::new(|| {
|
||||
pattern(&format!(
|
||||
r"(?i){SPACE}+[-–—]{SPACE}+(?:unknown(?:{SPACE}+author)?|anonymous|n/?a){SPACE}*$"
|
||||
))
|
||||
});
|
||||
|
||||
static NUMERIC_AUTHOR: LazyLock<Regex> =
|
||||
LazyLock::new(|| pattern(&format!(r"^{SPACE}*\d{{3,4}}{SPACE}*(?:$|[{SPACE}.\-–—])")));
|
||||
|
||||
@@ -140,24 +152,40 @@ 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_author", 2),
|
||||
("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),
|
||||
("html_entity", 2),
|
||||
("invalid_isbn", 3),
|
||||
("isbn_with_label", 3),
|
||||
("junk_title", 3),
|
||||
("lowercase_title", 2),
|
||||
("missing_apostrophe", 2),
|
||||
("mojibake_author", 3),
|
||||
("mojibake_title", 3),
|
||||
("name_in_title", 2),
|
||||
("numbered_title", 1),
|
||||
("numeric_author", 4),
|
||||
("path_title", 4),
|
||||
("placeholder_author", 4),
|
||||
("placeholder_isbn", 3),
|
||||
("placeholder_suffix", 2),
|
||||
("placeholder_title", 4),
|
||||
("possible_swap", 2),
|
||||
("publisher_as_author", 3),
|
||||
("release_tags", 1),
|
||||
("sentence_case_title", 1),
|
||||
("title_in_author", 3),
|
||||
("title_punctuation", 1),
|
||||
("underscore_title", 1),
|
||||
("unknown_author", 3),
|
||||
("url_title", 4),
|
||||
];
|
||||
|
||||
/// Everything wrong with a record, named.
|
||||
@@ -184,6 +212,18 @@ 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 crate::fix::tidy_punctuation(title).is_some() {
|
||||
reasons.push("title_punctuation");
|
||||
}
|
||||
if crate::fix::strip_leading_number(title).is_some() {
|
||||
reasons.push("numbered_title");
|
||||
}
|
||||
if crate::fix::strip_release_tags(title).is_some() {
|
||||
reasons.push("release_tags");
|
||||
}
|
||||
if FILENAME_TITLE.is_match(title) {
|
||||
reasons.push("filename_title");
|
||||
}
|
||||
@@ -199,6 +239,19 @@ pub fn problems(title: Option<&str>, author: Option<&str>, isbn: Option<&str>) -
|
||||
{
|
||||
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) {
|
||||
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");
|
||||
}
|
||||
@@ -228,15 +281,37 @@ 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");
|
||||
}
|
||||
if title_in_author(Some(title), Some(author)) {
|
||||
reasons.push("title_in_author");
|
||||
}
|
||||
if isbn
|
||||
.unwrap_or("")
|
||||
.trim_matches(textkit::is_space)
|
||||
.is_empty()
|
||||
{
|
||||
let isbn = isbn.unwrap_or("").trim_matches(textkit::is_space);
|
||||
if isbn.is_empty() {
|
||||
reasons.push("missing_isbn");
|
||||
} else if let Some(fault) = crate::isbn::fault(isbn) {
|
||||
reasons.push(fault);
|
||||
}
|
||||
|
||||
reasons.into_iter().map(str::to_string).collect()
|
||||
@@ -260,6 +335,100 @@ 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::<Vec<_>>()
|
||||
.windows(3)
|
||||
.any(|w| w[0].is_lowercase() && w[1].is_uppercase() && w[2].is_uppercase());
|
||||
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()
|
||||
.map(|c| if c.is_alphanumeric() { c } else { ' ' })
|
||||
.collect::<String>()
|
||||
.to_lowercase()
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.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))
|
||||
}
|
||||
|
||||
/// Whether the title field is a placeholder and the author field is holding
|
||||
/// the real title.
|
||||
///
|
||||
@@ -359,6 +528,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::*;
|
||||
|
||||
+289
-19
@@ -184,6 +184,15 @@ pub fn cluster(kind: Kind, items: &[Item], rules: &Rules) -> Vec<Proposal> {
|
||||
out.extend(proposals_from_group(kind, &group, method));
|
||||
grouped.extend(group.iter().map(|item| item.id));
|
||||
}
|
||||
if kind == Kind::Author {
|
||||
let dropped: Vec<i64> = out.iter().map(|proposal| proposal.drop_id).collect();
|
||||
let standing: Vec<Item> = items
|
||||
.iter()
|
||||
.filter(|item| !dropped.contains(&item.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
out.extend(fuller_form_proposals(&standing));
|
||||
}
|
||||
if kind == Kind::Tag {
|
||||
out.extend(junk_deletes(items, &grouped, rules));
|
||||
out.extend(scheme_proposals(items, &out, &rules.scheme));
|
||||
@@ -286,31 +295,22 @@ pub fn pick_canonical(kind: Kind, group: &[Item]) -> Item {
|
||||
.expect("a group is never empty")
|
||||
}
|
||||
|
||||
fn score(kind: Kind, item: &Item) -> (i64, usize) {
|
||||
fn score(kind: Kind, item: &Item) -> (i64, i64, usize) {
|
||||
let name = &item.name;
|
||||
// An author group is one person under several spellings, so the best
|
||||
// spelling should win however few books carry it: the commonest spelling
|
||||
// in a catalogue built from downloads is often the worst one, and keeping
|
||||
// it spreads it over every book in the group.
|
||||
if kind == Kind::Author {
|
||||
return (author_form(name), item.count, name.chars().count());
|
||||
}
|
||||
let mut score = item.count * 10;
|
||||
|
||||
if is_shouting(name) && name.contains(' ') {
|
||||
score -= 6;
|
||||
}
|
||||
match kind {
|
||||
Kind::Author => {
|
||||
if name.contains(',') || name.contains('|') {
|
||||
score -= 8;
|
||||
}
|
||||
if name
|
||||
.trim_end_matches(textkit::is_space)
|
||||
.ends_with([';', '|', ','])
|
||||
{
|
||||
score -= 10;
|
||||
}
|
||||
if INITIALS_TOGETHER.is_match(name) {
|
||||
score -= 1;
|
||||
}
|
||||
if INITIALS_SPACED.is_match(name) {
|
||||
score += 3;
|
||||
}
|
||||
}
|
||||
Kind::Author => {}
|
||||
Kind::Publisher => {
|
||||
if LEGAL_SUFFIX.is_match(name).unwrap_or(false) {
|
||||
score -= 4;
|
||||
@@ -328,7 +328,56 @@ fn score(kind: Kind, item: &Item) -> (i64, usize) {
|
||||
}
|
||||
}
|
||||
}
|
||||
(score, name.chars().count())
|
||||
(score, 0, name.chars().count())
|
||||
}
|
||||
|
||||
/// How well an author heading is written, independent of how many books
|
||||
/// carry it. Faults that make it wrong as a byline cost far more than the
|
||||
/// preferences that only make it better.
|
||||
fn author_form(name: &str) -> i64 {
|
||||
let mut form = 0;
|
||||
let trimmed = name.trim_end_matches(textkit::is_space);
|
||||
// Turned round, unless what follows the comma is part of the name:
|
||||
// "Copleston, S.J." is a byline; "Copleston, Frederick" is a card.
|
||||
if let Some((_, after)) = trimmed.split_once(',')
|
||||
&& !crate::heading::is_suffix(after)
|
||||
{
|
||||
form -= 100;
|
||||
}
|
||||
if name.contains('|') || trimmed.ends_with([';', '|', ',']) {
|
||||
form -= 100;
|
||||
}
|
||||
if name.contains('(') || name.contains(')') {
|
||||
form -= 100;
|
||||
}
|
||||
if is_shouting(name) && name.contains(' ') {
|
||||
form -= 100;
|
||||
}
|
||||
// A suffix in front: "S.J. Frederick Copleston".
|
||||
if name
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.is_some_and(crate::heading::is_suffix)
|
||||
{
|
||||
form -= 100;
|
||||
}
|
||||
// A full stop on a whole word, or one standing alone: "Plato.",
|
||||
// "Fyodor. Dostoyevsky", "Wouter J. . Hanegraaff".
|
||||
if name.split_whitespace().any(|word| {
|
||||
word == "."
|
||||
|| (word.ends_with('.')
|
||||
&& word.trim_end_matches('.').chars().count() > 1
|
||||
&& !crate::heading::is_suffix(word))
|
||||
}) {
|
||||
form -= 10;
|
||||
}
|
||||
if INITIALS_TOGETHER.is_match(name) {
|
||||
form -= 2;
|
||||
}
|
||||
if INITIALS_SPACED.is_match(name) {
|
||||
form += 2;
|
||||
}
|
||||
form
|
||||
}
|
||||
|
||||
/// Whether a heading is in capitals throughout, by Python's reading: at least
|
||||
@@ -603,6 +652,158 @@ fn author_components(items: &[Item]) -> Vec<Vec<Item>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A name and the same name written out further: "G. W. F. Hegel" and
|
||||
/// "Georg Wilhelm Friedrich Hegel", "Murray Rothbard" and "Murray N.
|
||||
/// Rothbard".
|
||||
///
|
||||
/// The surname must agree, and so must the first given name, written out or
|
||||
/// as its initial. Every other given name of the shorter heading must appear
|
||||
/// in the longer one, in order, likewise. A heading that would fit two longer
|
||||
/// ones that do not fit each other ("David Smith" beside "David Livingstone
|
||||
/// Smith" and "David Woodruff Smith") could be either person, so the whole
|
||||
/// set is left alone.
|
||||
///
|
||||
/// Two people can share a first name and a surname, so these are proposals
|
||||
/// for a person to look at, never as trusted as a respelling: 0.8 when the
|
||||
/// shorter heading is two or more initials, 0.6 when it is a name.
|
||||
fn fuller_form_proposals(items: &[Item]) -> Vec<Proposal> {
|
||||
let people: Vec<(Item, Vec<String>)> = items
|
||||
.iter()
|
||||
.filter(|item| crate::reasons::looks_like_person(&item.name))
|
||||
.filter_map(|item| {
|
||||
let tokens = author_tokens(&item.name);
|
||||
let surname = tokens.last()?;
|
||||
let given = &tokens[..tokens.len() - 1];
|
||||
let sound = (2..=5).contains(&tokens.len())
|
||||
&& !given.contains(surname)
|
||||
&& tokens
|
||||
.iter()
|
||||
.all(|token| token.chars().all(char::is_alphabetic));
|
||||
sound.then(|| (item.clone(), tokens))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut by_surname: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||
for (at, (_, tokens)) in people.iter().enumerate() {
|
||||
by_surname
|
||||
.entry(tokens.last().expect("two tokens or more"))
|
||||
.or_default()
|
||||
.push(at);
|
||||
}
|
||||
let mut surnames: Vec<&&str> = by_surname.keys().collect();
|
||||
surnames.sort();
|
||||
|
||||
let mut out = Vec::new();
|
||||
for surname in surnames {
|
||||
let members = &by_surname[*surname];
|
||||
let given = |at: usize| &people[at].1[..people[at].1.len() - 1];
|
||||
// Components of the "fits" relation among the headings with this surname.
|
||||
let mut seen: Vec<usize> = Vec::new();
|
||||
for &start in members {
|
||||
if seen.contains(&start) {
|
||||
continue;
|
||||
}
|
||||
let mut component = vec![start];
|
||||
let mut grow = 0;
|
||||
while grow < component.len() {
|
||||
let at = component[grow];
|
||||
for &other in members {
|
||||
if !component.contains(&other)
|
||||
&& (fits(given(at), given(other)) || fits(given(other), given(at)))
|
||||
{
|
||||
component.push(other);
|
||||
}
|
||||
}
|
||||
grow += 1;
|
||||
}
|
||||
seen.extend(&component);
|
||||
if component.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
// The fullest headings: those no other heading writes out further.
|
||||
let fullest: Vec<usize> = component
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&at| {
|
||||
!component.iter().any(|&other| {
|
||||
fits(given(at), given(other)) && !fits(given(other), given(at))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let one_person = fullest
|
||||
.iter()
|
||||
.all(|&a| fullest.iter().all(|&b| fits(given(a), given(b))));
|
||||
if !one_person {
|
||||
continue;
|
||||
}
|
||||
// The heading most of the works are under, unless it is faulty as
|
||||
// a byline; a tie goes to the fuller name. Not pick_canonical:
|
||||
// its preference for spaced initials would put fifty books by
|
||||
// "Bertrand Russell" under the one catalogued as "B. Russell".
|
||||
let keep = component
|
||||
.iter()
|
||||
.map(|&at| &people[at])
|
||||
.max_by_key(|(item, tokens)| {
|
||||
(
|
||||
author_form(&item.name).min(0),
|
||||
item.count,
|
||||
tokens.iter().map(|t| t.chars().count()).sum::<usize>(),
|
||||
)
|
||||
})
|
||||
.map(|(item, _)| item.clone())
|
||||
.expect("a component has two members or more");
|
||||
for &at in &component {
|
||||
let item = &people[at].0;
|
||||
if item.name == keep.name {
|
||||
continue;
|
||||
}
|
||||
let keep_given = &author_tokens(&keep.name);
|
||||
let keep_given = &keep_given[..keep_given.len() - 1];
|
||||
let shorter = match fits(given(at), keep_given) {
|
||||
true => given(at),
|
||||
false => keep_given,
|
||||
};
|
||||
let initials = shorter.len() >= 2 && shorter.iter().all(|t| t.chars().count() == 1);
|
||||
out.push(Proposal {
|
||||
kind: Kind::Author.name().to_string(),
|
||||
action: "merge".into(),
|
||||
keep: Some(keep.name.clone()),
|
||||
drop: item.name.clone(),
|
||||
keep_id: Some(keep.id),
|
||||
drop_id: item.id,
|
||||
keep_count: keep.count,
|
||||
drop_count: item.count,
|
||||
method: "fuller_form".to_string(),
|
||||
confidence: if initials { 0.8 } else { 0.6 },
|
||||
evidence: format!(
|
||||
"{} books as '{}' → '{}' ({}): the same name written out further",
|
||||
item.count, item.name, keep.name, keep.count
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the given names `short` are `long`'s, or initials of them, the
|
||||
/// first agreeing and the rest in order.
|
||||
fn fits(short: &[String], long: &[String]) -> bool {
|
||||
fn one(short: &str, long: &str) -> bool {
|
||||
short == long || (short.chars().count() == 1 && long.starts_with(short))
|
||||
}
|
||||
let (Some(first), Some(long_first)) = (short.first(), long.first()) else {
|
||||
return false;
|
||||
};
|
||||
if !one(first, long_first) {
|
||||
return false;
|
||||
}
|
||||
let mut rest = long[1..].iter();
|
||||
short[1..]
|
||||
.iter()
|
||||
.all(|token| rest.by_ref().any(|candidate| one(token, candidate)))
|
||||
}
|
||||
|
||||
/// Every bucket of a key, including the ones with a single member, in
|
||||
/// first-seen order.
|
||||
fn keyed_buckets(items: &[Item], key: impl Fn(&str) -> String) -> Vec<Vec<Item>> {
|
||||
@@ -713,6 +914,21 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_spelling_loses_to_a_byline_however_common() {
|
||||
for (bad, good) in [
|
||||
("Saint Thomas (aquinas)", "Saint Thomas Aquinas"),
|
||||
("S.J. Frederick Copleston", "Frederick Copleston, S.J."),
|
||||
("Fyodor. Dostoyevsky", "Fyodor Dostoyevsky"),
|
||||
("G.W.F. Hegel", "G. W. F. Hegel"),
|
||||
] {
|
||||
let items = [item(1, bad, 9), item(2, good, 1)];
|
||||
let proposals = cluster(Kind::Author, &items, &Rules::default());
|
||||
assert_eq!(proposals.len(), 1, "{bad}");
|
||||
assert_eq!(proposals[0].keep.as_deref(), Some(good), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_respelling_is_trusted_further_than_an_inversion() {
|
||||
let items = [
|
||||
@@ -816,6 +1032,60 @@ mod tests {
|
||||
assert_eq!(proposals[0].action, "merge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_written_out_further_is_one_heading() {
|
||||
let items = [
|
||||
item(1, "C. S. Lewis", 23),
|
||||
item(2, "Clive Staples Lewis", 3),
|
||||
item(3, "Murray Rothbard", 1),
|
||||
item(4, "Murray N. Rothbard", 8),
|
||||
item(5, "Murray Newton Rothbard", 2),
|
||||
item(6, "Bertrand Russell", 52),
|
||||
item(7, "B. Russell", 1),
|
||||
];
|
||||
let proposals = cluster(Kind::Author, &items, &Rules::default());
|
||||
let mut pairs: Vec<(&str, &str, f64)> = proposals
|
||||
.iter()
|
||||
.inspect(|p| assert_eq!(p.method, "fuller_form"))
|
||||
.map(|p| (p.drop.as_str(), p.keep.as_deref().unwrap(), p.confidence))
|
||||
.collect();
|
||||
pairs.sort_by(|a, b| a.0.cmp(b.0));
|
||||
// The heading most works are under is kept, however short; a pair of
|
||||
// initials is more surely the same person than a bare first name.
|
||||
assert_eq!(
|
||||
pairs,
|
||||
[
|
||||
("B. Russell", "Bertrand Russell", 0.6),
|
||||
("Clive Staples Lewis", "C. S. Lewis", 0.8),
|
||||
("Murray Newton Rothbard", "Murray N. Rothbard", 0.6),
|
||||
("Murray Rothbard", "Murray N. Rothbard", 0.6),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_could_be_two_people_is_left_alone() {
|
||||
let items = [
|
||||
item(1, "David Smith", 1),
|
||||
item(2, "David Livingstone Smith", 2),
|
||||
item(3, "David Woodruff Smith", 2),
|
||||
];
|
||||
assert!(cluster(Kind::Author, &items, &Rules::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_first_name_or_a_doubled_surname_is_not_a_fuller_form() {
|
||||
let items = [
|
||||
item(1, "Peter W. Martens", 1),
|
||||
item(2, "Paul M. Blowers Peter W Martens", 1),
|
||||
item(3, "Bertrand Russell", 52),
|
||||
item(4, "Bertrand Russell Russell", 1),
|
||||
item(5, "Masud Khan", 1),
|
||||
item(6, "M. Masud R. Khan", 1),
|
||||
];
|
||||
assert!(cluster(Kind::Author, &items, &Rules::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_in_nothing_out() {
|
||||
assert!(cluster(Kind::Author, &[], &Rules::default()).is_empty());
|
||||
|
||||
+156
-3
@@ -20,6 +20,8 @@ So this asks, and that is the only thing it does.
|
||||
- **Filling in a reference** you have only the identifier for.
|
||||
- **Before citing something**, to check the year and the authors are what you
|
||||
think they are.
|
||||
- **Cataloguing a book that came with no identifier**, to find the editions a
|
||||
register has under its title, and an ISBN to file it by.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -84,7 +86,7 @@ is a failure — nobody replied, and the identifier may be perfectly good.
|
||||
|---|---|---|
|
||||
| `doi` | Crossref | It assigns most scholarly DOIs |
|
||||
| `arxiv` | the arXiv | Its own register of preprints |
|
||||
| `isbn` | OpenLibrary's edition record, then its index, then Google Books | Books, without a key |
|
||||
| `isbn` | OpenLibrary's index, then its edition record, then Google Books | Books, without a key |
|
||||
|
||||
One register is enough for a DOI or a preprint: the body that assigns the
|
||||
identifier is the only one that has it. A book is different. An ISBN is
|
||||
@@ -95,6 +97,14 @@ names them. So the registers are asked in turn and the first complete answer
|
||||
wins. An incomplete one is kept in case nothing better comes, and a register
|
||||
being down is a failure only when every register is.
|
||||
|
||||
OpenLibrary's index answers about the work, not the edition: its publishers,
|
||||
languages, years and page counts are every edition's at once, and the first
|
||||
of each is usually another edition's. So for a book it gives only the title,
|
||||
the authors and the subjects, and the `container`, `language`, `year` and
|
||||
`pages` of a record come from the edition record for that ISBN, or from
|
||||
Google Books when the edition record does not say. A field neither gives is
|
||||
left out rather than filled from the work.
|
||||
|
||||
Google Books is asked last because it answers anonymous callers only until a
|
||||
daily quota runs out, after which it replies `429` to everyone sharing the
|
||||
address.
|
||||
@@ -107,6 +117,147 @@ register that is rate-limiting, short enough that one which is simply down
|
||||
does not hold up a pipeline. An answer this cannot read is not retried,
|
||||
because it will not read any better next time.
|
||||
|
||||
## Covers
|
||||
|
||||
```sh
|
||||
bibfetch cover 978-0-306-40615-7 -o cover.jpg
|
||||
```
|
||||
|
||||
Fetches a book's cover from Open Library's covers store by its ISBN and
|
||||
writes the image. The thirteen-digit form is asked first and the ten-digit
|
||||
form second, because a book is often filed under only one of them; an ISBN
|
||||
whose check digit is wrong is asked about as written, since converting it
|
||||
would give another book's number. `--cover-id` names an Open Library cover id
|
||||
to ask by last, which is what the `cover_id` field of a lookup record holds:
|
||||
the first cover in Open Library's record of that edition, never the cover its
|
||||
index picked for the whole work, which is often another edition's. The cover
|
||||
id is asked only when every form of the ISBN asked was answered with no cover; if
|
||||
asking by ISBN failed, that failure is the result.
|
||||
|
||||
What comes back is checked before it is written: a JPEG or PNG by its bytes
|
||||
as well as by what the server says, whole to its end marker (`FF D9` for a
|
||||
JPEG, `IEND` for a PNG), no larger than ten megabytes, reached in at
|
||||
most three redirects, each over HTTPS to `covers.openlibrary.org`,
|
||||
`archive.org` or a host under `archive.org`, and never to an address by number.
|
||||
One request is made at a time, a `429` or `503` is waited out for as long as
|
||||
its `Retry-After` says, up to a minute, and the whole fetch, every attempt and
|
||||
redirect included, stops after two minutes. The two minutes start once it is
|
||||
the fetch's turn, so a fetch queued behind others in the same process can wait
|
||||
that long again first.
|
||||
|
||||
Open Library allows a hundred covers by ISBN every five minutes from one
|
||||
address, and refuses the rest with `403`. Covers asked by ISBN are kept three
|
||||
seconds apart across the whole process (`Covers::pace`), which stays under that
|
||||
limit however long a run goes. A refusal all the same is not mistaken for an
|
||||
outage: the other form of the ISBN is not asked, the cover id is, because
|
||||
Open Library does not limit those, and with no cover found that way the fetch
|
||||
fails with `Error::Limited`, which means ask again later.
|
||||
|
||||
| Option | Effect |
|
||||
|---|---|
|
||||
| `-o`, `--output <FILE>` | Where to write the image |
|
||||
| `--size <SIZE>` | `small`, `medium` or `large`. Default `large` |
|
||||
| `--cover-id <ID>` | An Open Library cover id to ask by when the ISBN has none |
|
||||
|
||||
Exit `0` the cover was written, `1` Open Library has none, `65` the argument
|
||||
was not an ISBN or the answer was not an image, `69` Open Library could not be
|
||||
reached, `74` the file could not be written, `75` Open Library refused for
|
||||
being asked too often and will answer later.
|
||||
|
||||
From Rust, `bibfetch::cover(&agent, isbn, cover_id, size)` returns
|
||||
`Ok(None)` when there is no cover, and a [`Cover`](src/cover.rs) with the
|
||||
bytes, the media type and the address asked when there is.
|
||||
|
||||
## Searching by title
|
||||
|
||||
```
|
||||
$ bibfetch search --title 'The First World War' --author Howard --limit 2
|
||||
{"v":1,"id":"9780192853622","kind":"isbn","found":true,"source":"openlibrary","title":"The First World War","authors":["Michael Eliot Howard"],"year":2002,"container":"Oxford University Press","subjects":["World War, 1914-1918"],"language":"eng","cover_id":1123124}
|
||||
{"v":1,"id":"9780199205592","kind":"isbn","found":true,"source":"openlibrary","title":"The First World War: A Very Short Introduction","authors":["Michael Howard"],"year":2007,"container":"Oxford University Press","language":"eng","cover_id":14606475}
|
||||
```
|
||||
|
||||
A book that arrives as a file often has no identifier to ask about, only a
|
||||
title and perhaps a name. This asks which books a register has under those,
|
||||
and prints one record per candidate: Open Library's index first, and Google
|
||||
Books only when Open Library has nothing.
|
||||
|
||||
Open Library's title search is strict. Given an author as well, it finds
|
||||
nothing for *The Ladder of Divine Ascent* and four editions of *Ladder of
|
||||
Divine Ascent*. So when the title as given finds nothing, the title without a
|
||||
leading "The", "A" or "An" is asked next, and then the title and author as one
|
||||
free-text query. Each is asked only when the one before found nothing, so a
|
||||
title that matches costs one request. The looser questions can bring back
|
||||
books that only share words with the title, which is one more reason the
|
||||
candidates are for the caller to judge.
|
||||
|
||||
Each candidate is one edition. Open Library's index answers with works, and
|
||||
names the edition of each that best matches the search. The ISBN, publisher,
|
||||
language, year and cover are that edition's and no other's: a field the
|
||||
edition does not give is left out rather than filled from the work, whose
|
||||
publishers, years and ISBNs belong to all its editions at once. Only the
|
||||
title, the authors and the subjects, which describe the work, are the work's.
|
||||
Open Library's index gives no length for an edition, so its candidates carry
|
||||
no `pages`. Google Books answers with volumes, which are editions already.
|
||||
|
||||
| Field | When the candidate has an ISBN | When it has none |
|
||||
|---|---|---|
|
||||
| `id` | The first ISBN of the edition whose check digit agrees, in thirteen digits; one written in thirteen is taken over one written in ten | The register's own key: an Open Library id such as `OL37863121M` for the edition, or `OL267171W` for the work when no edition was named; a Google Books volume id |
|
||||
| `kind` | `isbn` | `olid` for Open Library, `googlebooks` for Google Books |
|
||||
|
||||
A work the index names no edition of, or names one it gives neither an ISBN
|
||||
nor a key for, is a candidate named by the work's key, with its title,
|
||||
authors and subjects and nothing an edition would say.
|
||||
|
||||
An ISBN whose check digit is wrong is passed over rather than corrected, and
|
||||
Google's shelfmarks, typed `OTHER`, are not read as ISBNs even when their
|
||||
digits would pass for one. A record of kind `isbn` can be handed straight back
|
||||
to `bibfetch` for everything the registers say about that edition; `olid` and
|
||||
`googlebooks` are names no lookup here answers about.
|
||||
|
||||
`cover_id` is the same thing it is in a lookup record: the first cover in
|
||||
Open Library's record of the edition the record names, by that edition's ISBN
|
||||
or its key, so `bibfetch cover --cover-id` fetches that edition's cover and no
|
||||
other. The cover the index picked for the whole work is never asked for,
|
||||
because it is often another edition's. Google Books knows nothing of Open
|
||||
Library's covers and gives none.
|
||||
|
||||
The candidates are what the register said, in the order it said them. This
|
||||
makes no judgement about which one is the book in hand, and keeps one that is
|
||||
plainly another book, because a title is not an identifier: *The Hamlet* comes
|
||||
back for *Hamlet*. Deciding whether a candidate is the same work is a
|
||||
comparison of titles, and [`bibclean`](../bibclean/README.md)'s `same_work`
|
||||
is one.
|
||||
|
||||
```sh
|
||||
bibfetch search --title 'Anathem' --author Stephenson \
|
||||
| jq -r 'select(.kind == "isbn") | .id' | head -1
|
||||
```
|
||||
|
||||
Open Library having nothing is an answer only once Google Books has been
|
||||
asked and has nothing either. When Google Books cannot be reached, the search
|
||||
fails rather than say no register has the title, and when it refuses for its
|
||||
quota (`403`, or `429` on every attempt) the failure says so and the command
|
||||
exits `75`. Open Library being down is a failure only when Google Books has
|
||||
nothing to offer in its place. Each is asked the same way a lookup asks,
|
||||
retried with the same waits, except that a `403` from Google Books is not
|
||||
asked again. Open Library is sent the title and the author as written; Google Books
|
||||
is sent each word as its own `intitle:` or `inauthor:` term, so nothing in a
|
||||
title is read as search syntax.
|
||||
|
||||
| Option | Effect |
|
||||
|---|---|
|
||||
| `--title <TITLE>` | The title, or as much of it as you have |
|
||||
| `--author <AUTHOR>` | An author's name, or part of one |
|
||||
| `--limit <COUNT>` | The most candidates to print, `1` to `40`. Default `10` |
|
||||
|
||||
Exit `0` at least one candidate was printed, `1` no register has the title,
|
||||
`65` the title was empty, `69` a register that had to answer could not be
|
||||
reached, `74` the output could not be written, `75` Google Books refused for
|
||||
its quota.
|
||||
|
||||
From Rust, `bibfetch::search(&agent, title, author, limit, attempts)` returns
|
||||
the candidates, empty when no register has the title.
|
||||
|
||||
## Reaching the network
|
||||
|
||||
This and [`emb`](../emb/README.md) are the only two tools here that do. Both
|
||||
@@ -114,10 +265,12 @@ say so in `--help`, and for both it is the whole of what they do rather than
|
||||
something that happens on the way to something else — which is the condition
|
||||
under which [the contract](../../docs/contract.md) allows it at all.
|
||||
|
||||
Nothing is cached, nothing is stored, and nothing is sent but the identifier
|
||||
Nothing is cached, nothing is stored but a cover you asked to have written,
|
||||
and nothing is sent but the identifier, or the title and author searched for,
|
||||
and the address you pass to `--polite`.
|
||||
|
||||
## See also
|
||||
|
||||
- [`idnorm`](../idnorm/README.md) — reading the identifier in the first place.
|
||||
- [`bibclean`](../bibclean/README.md) — the rest of a catalogue record.
|
||||
- [`bibclean`](../bibclean/README.md) — the rest of a catalogue record, and
|
||||
whether a candidate is the same work.
|
||||
+30
-25
@@ -89,10 +89,6 @@ pub fn lookup(
|
||||
}
|
||||
|
||||
/// Ask a register, retrying a failure that might not be one.
|
||||
///
|
||||
/// Waits a second before the second attempt and two before the third: long
|
||||
/// enough for a register that is rate-limiting, short enough that one which
|
||||
/// is simply down does not hold up a pipeline.
|
||||
fn ask(
|
||||
agent: &ureq::Agent,
|
||||
source: Source,
|
||||
@@ -100,39 +96,48 @@ fn ask(
|
||||
kind: &str,
|
||||
attempts: u32,
|
||||
) -> Result<crate::Record, Error> {
|
||||
let mut last = Error::Unreachable("no attempt was made".into());
|
||||
match get(agent, &source.url(id), attempts)? {
|
||||
Some(body) => source.read(id, kind, &body),
|
||||
// A register that does not have it says so with a status, and that is
|
||||
// an answer rather than a failure.
|
||||
None => Ok(crate::missing(id, kind, source)),
|
||||
}
|
||||
}
|
||||
|
||||
for attempt in 0..attempts.max(1) {
|
||||
match fetch(agent, source, id, kind) {
|
||||
Ok(record) => return Ok(record),
|
||||
// A shape this cannot read will not read any better next time.
|
||||
Err(e @ Error::Shape(_)) => return Err(e),
|
||||
/// The body at an address, or `None` when the register says it has no such
|
||||
/// thing; a failure is asked again.
|
||||
///
|
||||
/// Waits a second before the second attempt and two before the third: long
|
||||
/// enough for a register that is rate-limiting, short enough that one which
|
||||
/// is simply down does not hold up a pipeline. Reading what came back is left
|
||||
/// to the caller, because an answer this cannot read will not read any better
|
||||
/// next time.
|
||||
pub(crate) fn get(agent: &ureq::Agent, url: &str, attempts: u32) -> Result<Option<String>, Error> {
|
||||
let attempts = attempts.max(1);
|
||||
let mut last = Error::Unreachable("no attempt was made".into());
|
||||
for attempt in 0..attempts {
|
||||
match once(agent, url) {
|
||||
Ok(answer) => return Ok(answer),
|
||||
Err(e) => last = e,
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(1 << attempt));
|
||||
if attempt + 1 < attempts {
|
||||
std::thread::sleep(Duration::from_secs(1 << attempt.min(5)));
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
|
||||
fn fetch(
|
||||
agent: &ureq::Agent,
|
||||
source: Source,
|
||||
id: &str,
|
||||
kind: &str,
|
||||
) -> Result<crate::Record, Error> {
|
||||
let response = agent.get(source.url(id)).call();
|
||||
let mut response = match response {
|
||||
fn once(agent: &ureq::Agent, url: &str) -> Result<Option<String>, Error> {
|
||||
let mut response = match agent.get(url).call() {
|
||||
Ok(response) => response,
|
||||
// A register that does not have it says so with a status, and that is
|
||||
// an answer rather than a failure.
|
||||
Err(ureq::Error::StatusCode(404)) => return Ok(crate::missing(id, kind, source)),
|
||||
Err(ureq::Error::StatusCode(404)) => return Ok(None),
|
||||
Err(e) => return Err(Error::Unreachable(e.to_string())),
|
||||
};
|
||||
let body = response
|
||||
response
|
||||
.body_mut()
|
||||
.read_to_string()
|
||||
.map_err(|e| Error::Unreachable(e.to_string()))?;
|
||||
source.read(id, kind, &body)
|
||||
.map(Some)
|
||||
.map_err(|e| Error::Unreachable(e.to_string()))
|
||||
}
|
||||
|
||||
/// Who is asking.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,8 +12,14 @@
|
||||
//! them: Crossref for a DOI, the arXiv for a preprint, OpenLibrary for a
|
||||
//! book. There is no register for an ISSN that answers without a key, so an
|
||||
//! ISSN is looked up as the journal of a work rather than on its own.
|
||||
//!
|
||||
//! A book with no identifier at all can still be looked for by its title,
|
||||
//! with [`search()`]: Open Library's index, then Google Books, each candidate
|
||||
//! a record of one edition, in the order the register gave them.
|
||||
|
||||
pub mod ask;
|
||||
pub mod cover;
|
||||
pub mod search;
|
||||
pub mod source;
|
||||
|
||||
use std::time::Duration;
|
||||
@@ -21,6 +27,8 @@ use std::time::Duration;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use cover::{Cover, CoverSize, cover};
|
||||
pub use search::search;
|
||||
pub use source::Source;
|
||||
|
||||
/// How long to wait on a register before giving up.
|
||||
@@ -74,6 +82,13 @@ pub struct Record {
|
||||
/// How many pages the register says it has.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pages: Option<u32>,
|
||||
/// The first cover id in Open Library's record of this edition, for
|
||||
/// [`cover()`] to ask by when the ISBN has none. Taken from the edition
|
||||
/// record only, never from the index's cover for the work, which is
|
||||
/// often another edition's; `None` when the edition names no cover or
|
||||
/// the lookup stopped before asking for the edition record.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cover_id: Option<u64>,
|
||||
}
|
||||
|
||||
fn version() -> u32 {
|
||||
@@ -95,6 +110,11 @@ pub enum Error {
|
||||
Shape(String),
|
||||
/// Nothing here knows where to ask about this kind.
|
||||
NoRegister(String),
|
||||
/// What was asked about is not an identifier of the kind it should be.
|
||||
Invalid(String),
|
||||
/// The register refused because it has been asked too often from this
|
||||
/// address. It is not down, and asking again later will work.
|
||||
Limited(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
@@ -105,6 +125,8 @@ impl std::fmt::Display for Error {
|
||||
Error::NoRegister(kind) => {
|
||||
write!(f, "no register here answers about {kind} identifiers")
|
||||
}
|
||||
Error::Invalid(why) => write!(f, "{why}"),
|
||||
Error::Limited(why) => write!(f, "{why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +152,7 @@ pub fn missing(id: &str, kind: &str, source: Source) -> Record {
|
||||
subjects: Vec::new(),
|
||||
language: None,
|
||||
pages: None,
|
||||
cover_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +210,9 @@ impl Record {
|
||||
if self.pages.is_none() {
|
||||
self.pages = other.pages;
|
||||
}
|
||||
if self.cover_id.is_none() {
|
||||
self.cover_id = other.cover_id;
|
||||
}
|
||||
// Which register answered becomes which registers did.
|
||||
if !self.source.split('+').any(|s| s == other.source) {
|
||||
self.source = format!("{}+{}", self.source, other.source);
|
||||
@@ -239,11 +265,10 @@ mod merge_tests {
|
||||
let mut index = rec("openlibrary");
|
||||
index.title = Some("The First World War".into());
|
||||
index.authors = vec!["Michael Howard".into()];
|
||||
index.year = Some(2007);
|
||||
|
||||
edition.fill_from(index);
|
||||
assert_eq!(edition.authors, ["Michael Howard"]);
|
||||
assert_eq!(edition.year, Some(2007));
|
||||
assert_eq!(edition.language.as_deref(), Some("eng"));
|
||||
// The fuller title arrived first and is not displaced by the shorter.
|
||||
assert_eq!(
|
||||
edition.title.as_deref(),
|
||||
|
||||
+160
-11
@@ -29,33 +29,117 @@ Exit codes: 0 every identifier was found, 1 at least one was not,
|
||||
Example:
|
||||
|
||||
idnorm refs.txt | bibfetch | jq -r 'select(.found) | .title'
|
||||
idnorm --kind doi refs.txt | bibfetch --polite you@example.org"
|
||||
idnorm --kind doi refs.txt | bibfetch --polite you@example.org
|
||||
bibfetch cover 978-0-306-40615-7 -o cover.jpg
|
||||
bibfetch search --title 'The First World War' --author Howard"
|
||||
)]
|
||||
struct Args {
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
|
||||
/// Identifier records to look up, as `idnorm` writes them. Reads stdin
|
||||
/// when absent.
|
||||
path: Option<PathBuf>,
|
||||
|
||||
/// An address to put in the request, which the registers ask for and
|
||||
/// answer faster when they get.
|
||||
#[arg(long, value_name = "EMAIL")]
|
||||
#[arg(long, global = true, value_name = "EMAIL")]
|
||||
polite: Option<String>,
|
||||
|
||||
/// How long to wait on a register, in seconds.
|
||||
#[arg(long, default_value_t = bibfetch::TIMEOUT.as_secs(), value_name = "SECONDS")]
|
||||
#[arg(long, global = true, default_value_t = bibfetch::TIMEOUT.as_secs(), value_name = "SECONDS")]
|
||||
timeout: u64,
|
||||
|
||||
/// How many times to ask before believing a failure.
|
||||
#[arg(long, default_value_t = bibfetch::ATTEMPTS, value_name = "COUNT")]
|
||||
#[arg(long, global = true, default_value_t = bibfetch::ATTEMPTS, value_name = "COUNT")]
|
||||
attempts: u32,
|
||||
}
|
||||
|
||||
#[derive(clap::Subcommand)]
|
||||
enum Command {
|
||||
/// Fetch a book's cover from Open Library by its ISBN.
|
||||
///
|
||||
/// Exit codes: 0 the cover was written, 1 Open Library has none,
|
||||
/// 65 not an ISBN or not an image, 69 Open Library could not be reached,
|
||||
/// 74 the file could not be written.
|
||||
Cover {
|
||||
/// The ISBN, ten or thirteen digits, hyphens or not.
|
||||
isbn: String,
|
||||
/// Where to write the image.
|
||||
#[arg(short, long, value_name = "FILE")]
|
||||
output: PathBuf,
|
||||
/// Which size to ask for.
|
||||
#[arg(long, value_enum, default_value_t = Size::Large)]
|
||||
size: Size,
|
||||
/// An Open Library cover id to ask by when the ISBN has no cover.
|
||||
#[arg(long, value_name = "ID")]
|
||||
cover_id: Option<u64>,
|
||||
},
|
||||
/// Find the books a register has under a title, and an author.
|
||||
///
|
||||
/// Prints one record per candidate edition, in the order the register
|
||||
/// gave them: Open Library's index, or Google Books when that has
|
||||
/// nothing. Which one is the book in hand is left to you.
|
||||
///
|
||||
/// Exit codes: 0 at least one candidate, 1 none, 65 no title,
|
||||
/// 69 no register could be reached, 74 the output could not be written.
|
||||
Search {
|
||||
/// The title, or as much of it as you have.
|
||||
#[arg(long)]
|
||||
title: String,
|
||||
/// An author's name, or part of one.
|
||||
#[arg(long)]
|
||||
author: Option<String>,
|
||||
/// The most candidates to print.
|
||||
#[arg(long, default_value_t = 10, value_name = "COUNT",
|
||||
value_parser = clap::value_parser!(u16).range(1..=bibfetch::search::MAX_LIMIT as i64))]
|
||||
limit: u16,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, clap::ValueEnum)]
|
||||
enum Size {
|
||||
Small,
|
||||
Medium,
|
||||
Large,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Args = match catena_cli::parse() {
|
||||
Ok(args) => args,
|
||||
Err(code) => return code,
|
||||
};
|
||||
|
||||
let agent = bibfetch::ask::Ask {
|
||||
polite: args.polite.clone(),
|
||||
timeout: Duration::from_secs(args.timeout),
|
||||
attempts: args.attempts,
|
||||
}
|
||||
.agent();
|
||||
|
||||
match &args.command {
|
||||
Some(Command::Cover {
|
||||
isbn,
|
||||
output,
|
||||
size,
|
||||
cover_id,
|
||||
}) => return cover(&agent, args.attempts, isbn, output, *size, *cover_id),
|
||||
Some(Command::Search {
|
||||
title,
|
||||
author,
|
||||
limit,
|
||||
}) => {
|
||||
return search(
|
||||
&agent,
|
||||
args.attempts,
|
||||
title,
|
||||
author.as_deref(),
|
||||
usize::from(*limit),
|
||||
);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
let text = match catena_cli::read_text(args.path.as_deref()) {
|
||||
Ok(text) => text,
|
||||
Err((code, why)) => {
|
||||
@@ -64,13 +148,6 @@ fn main() -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
let agent = bibfetch::ask::Ask {
|
||||
polite: args.polite.clone(),
|
||||
timeout: Duration::from_secs(args.timeout),
|
||||
attempts: args.attempts,
|
||||
}
|
||||
.agent();
|
||||
|
||||
let mut records = Vec::new();
|
||||
let mut missing = 0usize;
|
||||
|
||||
@@ -114,6 +191,78 @@ fn main() -> ExitCode {
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch one cover and write it where asked.
|
||||
fn cover(
|
||||
agent: &ureq::Agent,
|
||||
attempts: u32,
|
||||
isbn: &str,
|
||||
output: &std::path::Path,
|
||||
size: Size,
|
||||
cover_id: Option<u64>,
|
||||
) -> ExitCode {
|
||||
let covers = bibfetch::cover::Covers {
|
||||
attempts,
|
||||
..Default::default()
|
||||
};
|
||||
let size = match size {
|
||||
Size::Small => bibfetch::CoverSize::Small,
|
||||
Size::Medium => bibfetch::CoverSize::Medium,
|
||||
Size::Large => bibfetch::CoverSize::Large,
|
||||
};
|
||||
match covers.fetch(agent, isbn, cover_id, size) {
|
||||
Ok(Some(found)) => match std::fs::write(output, &found.bytes) {
|
||||
Ok(()) => ExitCode::from(exit::OK),
|
||||
Err(why) => {
|
||||
eprintln!("bibfetch: {}: {why}", output.display());
|
||||
ExitCode::from(exit::IO)
|
||||
}
|
||||
},
|
||||
Ok(None) => {
|
||||
eprintln!("bibfetch: {isbn}: Open Library has no cover");
|
||||
ExitCode::from(exit::NO)
|
||||
}
|
||||
Err(why) => {
|
||||
eprintln!("bibfetch: {isbn}: {why}");
|
||||
ExitCode::from(match why {
|
||||
bibfetch::Error::Unreachable(_) => exit::UNAVAILABLE,
|
||||
bibfetch::Error::Limited(_) => exit::TEMPFAIL,
|
||||
_ => exit::DATA,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Search by title and print the candidates.
|
||||
fn search(
|
||||
agent: &ureq::Agent,
|
||||
attempts: u32,
|
||||
title: &str,
|
||||
author: Option<&str>,
|
||||
limit: usize,
|
||||
) -> ExitCode {
|
||||
match bibfetch::search(agent, title, author, limit, attempts) {
|
||||
Ok(found) => {
|
||||
let wrote = catena_cli::stream("bibfetch", &found);
|
||||
if format!("{wrote:?}") != format!("{:?}", ExitCode::from(exit::OK)) {
|
||||
return wrote;
|
||||
}
|
||||
if found.is_empty() {
|
||||
eprintln!("bibfetch: no register has {title:?}");
|
||||
return ExitCode::from(exit::NO);
|
||||
}
|
||||
ExitCode::from(exit::OK)
|
||||
}
|
||||
Err(why) => {
|
||||
eprintln!("bibfetch: {why}");
|
||||
ExitCode::from(match why {
|
||||
bibfetch::Error::Invalid(_) => exit::DATA,
|
||||
bibfetch::Error::Limited(_) => exit::TEMPFAIL,
|
||||
_ => exit::UNAVAILABLE,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier and its kind out of one record.
|
||||
fn read_identifier(line: &str) -> Result<(String, String), String> {
|
||||
let value: serde_json::Value =
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+206
-41
@@ -17,9 +17,10 @@ pub enum Source {
|
||||
Arxiv,
|
||||
/// OpenLibrary, for books by ISBN.
|
||||
OpenLibrary,
|
||||
/// OpenLibrary's index, rather than its edition record. Asked when the
|
||||
/// edition record has the book but not who wrote it, which is often: an
|
||||
/// edition names its authors by key, and the index names them.
|
||||
/// OpenLibrary's index, rather than its edition record. Asked for what is
|
||||
/// true of the work — the title, the authors by name, the subjects —
|
||||
/// because an edition names its authors by key and the index names them.
|
||||
/// Never for what differs between editions.
|
||||
OpenLibrarySearch,
|
||||
/// Google Books, for books by ISBN. Asked last, because it answers
|
||||
/// anonymous callers only until a daily quota runs out.
|
||||
@@ -55,14 +56,14 @@ impl Source {
|
||||
match kind {
|
||||
"doi" => &[Source::Crossref],
|
||||
"arxiv" => &[Source::Arxiv],
|
||||
// The index first. Asked for the fields by name it answers with
|
||||
// the title, the authors, the publisher, the language, a page
|
||||
// count and the subjects in one request, which is the whole of
|
||||
// what a catalogue wants; the edition record is then needed only
|
||||
// for a subtitle or a publisher the index did not give. Asking it
|
||||
// second cost three requests per book where one usually does, and
|
||||
// at three books in flight that is the difference between two
|
||||
// days and two hours.
|
||||
// The index first, for what is true of the work: the title, the
|
||||
// authors by name, the subjects. Then the edition record, for
|
||||
// what is true of this edition only: the publisher, the language,
|
||||
// the year and the length. The index answers about the work, and
|
||||
// its publishers, languages and years are every edition's at
|
||||
// once, so they are not asked of it; the lookup goes on to the
|
||||
// edition record for them. Google Books last, for whatever the
|
||||
// edition record does not say.
|
||||
"isbn" => &[
|
||||
Source::OpenLibrarySearch,
|
||||
Source::OpenLibrary,
|
||||
@@ -83,12 +84,16 @@ impl Source {
|
||||
Source::OpenLibrary => {
|
||||
format!("https://openlibrary.org/isbn/{}.json", encode(id))
|
||||
}
|
||||
// `fields` or the index answers with a handful of defaults and
|
||||
// keeps the rest, which is how a language it holds went unread.
|
||||
// Only what is true of the work. Not `publisher`, `language`,
|
||||
// `first_publish_year` or `number_of_pages_median`: those are every
|
||||
// edition's at once, and the first of each is usually another
|
||||
// edition's (the Penguin *War and Peace* came back Spanish, from
|
||||
// W.W. Norton, in 1845). Not `cover_i`: that is the cover chosen
|
||||
// for the whole work, often another edition's in another
|
||||
// translation or language.
|
||||
Source::OpenLibrarySearch => format!(
|
||||
"https://openlibrary.org/search.json?q=isbn:{}\
|
||||
&fields=title,subtitle,author_name,first_publish_year,publisher,language,subject,\
|
||||
number_of_pages_median&limit=1",
|
||||
&fields=title,subtitle,author_name,subject&limit=1",
|
||||
encode(id)
|
||||
),
|
||||
Source::GoogleBooks => format!(
|
||||
@@ -114,7 +119,7 @@ number_of_pages_median&limit=1",
|
||||
///
|
||||
/// A DOI suffix may hold a slash, a question mark or a hash, and every one of
|
||||
/// those means something else in a URL.
|
||||
fn encode(text: &str) -> String {
|
||||
pub(crate) fn encode(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for byte in text.bytes() {
|
||||
match byte {
|
||||
@@ -128,7 +133,7 @@ fn encode(text: &str) -> String {
|
||||
}
|
||||
|
||||
/// A record with the fields nothing found fills in.
|
||||
fn blank(id: &str, kind: &str, source: Source) -> Record {
|
||||
pub(crate) fn blank(id: &str, kind: &str, source: Source) -> Record {
|
||||
let mut record = crate::missing(id, kind, source);
|
||||
record.found = true;
|
||||
record
|
||||
@@ -245,6 +250,9 @@ struct OpenLibraryBook {
|
||||
languages: Vec<OpenLibraryKey>,
|
||||
#[serde(default)]
|
||||
number_of_pages: Option<u32>,
|
||||
/// Cover ids, best first. A deleted cover is left in the list as `-1`.
|
||||
#[serde(default)]
|
||||
covers: Vec<i64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -275,6 +283,11 @@ fn open_library(id: &str, kind: &str, body: &str) -> Result<Record, Error> {
|
||||
.find_map(|l| l.key.rsplit('/').next().map(str::to_string))
|
||||
.filter(|l| !l.is_empty());
|
||||
record.pages = book.number_of_pages;
|
||||
// The edition's own cover, and the only place a cover id is taken from.
|
||||
record.cover_id = book
|
||||
.covers
|
||||
.into_iter()
|
||||
.find_map(|id| u64::try_from(id).ok().filter(|id| *id > 0));
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
@@ -284,6 +297,8 @@ struct SearchReply {
|
||||
docs: Vec<SearchDoc>,
|
||||
}
|
||||
|
||||
/// What the index says about a work. Only the fields true of every edition
|
||||
/// are read, so an answer that carries the others anyway cannot leak them.
|
||||
#[derive(Deserialize)]
|
||||
struct SearchDoc {
|
||||
#[serde(default)]
|
||||
@@ -293,15 +308,7 @@ struct SearchDoc {
|
||||
#[serde(default)]
|
||||
author_name: Vec<String>,
|
||||
#[serde(default)]
|
||||
first_publish_year: Option<i64>,
|
||||
#[serde(default)]
|
||||
publisher: Vec<String>,
|
||||
#[serde(default)]
|
||||
language: Vec<String>,
|
||||
#[serde(default)]
|
||||
subject: Vec<String>,
|
||||
#[serde(rename = "number_of_pages_median", default)]
|
||||
pages: Option<u32>,
|
||||
}
|
||||
|
||||
/// How many of a work's subject headings are worth carrying.
|
||||
@@ -309,10 +316,15 @@ struct SearchDoc {
|
||||
/// The index lists every heading every edition has ever been given, which on a
|
||||
/// well-known book is hundreds and on Hamlet is thousands. A shelf is filed
|
||||
/// from a handful, and the first are the broadest.
|
||||
const SUBJECT_LIMIT: usize = 12;
|
||||
pub(crate) const SUBJECT_LIMIT: usize = 12;
|
||||
|
||||
/// A search that matched nothing answers with no documents rather than a
|
||||
/// status, so an empty reply is the absence and not a failure.
|
||||
///
|
||||
/// The record says what is true of the work and nothing that belongs to one
|
||||
/// edition: no publisher, language, year or page count. Those come from the
|
||||
/// edition record, which [`crate::ask::lookup`] asks next because a record
|
||||
/// without them is never complete.
|
||||
fn open_library_search(id: &str, kind: &str, body: &str) -> Result<Record, Error> {
|
||||
let reply: SearchReply = serde_json::from_str(body).map_err(|e| Error::Shape(e.to_string()))?;
|
||||
let Some(doc) = reply.docs.into_iter().next() else {
|
||||
@@ -325,31 +337,30 @@ fn open_library_search(id: &str, kind: &str, body: &str) -> Result<Record, Error
|
||||
(title, _) => title,
|
||||
};
|
||||
record.authors = doc.author_name;
|
||||
record.year = doc.first_publish_year;
|
||||
record.container = doc.publisher.into_iter().next();
|
||||
record.language = doc.language.into_iter().next();
|
||||
// The index lists every subject any edition of the work carries, which
|
||||
// runs to hundreds on a well-known book. A shelf needs a handful.
|
||||
record.subjects = doc.subject;
|
||||
record.subjects.truncate(SUBJECT_LIMIT);
|
||||
record.pages = doc.pages;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GoogleReply {
|
||||
pub(crate) struct GoogleReply {
|
||||
#[serde(default)]
|
||||
items: Vec<GoogleItem>,
|
||||
pub(crate) items: Vec<GoogleItem>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GoogleItem {
|
||||
pub(crate) struct GoogleItem {
|
||||
/// Google's own key for the volume.
|
||||
#[serde(default)]
|
||||
pub(crate) id: Option<String>,
|
||||
#[serde(rename = "volumeInfo", default)]
|
||||
volume_info: GoogleVolume,
|
||||
pub(crate) volume_info: GoogleVolume,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct GoogleVolume {
|
||||
pub(crate) struct GoogleVolume {
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -368,6 +379,18 @@ struct GoogleVolume {
|
||||
language: Option<String>,
|
||||
#[serde(rename = "pageCount", default)]
|
||||
page_count: Option<u32>,
|
||||
/// `[{"type": "ISBN_13", "identifier": "…"}]`, alongside library
|
||||
/// shelfmarks typed `OTHER`.
|
||||
#[serde(rename = "industryIdentifiers", default)]
|
||||
pub(crate) identifiers: Vec<GoogleIdentifier>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct GoogleIdentifier {
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: String,
|
||||
#[serde(default)]
|
||||
pub(crate) identifier: String,
|
||||
}
|
||||
|
||||
/// A search that matched nothing answers with no items rather than a status,
|
||||
@@ -377,8 +400,11 @@ fn google_books(id: &str, kind: &str, body: &str) -> Result<Record, Error> {
|
||||
let Some(item) = reply.items.into_iter().next() else {
|
||||
return Ok(crate::missing(id, kind, Source::GoogleBooks));
|
||||
};
|
||||
let volume = item.volume_info;
|
||||
Ok(google_volume(id, kind, item.volume_info))
|
||||
}
|
||||
|
||||
/// One Google Books volume as a record.
|
||||
pub(crate) fn google_volume(id: &str, kind: &str, volume: GoogleVolume) -> Record {
|
||||
let mut record = blank(id, kind, Source::GoogleBooks);
|
||||
record.title = match (volume.title, volume.subtitle) {
|
||||
(Some(title), Some(subtitle)) => Some(format!("{title}: {subtitle}")),
|
||||
@@ -391,11 +417,11 @@ fn google_books(id: &str, kind: &str, body: &str) -> Result<Record, Error> {
|
||||
record.subjects = volume.categories;
|
||||
record.language = volume.language;
|
||||
record.pages = volume.page_count;
|
||||
Ok(record)
|
||||
record
|
||||
}
|
||||
|
||||
/// The first four-digit year in a string.
|
||||
fn year_in(text: &str) -> Option<i64> {
|
||||
pub(crate) fn year_in(text: &str) -> Option<i64> {
|
||||
let bytes: Vec<char> = text.chars().collect();
|
||||
for window in bytes.windows(4) {
|
||||
if window.iter().all(char::is_ascii_digit) {
|
||||
@@ -446,9 +472,8 @@ mod tests {
|
||||
fn each_kind_goes_to_the_body_that_assigns_it() {
|
||||
assert_eq!(Source::for_kind("doi"), Some(Source::Crossref));
|
||||
assert_eq!(Source::for_kind("arxiv"), Some(Source::Arxiv));
|
||||
// The index, not the edition record: it answers with the whole of
|
||||
// what a catalogue wants in one request, where the edition record
|
||||
// takes up to twenty-eight seconds and names its authors by key.
|
||||
// The index first, for the authors by name; the edition record names
|
||||
// them by key, and is asked next for what only the edition knows.
|
||||
assert_eq!(Source::for_kind("isbn"), Some(Source::OpenLibrarySearch));
|
||||
// No register answers about an ISSN without a key.
|
||||
assert_eq!(Source::for_kind("issn"), None);
|
||||
@@ -520,6 +545,146 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cover_id_a_record_names_is_kept_for_the_cover_lookup() {
|
||||
// A deleted cover stays in an edition's list as -1, ahead of the
|
||||
// ones still there.
|
||||
let record = open_library("1", "isbn", r#"{"title":"A","covers":[-1,1162784,99]}"#)
|
||||
.expect("a record");
|
||||
assert_eq!(record.cover_id, Some(1162784));
|
||||
let record = open_library("1", "isbn", r#"{"title":"A"}"#).expect("a record");
|
||||
assert_eq!(record.cover_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cover_id_is_the_editions_and_not_the_works() {
|
||||
// ISBN 9780140447934 today: the index (asked first) names the work's
|
||||
// cover; the edition record has none. Merged as `ask::lookup` merges.
|
||||
let mut kept = open_library_search(
|
||||
"9780140447934",
|
||||
"isbn",
|
||||
r#"{"docs":[{"title":"War and Peace","cover_i":12621906}]}"#,
|
||||
)
|
||||
.expect("a record");
|
||||
let edition = open_library("9780140447934", "isbn", r#"{"title":"War and Peace"}"#)
|
||||
.expect("a record");
|
||||
kept.fill_from(edition);
|
||||
// Cover 12621906 is OL34941467M, Standard Ebooks' Maude translation.
|
||||
assert_eq!(kept.cover_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edition_with_no_covers_gives_no_cover_id() {
|
||||
let index = r#"{"docs":[{"title":"War and Peace","cover_i":12621906}]}"#;
|
||||
// `lookup` often stops at the index, before the edition is asked.
|
||||
let alone = open_library_search("9780140447934", "isbn", index).expect("a record");
|
||||
assert_eq!(alone.cover_id, None);
|
||||
// An edition whose only cover was deleted, and one with an empty list.
|
||||
for edition in [
|
||||
r#"{"title":"War and Peace","covers":[-1]}"#,
|
||||
r#"{"title":"War and Peace","covers":[]}"#,
|
||||
] {
|
||||
let mut kept = open_library_search("9780140447934", "isbn", index).expect("a record");
|
||||
kept.fill_from(open_library("9780140447934", "isbn", edition).expect("a record"));
|
||||
assert_eq!(kept.cover_id, None, "{edition}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_is_not_asked_for_the_works_cover() {
|
||||
assert!(!Source::OpenLibrarySearch.url("1").contains("cover_i"));
|
||||
}
|
||||
|
||||
/// What the index said for ISBN 9780140447934, the Penguin Classics *War
|
||||
/// and Peace*, on 2026-11-13, asked for the fields the lookup asked for
|
||||
/// before #6: the publishers, languages and first year of every edition
|
||||
/// of the work.
|
||||
const WAR_AND_PEACE_INDEX: &str = r#"{"docs":[{"title":"War and Peace",
|
||||
"author_name":["Leo Tolstoy"],"first_publish_year":1845,
|
||||
"publisher":["W.W. Norton","IndyPublish.com","Canterbury Classics"],
|
||||
"language":["spa","gre","dut","eng"],"subject":["Fiction"],
|
||||
"number_of_pages_median":1296}]}"#;
|
||||
|
||||
/// The edition record for the same ISBN, `/isbn/9780140447934.json`, with
|
||||
/// the English language its `languages` field should name.
|
||||
const WAR_AND_PEACE_EDITION: &str = r#"{"title":"War and Peace (Penguin Classics)",
|
||||
"publishers":["Penguin Books"],"publish_date":"September 27, 2007",
|
||||
"languages":[{"key":"/languages/eng"}],"number_of_pages":1440}"#;
|
||||
|
||||
/// Index first, then the edition record, merged as `ask::lookup` merges.
|
||||
fn looked_up(edition: &str) -> Record {
|
||||
let mut kept =
|
||||
open_library_search("9780140447934", "isbn", WAR_AND_PEACE_INDEX).expect("a record");
|
||||
kept.fill_from(open_library("9780140447934", "isbn", edition).expect("a record"));
|
||||
kept
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_says_nothing_only_an_edition_can() {
|
||||
let record =
|
||||
open_library_search("9780140447934", "isbn", WAR_AND_PEACE_INDEX).expect("a record");
|
||||
// What is true of the work is kept.
|
||||
assert_eq!(record.title.as_deref(), Some("War and Peace"));
|
||||
assert_eq!(record.authors, ["Leo Tolstoy"]);
|
||||
// What belongs to one edition is not taken from all of them.
|
||||
assert_eq!(record.language, None);
|
||||
assert_eq!(record.container, None);
|
||||
assert_eq!(record.year, None);
|
||||
assert_eq!(record.pages, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_by_isbn_gives_the_editions_language_publisher_and_year() {
|
||||
let record = looked_up(WAR_AND_PEACE_EDITION);
|
||||
assert_eq!(record.language.as_deref(), Some("eng"));
|
||||
assert_eq!(record.container.as_deref(), Some("Penguin Books"));
|
||||
assert_eq!(record.year, Some(2007));
|
||||
assert_eq!(record.pages, Some(1440));
|
||||
assert_eq!(record.authors, ["Leo Tolstoy"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_edition_does_not_say_is_missing_rather_than_the_works() {
|
||||
// The real edition record today names no language at all.
|
||||
let record = looked_up(
|
||||
r#"{"title":"War and Peace (Penguin Classics)","publishers":["Penguin Books"],
|
||||
"publish_date":"September 27, 2007","number_of_pages":1440}"#,
|
||||
);
|
||||
assert_eq!(record.language, None);
|
||||
assert_eq!(record.container.as_deref(), Some("Penguin Books"));
|
||||
assert_eq!(record.year, Some(2007));
|
||||
// Nor a date: the work's first year is not this edition's.
|
||||
let record = looked_up(r#"{"title":"War and Peace (Penguin Classics)"}"#);
|
||||
assert_eq!(record.year, None);
|
||||
assert_eq!(record.container, None);
|
||||
assert_eq!(record.pages, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_alone_never_ends_a_lookup() {
|
||||
// `lookup` stops at the first complete record; the index must not be
|
||||
// one, or the edition record is never asked.
|
||||
let record =
|
||||
open_library_search("9780140447934", "isbn", WAR_AND_PEACE_INDEX).expect("a record");
|
||||
assert!(!record.complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_is_not_asked_for_what_its_editions_differ_in() {
|
||||
let url = Source::OpenLibrarySearch.url("9780140447934");
|
||||
for field in [
|
||||
"publisher",
|
||||
"language",
|
||||
"first_publish_year",
|
||||
"number_of_pages_median",
|
||||
] {
|
||||
assert!(
|
||||
!url.split(['=', ',', '&']).any(|f| f == field),
|
||||
"{field} in {url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_that_is_not_what_it_should_be_says_so() {
|
||||
assert!(matches!(
|
||||
|
||||
@@ -21,6 +21,8 @@ from ._catena import (
|
||||
compose_subjects,
|
||||
count_tokens,
|
||||
cue_windows,
|
||||
Limited,
|
||||
fetch_cover,
|
||||
fetch_identifier,
|
||||
find_citations,
|
||||
fuse_hits,
|
||||
@@ -41,6 +43,7 @@ from ._catena import (
|
||||
record_severity,
|
||||
same_work,
|
||||
scrub,
|
||||
search_title,
|
||||
segment_cues,
|
||||
series_of,
|
||||
shelve,
|
||||
@@ -53,6 +56,7 @@ from ._catena import (
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"Limited",
|
||||
"canonical_subject",
|
||||
"chunk_markdown",
|
||||
"citation_prompt",
|
||||
@@ -62,6 +66,7 @@ __all__ = [
|
||||
"compose_subjects",
|
||||
"count_tokens",
|
||||
"cue_windows",
|
||||
"fetch_cover",
|
||||
"fetch_identifier",
|
||||
"find_citations",
|
||||
"fuse_hits",
|
||||
@@ -82,6 +87,7 @@ __all__ = [
|
||||
"record_severity",
|
||||
"same_work",
|
||||
"scrub",
|
||||
"search_title",
|
||||
"segment_cues",
|
||||
"series_of",
|
||||
"shelve",
|
||||
|
||||
@@ -103,6 +103,40 @@ def fetch_identifier(
|
||||
"""
|
||||
...
|
||||
|
||||
class Limited(Exception):
|
||||
"""A register refused because it has been asked too often; ask again later."""
|
||||
|
||||
def fetch_cover(
|
||||
isbn: str,
|
||||
cover_id: int | None = ...,
|
||||
size: str = ...,
|
||||
polite: str | None = ...,
|
||||
timeout: int = ...,
|
||||
deadline: int = ...,
|
||||
) -> dict[str, Any] | None:
|
||||
"""The cover Open Library has for a book, by ISBN, then by cover id.
|
||||
|
||||
A dict with `bytes`, `media_type`, `extension`, `source` and `url`, or
|
||||
`None` when there is none. Raises `Limited` when Open Library refused for
|
||||
being asked too often. Blocks on the network.
|
||||
"""
|
||||
...
|
||||
|
||||
def search_title(
|
||||
title: str,
|
||||
author: str | None = ...,
|
||||
limit: int = ...,
|
||||
polite: str | None = ...,
|
||||
timeout: int = ...,
|
||||
attempts: int = ...,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""The editions the registers list for a title and author, in their order.
|
||||
|
||||
Records shaped like `fetch_identifier`'s. Use `same_work` to decide which
|
||||
one is the book. Blocks on the network.
|
||||
"""
|
||||
...
|
||||
|
||||
def colophon_prompt(
|
||||
record: dict[str, Any], text: str, pages: int = ...
|
||||
) -> str | None:
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
use pyo3::exceptions::PyValueError;
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::{PyDict, PyList};
|
||||
use pyo3::types::{PyBytes, PyDict, PyList};
|
||||
|
||||
use crate::{ChunkBudgets, CueBudgets};
|
||||
|
||||
@@ -434,6 +434,9 @@ fn _catena(module: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
module.add_function(wrap_pyfunction!(read_colophon, module)?)?;
|
||||
module.add_function(wrap_pyfunction!(shelve, module)?)?;
|
||||
module.add_function(wrap_pyfunction!(fetch_identifier, module)?)?;
|
||||
module.add_function(wrap_pyfunction!(fetch_cover, module)?)?;
|
||||
module.add_function(wrap_pyfunction!(search_title, module)?)?;
|
||||
module.add("Limited", module.py().get_type::<Limited>())?;
|
||||
module.add_function(wrap_pyfunction!(colophon_prompt, module)?)?;
|
||||
module.add_function(wrap_pyfunction!(merge_colophon, module)?)?;
|
||||
Ok(())
|
||||
@@ -512,13 +515,112 @@ fn fetch_identifier<'py>(
|
||||
// would stop every other thread in the interpreter for the whole request.
|
||||
let found = py
|
||||
.detach(|| bibfetch::ask::lookup(&agent, id, kind, ask.attempts))
|
||||
.map_err(|e| PyValueError::new_err(e.to_string()))?;
|
||||
.map_err(register_error)?;
|
||||
match found {
|
||||
Some(record) => Ok(Some(to_py(py, &record)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pyo3::create_exception!(
|
||||
_catena,
|
||||
Limited,
|
||||
pyo3::exceptions::PyException,
|
||||
"A register refused because it has been asked too often; ask again later."
|
||||
);
|
||||
|
||||
/// A register's error as the Python exception that says what to do about it.
|
||||
fn register_error(error: bibfetch::Error) -> PyErr {
|
||||
match error {
|
||||
bibfetch::Error::Limited(why) => Limited::new_err(why),
|
||||
other => PyValueError::new_err(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cover Open Library has for a book, by its ISBN, then by the cover id
|
||||
/// a record named.
|
||||
///
|
||||
/// Returns a dict with `bytes`, `media_type` (`image/jpeg` or `image/png`),
|
||||
/// `extension`, `source` and `url`, or `None` when there is no cover. Covers
|
||||
/// asked by ISBN are kept three seconds apart across the process, and the
|
||||
/// whole fetch stops after `deadline` seconds. Raises `catena.Limited` when
|
||||
/// Open Library refused for being asked too often, and `ValueError` when the
|
||||
/// ISBN is not one or the store could not be reached. Blocks on the network.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (isbn, cover_id = None, size = "large", polite = None, timeout = 20, deadline = 120))]
|
||||
fn fetch_cover<'py>(
|
||||
py: Python<'py>,
|
||||
isbn: &str,
|
||||
cover_id: Option<u64>,
|
||||
size: &str,
|
||||
polite: Option<String>,
|
||||
timeout: u64,
|
||||
deadline: u64,
|
||||
) -> PyResult<Option<Bound<'py, PyDict>>> {
|
||||
let size = match size {
|
||||
"small" => bibfetch::CoverSize::Small,
|
||||
"medium" => bibfetch::CoverSize::Medium,
|
||||
"large" => bibfetch::CoverSize::Large,
|
||||
other => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"size is small, medium or large, not {other:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let agent = bibfetch::ask::Ask {
|
||||
polite,
|
||||
timeout: std::time::Duration::from_secs(timeout.max(1)),
|
||||
..Default::default()
|
||||
}
|
||||
.agent();
|
||||
let covers = bibfetch::cover::Covers {
|
||||
deadline: std::time::Duration::from_secs(deadline.max(1)),
|
||||
..Default::default()
|
||||
};
|
||||
let found = py
|
||||
.detach(|| covers.fetch(&agent, isbn, cover_id, size))
|
||||
.map_err(register_error)?;
|
||||
let Some(cover) = found else {
|
||||
return Ok(None);
|
||||
};
|
||||
let out = PyDict::new(py);
|
||||
out.set_item("bytes", PyBytes::new(py, &cover.bytes))?;
|
||||
out.set_item("media_type", cover.media_type)?;
|
||||
out.set_item("extension", cover.extension())?;
|
||||
out.set_item("source", cover.source)?;
|
||||
out.set_item("url", cover.url)?;
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// The editions the registers list for a title, and an author if one is known.
|
||||
///
|
||||
/// Open Library is asked first and Google Books only when it has nothing.
|
||||
/// The candidates come back in the register's own order, as records shaped
|
||||
/// like `fetch_identifier`'s; nothing here decides which is the book, which is
|
||||
/// what `same_work` is for. Blocks on the network.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (title, author = None, limit = 10, polite = None, timeout = 20, attempts = 3))]
|
||||
fn search_title<'py>(
|
||||
py: Python<'py>,
|
||||
title: &str,
|
||||
author: Option<&str>,
|
||||
limit: usize,
|
||||
polite: Option<String>,
|
||||
timeout: u64,
|
||||
attempts: u32,
|
||||
) -> PyResult<Bound<'py, PyList>> {
|
||||
let ask = bibfetch::ask::Ask {
|
||||
polite,
|
||||
timeout: std::time::Duration::from_secs(timeout.max(1)),
|
||||
attempts: attempts.max(1),
|
||||
};
|
||||
let agent = ask.agent();
|
||||
let found = py
|
||||
.detach(|| bibfetch::search(&agent, title, author, limit, ask.attempts))
|
||||
.map_err(register_error)?;
|
||||
list_to_py(py, &found)
|
||||
}
|
||||
|
||||
/// The question to put to a model about the fields a book's pages did not
|
||||
/// settle, or `None` when they settled everything.
|
||||
///
|
||||
|
||||
@@ -84,6 +84,7 @@ bookmeta library/*.epub \
|
||||
|---|---|
|
||||
| EPUB | The package document named by `META-INF/container.xml` — Dublin Core, plus the `<meta>` entries Calibre adds for a series |
|
||||
| PDF | The trailer's information dictionary |
|
||||
| MOBI, AZW, AZW3 | The MOBI header in the first record, and the EXTH records after it |
|
||||
|
||||
An EPUB whose container is malformed falls back to the first `.opf` in the
|
||||
archive, because a converter that wrote a bad container often still wrote a
|
||||
@@ -94,6 +95,75 @@ both become `isbn`, a UUID becomes `uuid`, anything else `other`. PDF dates
|
||||
are reduced to the day where they parse and kept verbatim where they do not,
|
||||
because a date nobody can read is still evidence.
|
||||
|
||||
A Kindle book's title is EXTH 503 where it is there, then the MOBI header's
|
||||
full name, then the Palm database name (cut to 31 bytes, with a note). Authors
|
||||
(100) and subjects (105) are every record of their kind, in order; publisher
|
||||
(101), description (103), date (106) and language (524) the first. EXTH 104 is
|
||||
an `isbn` when it is shaped like one and `other` when not. 113 is filed by
|
||||
its shape: a `uuid` when it is one (calibre writes its book id there), an
|
||||
`asin` when it is ten letters and digits, and `other` when it is neither. A
|
||||
contributor (108) is not an author, the same as an EPUB's
|
||||
`dc:contributor`, and is not reported. With no EXTH language, the language
|
||||
comes from the header's locale. Strings are decoded as the header says,
|
||||
UTF-8 or Windows-1252. A book whose text is encrypted still has its header
|
||||
read, and carries the note `drm`.
|
||||
|
||||
Every offset in a Kindle book is checked before it is followed: headers that
|
||||
are cut short or point outside the file give an empty record with a note, and
|
||||
an EXTH block that breaks off keeps the records before the break.
|
||||
|
||||
## Covers
|
||||
|
||||
`Metadata::cover` is the cover image the file carries, with its media type
|
||||
read off its first bytes: JPEG, PNG, GIF, WebP or BMP. It is for library
|
||||
callers and is not part of the JSON record, which is a line of text.
|
||||
|
||||
A Kindle book's cover is EXTH 201, or the thumbnail, 202, when no cover is
|
||||
named. With neither, it is the record at the header's first image index, as
|
||||
calibre does, and only that record: when it is not a JPEG, PNG or GIF there is
|
||||
no cover, because the records after it can be illustrations, and kindlegen
|
||||
sometimes puts a font there first.
|
||||
|
||||
An EPUB's is the first of these that reaches an image:
|
||||
|
||||
1. The manifest item whose `properties` include `cover-image` (EPUB 3).
|
||||
2. The item `<meta name="cover" content="…">` names (EPUB 2). Some
|
||||
converters write the image's address there rather than its id, and that is
|
||||
followed too.
|
||||
3. The guide's `<reference type="cover">`, a page, and the `<img src>` or
|
||||
SVG `<image href>` on it. Where the page has several, the one whose file
|
||||
name, `alt`, `id` or `class` says `cover` is taken; where none does, the
|
||||
first is, with a note that there were others. A guide that points straight
|
||||
at an image is taken at its word.
|
||||
4. Any image in the manifest whose id or file name says `cover`, one named
|
||||
`cover` outright first and the rest in manifest order.
|
||||
|
||||
A name says `cover` when it has it as a word of its own, in any case. Words
|
||||
break at anything not a letter or digit and where a lower case letter meets a
|
||||
capital, so `CoverImage`, `Book_COVER` and `cover-thumb` say it, and
|
||||
`discover-ch1` and `recovery-map` do not.
|
||||
|
||||
A route that names something unusable — not in the archive, not an image —
|
||||
leaves a note, and the next route is asked. Addresses are resolved against the
|
||||
document they are written in, with their fragment off and their
|
||||
percent-escapes undone, and one that climbs out of the archive or names a
|
||||
scheme (`http:`, `data:`) is not followed.
|
||||
|
||||
What the bytes say beats what the manifest says: a JPEG listed as
|
||||
`image/png` comes back as `image/jpeg`, with a note. A cover larger than
|
||||
`bookmeta::MAX_COVER` (16 MiB) is left out with a note, in either format, and
|
||||
an EPUB's is never decompressed further than that, whatever size the archive
|
||||
claims for it. Nor are more than eight members read looking for one,
|
||||
however many candidates the manifest lists: the search stops there, with a
|
||||
note.
|
||||
|
||||
`Cover::guessed` says the file left the choice open: a Kindle book's first
|
||||
image record, or an EPUB image picked because its name says `cover`. Either
|
||||
can be an illustration from inside the book, so a caller that can get a cover
|
||||
another way, from a register by ISBN, should prefer that one. A cover the file
|
||||
names is never a guess. `Cover::extension` gives the usual file extension for
|
||||
its media type.
|
||||
|
||||
## Asking a model
|
||||
|
||||
Some files say nothing useful. `--prompt` writes the question and **sends
|
||||
@@ -147,7 +217,7 @@ if let Some(prompt) = bookmeta::prompt::compose(&meta, Some(opening)) {
|
||||
}
|
||||
```
|
||||
|
||||
`bookmeta::epub` and `bookmeta::pdf` read one format each, and
|
||||
`bookmeta::epub`, `bookmeta::pdf` and `bookmeta::mobi` read one format each, and
|
||||
`Metadata::missing` says which fields a record still wants.
|
||||
|
||||
## See also
|
||||
|
||||
+1007
-4
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,7 @@
|
||||
//! [`bibfetch`]: https://git.pumpin.online/funkpower/catena
|
||||
|
||||
pub mod epub;
|
||||
pub mod mobi;
|
||||
pub mod pdf;
|
||||
pub mod prompt;
|
||||
|
||||
@@ -30,6 +31,8 @@ pub enum Source {
|
||||
Opf,
|
||||
/// A PDF's information dictionary.
|
||||
PdfInfo,
|
||||
/// A Kindle book's MOBI header and the EXTH records after it.
|
||||
Mobi,
|
||||
/// Nothing was found to read.
|
||||
None,
|
||||
}
|
||||
@@ -40,6 +43,7 @@ impl Source {
|
||||
match self {
|
||||
Source::Opf => "opf",
|
||||
Source::PdfInfo => "pdf_info",
|
||||
Source::Mobi => "mobi",
|
||||
Source::None => "none",
|
||||
}
|
||||
}
|
||||
@@ -64,6 +68,9 @@ pub struct Metadata {
|
||||
/// Who published it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub publisher: Option<String>,
|
||||
/// The publisher's description of the book, as written: often HTML.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
/// The publication date, in whatever form the file wrote it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date: Option<String>,
|
||||
@@ -86,6 +93,76 @@ pub struct Metadata {
|
||||
/// What was worth saying about the reading.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub notes: Vec<String>,
|
||||
/// The cover image the file carries.
|
||||
///
|
||||
/// Not part of the record: a record is a line of text and this is an
|
||||
/// image. A library caller takes it from here.
|
||||
#[serde(skip)]
|
||||
#[schemars(skip)]
|
||||
pub cover: Option<Cover>,
|
||||
}
|
||||
|
||||
/// A cover image, as the file stores it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Cover {
|
||||
/// What kind of image it is, read off its first bytes: `image/jpeg`,
|
||||
/// `image/png`, `image/gif`, `image/webp` or `image/bmp`.
|
||||
pub media_type: String,
|
||||
/// The image itself, never more than [`MAX_COVER`] bytes.
|
||||
pub bytes: Vec<u8>,
|
||||
/// Whether the file left the choice open. A MOBI that names no cover, or
|
||||
/// an EPUB whose only cover is an image with "cover" in its name, has one
|
||||
/// picked by position or by name, and that pick can be an illustration
|
||||
/// from inside the book. A caller with a better source should prefer it.
|
||||
pub guessed: bool,
|
||||
}
|
||||
|
||||
impl Cover {
|
||||
/// The usual file extension for the image, without the dot.
|
||||
pub fn extension(&self) -> &'static str {
|
||||
match self.media_type.as_str() {
|
||||
"image/png" => "png",
|
||||
"image/gif" => "gif",
|
||||
"image/webp" => "webp",
|
||||
"image/bmp" => "bmp",
|
||||
_ => "jpg",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How large a cover is worth keeping.
|
||||
///
|
||||
/// A real one is a few hundred kilobytes. An EPUB's cover has to be
|
||||
/// decompressed to be read, and this is as far as that goes: a larger one is
|
||||
/// left out with a note, in every format, so a hostile file cannot make a
|
||||
/// reader allocate whatever it likes.
|
||||
pub const MAX_COVER: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// A size, as a note says it.
|
||||
pub(crate) fn size(bytes: usize) -> String {
|
||||
const MIB: usize = 1024 * 1024;
|
||||
if bytes >= MIB && bytes % MIB == 0 {
|
||||
format!("{} MiB", bytes / MIB)
|
||||
} else {
|
||||
format!("{bytes} bytes")
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of image these bytes are, by their magic.
|
||||
pub(crate) fn image_type(data: &[u8]) -> Option<&'static str> {
|
||||
if data.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||
Some("image/jpeg")
|
||||
} else if data.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
Some("image/png")
|
||||
} else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
|
||||
Some("image/gif")
|
||||
} else if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP") {
|
||||
Some("image/webp")
|
||||
} else if data.starts_with(b"BM") && data.len() > 14 {
|
||||
Some("image/bmp")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn version() -> u32 {
|
||||
@@ -143,6 +220,7 @@ impl Metadata {
|
||||
self.title.is_none()
|
||||
&& self.authors.is_empty()
|
||||
&& self.publisher.is_none()
|
||||
&& self.description.is_none()
|
||||
&& self.date.is_none()
|
||||
&& self.language.is_none()
|
||||
&& self.identifiers.is_empty()
|
||||
@@ -171,6 +249,9 @@ pub fn from_bytes(path: &str, bytes: &[u8]) -> Metadata {
|
||||
if bytes.starts_with(b"%PDF") {
|
||||
return pdf::read(path, bytes);
|
||||
}
|
||||
if mobi::is_mobi(bytes) {
|
||||
return mobi::read(path, bytes);
|
||||
}
|
||||
let mut meta = Metadata::empty(path, Source::None);
|
||||
meta.note("not a format this reads metadata out of");
|
||||
meta
|
||||
|
||||
@@ -0,0 +1,870 @@
|
||||
//! A Kindle book's MOBI header and the EXTH records after it.
|
||||
//!
|
||||
//! MOBI, AZW and AZW3 files are Palm databases. The first record opens with a
|
||||
//! PalmDOC header and a MOBI header, which gives the book's full name and says
|
||||
//! how its strings are encoded. When a flag in that header is set, an EXTH
|
||||
//! block follows with everything else: authors, publisher, ISBN, subjects, and
|
||||
//! which image record is the cover. AZW3 (KF8) keeps the same layout in its
|
||||
//! first record, so one reader covers all three.
|
||||
//!
|
||||
//! Every offset in the file is checked before it is followed. A file whose
|
||||
//! headers are cut short or written wrongly gives an empty record with a note;
|
||||
//! an EXTH block that breaks off keeps the records before the break. Neither
|
||||
//! panics or reads past the end.
|
||||
|
||||
use crate::epub::{digits_of, is_isbn, is_uuid};
|
||||
use crate::{Cover, MAX_COVER, Metadata, Source, image_type};
|
||||
|
||||
/// Where a Palm database says what it holds.
|
||||
const TYPE_AT: usize = 60;
|
||||
/// What a Kindle book says there.
|
||||
const BOOK_TYPE: &[u8] = b"BOOKMOBI";
|
||||
/// The Palm database's own name: 32 bytes, NUL-padded.
|
||||
const NAME_LEN: usize = 32;
|
||||
/// Where the number of records is written.
|
||||
const RECORD_COUNT_AT: usize = 76;
|
||||
/// Where the record list starts: eight bytes per record, offset first.
|
||||
const RECORD_LIST_AT: usize = 78;
|
||||
|
||||
/// Where the PalmDOC header says whether the text is encrypted.
|
||||
const ENCRYPTION_AT: usize = 12;
|
||||
/// Where the MOBI header begins inside the first record.
|
||||
const MOBI_AT: usize = 16;
|
||||
/// The MOBI header's own magic.
|
||||
const MOBI_MAGIC: &[u8] = b"MOBI";
|
||||
|
||||
// Fields of the MOBI header, as offsets from its start. Each is only there
|
||||
// when the header's declared length reaches past it.
|
||||
const HEADER_LENGTH: usize = 4;
|
||||
const TEXT_ENCODING: usize = 12;
|
||||
const FULL_NAME_OFFSET: usize = 68;
|
||||
const FULL_NAME_LENGTH: usize = 72;
|
||||
const LOCALE: usize = 76;
|
||||
const FIRST_IMAGE: usize = 92;
|
||||
const EXTH_FLAGS: usize = 112;
|
||||
|
||||
/// The flag that says an EXTH block follows the MOBI header.
|
||||
const HAS_EXTH: u32 = 0x40;
|
||||
/// The EXTH block's magic.
|
||||
const EXTH_MAGIC: &[u8] = b"EXTH";
|
||||
|
||||
/// The text encodings a MOBI header names.
|
||||
const UTF_8: u32 = 65001;
|
||||
const WINDOWS_1252: u32 = 1252;
|
||||
|
||||
/// What an index or offset says when it points at nothing.
|
||||
const NONE: u32 = 0xffff_ffff;
|
||||
|
||||
// EXTH record types.
|
||||
const AUTHOR: u32 = 100;
|
||||
const PUBLISHER: u32 = 101;
|
||||
const DESCRIPTION: u32 = 103;
|
||||
const ISBN: u32 = 104;
|
||||
const SUBJECT: u32 = 105;
|
||||
const PUBLISHED: u32 = 106;
|
||||
const ASIN: u32 = 113;
|
||||
const COVER_OFFSET: u32 = 201;
|
||||
const THUMB_OFFSET: u32 = 202;
|
||||
const UPDATED_TITLE: u32 = 503;
|
||||
const LANGUAGE: u32 = 524;
|
||||
|
||||
/// Whether these bytes are a Kindle book this module can read.
|
||||
pub fn is_mobi(bytes: &[u8]) -> bool {
|
||||
bytes.get(TYPE_AT..TYPE_AT + BOOK_TYPE.len()) == Some(BOOK_TYPE)
|
||||
}
|
||||
|
||||
/// Read what a MOBI, AZW or AZW3 file says about itself.
|
||||
pub fn read(path: &str, bytes: &[u8]) -> Metadata {
|
||||
let mut meta = Metadata::empty(path, Source::Mobi);
|
||||
if let Err(why) = fill(&mut meta, bytes) {
|
||||
let mut empty = Metadata::empty(path, Source::None);
|
||||
empty.note(why);
|
||||
return empty;
|
||||
}
|
||||
if meta.is_empty() {
|
||||
meta.note("a MOBI header with nothing filled in");
|
||||
}
|
||||
meta
|
||||
}
|
||||
|
||||
/// The strings an EXTH block carries, before they are placed in a record.
|
||||
#[derive(Default)]
|
||||
struct Exth {
|
||||
authors: Vec<String>,
|
||||
publisher: Option<String>,
|
||||
description: Option<String>,
|
||||
isbn: Option<String>,
|
||||
subjects: Vec<String>,
|
||||
published: Option<String>,
|
||||
asin: Option<String>,
|
||||
cover: Option<u32>,
|
||||
thumb: Option<u32>,
|
||||
title: Option<String>,
|
||||
language: Option<String>,
|
||||
}
|
||||
|
||||
fn fill(meta: &mut Metadata, bytes: &[u8]) -> Result<(), String> {
|
||||
if !is_mobi(bytes) {
|
||||
return Err("not a Kindle book: the Palm database type is not BOOKMOBI".into());
|
||||
}
|
||||
let records = records(bytes)?;
|
||||
let first = record(bytes, &records, 0).ok_or("the first record lies outside the file")?;
|
||||
|
||||
if first.get(MOBI_AT..MOBI_AT + MOBI_MAGIC.len()) != Some(MOBI_MAGIC) {
|
||||
return Err("no MOBI header in the first record".into());
|
||||
}
|
||||
let header_length =
|
||||
u32_at(first, MOBI_AT + HEADER_LENGTH).ok_or("the MOBI header is cut short")? as usize;
|
||||
let header = Header {
|
||||
record: first,
|
||||
length: header_length,
|
||||
};
|
||||
|
||||
let encoding = header.field(TEXT_ENCODING).unwrap_or(WINDOWS_1252);
|
||||
if encoding != UTF_8 && encoding != WINDOWS_1252 {
|
||||
meta.note(format!(
|
||||
"text encoding {encoding}, which is neither UTF-8 nor Windows-1252; read as Windows-1252"
|
||||
));
|
||||
}
|
||||
let decode = |raw: &[u8]| text(raw, encoding);
|
||||
|
||||
if u16_at(first, ENCRYPTION_AT).is_some_and(|kind| kind != 0) {
|
||||
meta.note("drm");
|
||||
}
|
||||
|
||||
let exth = if header
|
||||
.field(EXTH_FLAGS)
|
||||
.is_some_and(|flags| flags & HAS_EXTH != 0)
|
||||
{
|
||||
let at = MOBI_AT
|
||||
.checked_add(header_length)
|
||||
.ok_or("the MOBI header length is out of range")?;
|
||||
exth(first, at, &decode, meta)
|
||||
} else {
|
||||
Exth::default()
|
||||
};
|
||||
|
||||
let full_name = header
|
||||
.field(FULL_NAME_OFFSET)
|
||||
.zip(header.field(FULL_NAME_LENGTH))
|
||||
.and_then(|(at, len)| slice(first, at as usize, len as usize))
|
||||
.and_then(decode);
|
||||
meta.title = match (exth.title, full_name) {
|
||||
(Some(title), _) | (None, Some(title)) => Some(title),
|
||||
(None, None) => {
|
||||
let name = palm_name(bytes);
|
||||
if name.is_some() {
|
||||
meta.note("title from the Palm database name, which is cut to 31 bytes");
|
||||
}
|
||||
name
|
||||
}
|
||||
};
|
||||
|
||||
meta.authors = exth.authors;
|
||||
meta.publisher = exth.publisher;
|
||||
meta.description = exth.description;
|
||||
meta.date = exth.published;
|
||||
meta.subjects = exth.subjects;
|
||||
meta.language = exth.language.or_else(|| {
|
||||
header
|
||||
.field(LOCALE)
|
||||
.and_then(|locale| language_of(locale).map(str::to_string))
|
||||
});
|
||||
if let Some(isbn) = exth.isbn {
|
||||
if is_isbn(&isbn) {
|
||||
meta.identifiers.insert("isbn".into(), digits_of(&isbn));
|
||||
} else {
|
||||
meta.identifiers.insert("other".into(), isbn);
|
||||
}
|
||||
}
|
||||
// EXTH 113 holds an ASIN when the book was made for Amazon, and calibre's
|
||||
// own book UUID when it was converted without one.
|
||||
if let Some(value) = exth.asin {
|
||||
let lower = value.to_lowercase();
|
||||
if is_uuid(&lower) {
|
||||
meta.identifiers.insert("uuid".into(), lower);
|
||||
} else if is_asin(&value) {
|
||||
meta.identifiers.insert("asin".into(), value);
|
||||
} else {
|
||||
meta.identifiers.entry("other".into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
|
||||
let first_image = header.field(FIRST_IMAGE);
|
||||
if let Some(offset) = exth.cover.or(exth.thumb) {
|
||||
meta.cover = cover(bytes, &records, first_image, offset, meta);
|
||||
} else {
|
||||
meta.cover = first_image_record(bytes, &records, first_image);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The MOBI header, for reading fields that may or may not be in it.
|
||||
struct Header<'a> {
|
||||
record: &'a [u8],
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl Header<'_> {
|
||||
/// A field at `at` bytes into the header, when the header reaches it.
|
||||
fn field(&self, at: usize) -> Option<u32> {
|
||||
if at.checked_add(4)? > self.length {
|
||||
return None;
|
||||
}
|
||||
u32_at(self.record, MOBI_AT.checked_add(at)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each record starts, as the record list says.
|
||||
fn records(bytes: &[u8]) -> Result<Vec<usize>, String> {
|
||||
let count = u16_at(bytes, RECORD_COUNT_AT).ok_or("the Palm database header is cut short")?;
|
||||
if count == 0 {
|
||||
return Err("a Palm database with no records".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for at in 0..count as usize {
|
||||
let entry = RECORD_LIST_AT + at * 8;
|
||||
let Some(offset) = u32_at(bytes, entry) else {
|
||||
return Err("the record list runs past the end of the file".into());
|
||||
};
|
||||
out.push(offset as usize);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One record's bytes: from its offset to the next record's, or to the end.
|
||||
fn record<'a>(bytes: &'a [u8], records: &[usize], index: usize) -> Option<&'a [u8]> {
|
||||
let start = *records.get(index)?;
|
||||
let end = records.get(index + 1).copied().unwrap_or(bytes.len());
|
||||
bytes.get(start..end)
|
||||
}
|
||||
|
||||
/// Read the EXTH block at `at` inside the first record.
|
||||
///
|
||||
/// A block that ends early keeps what was read before the break, with a note:
|
||||
/// the records already read are as good as they would have been.
|
||||
fn exth(
|
||||
first: &[u8],
|
||||
at: usize,
|
||||
decode: &dyn Fn(&[u8]) -> Option<String>,
|
||||
meta: &mut Metadata,
|
||||
) -> Exth {
|
||||
let mut out = Exth::default();
|
||||
if at >= first.len() || first.get(at..at + EXTH_MAGIC.len()) != Some(EXTH_MAGIC) {
|
||||
meta.note("the header says an EXTH block follows, but none does");
|
||||
return out;
|
||||
}
|
||||
let (Some(length), Some(count)) = (u32_at(first, at + 4), u32_at(first, at + 8)) else {
|
||||
meta.note("the EXTH block ends early");
|
||||
return out;
|
||||
};
|
||||
let end = at.saturating_add(length as usize).min(first.len());
|
||||
|
||||
let mut cursor = at + 12;
|
||||
for _ in 0..count {
|
||||
let (Some(kind), Some(size)) = (u32_at(first, cursor), u32_at(first, cursor + 4)) else {
|
||||
meta.note("the EXTH block ends early");
|
||||
break;
|
||||
};
|
||||
let size = size as usize;
|
||||
let Some(data) = size
|
||||
.checked_sub(8)
|
||||
.and_then(|len| slice(first, cursor + 8, len))
|
||||
.filter(|_| cursor.checked_add(size).is_some_and(|stop| stop <= end))
|
||||
else {
|
||||
meta.note("the EXTH block ends early");
|
||||
break;
|
||||
};
|
||||
cursor += size;
|
||||
|
||||
match kind {
|
||||
AUTHOR => out.authors.extend(decode(data)),
|
||||
SUBJECT => out.subjects.extend(decode(data)),
|
||||
PUBLISHER => set(&mut out.publisher, decode(data)),
|
||||
DESCRIPTION => set(&mut out.description, decode(data)),
|
||||
ISBN => set(&mut out.isbn, decode(data)),
|
||||
PUBLISHED => set(&mut out.published, decode(data)),
|
||||
ASIN => set(&mut out.asin, decode(data)),
|
||||
UPDATED_TITLE => set(&mut out.title, decode(data)),
|
||||
LANGUAGE => set(&mut out.language, decode(data)),
|
||||
COVER_OFFSET => set(&mut out.cover, number(data)),
|
||||
THUMB_OFFSET => set(&mut out.thumb, number(data)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Keep the first value a field is given: a later duplicate is usually a
|
||||
/// converter writing the same thing twice, and the first is what it meant.
|
||||
fn set<T>(slot: &mut Option<T>, value: Option<T>) {
|
||||
if slot.is_none() {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// A four-byte number record that points somewhere.
|
||||
fn number(data: &[u8]) -> Option<u32> {
|
||||
let value = u32::from_be_bytes(data.try_into().ok()?);
|
||||
(value != NONE).then_some(value)
|
||||
}
|
||||
|
||||
/// The cover image, from the record the header and the EXTH offset name.
|
||||
fn cover(
|
||||
bytes: &[u8],
|
||||
records: &[usize],
|
||||
first_image: Option<u32>,
|
||||
offset: u32,
|
||||
meta: &mut Metadata,
|
||||
) -> Option<Cover> {
|
||||
let Some(first_image) = first_image.filter(|&index| index != NONE) else {
|
||||
meta.note("a cover is named, but the header has no image records");
|
||||
return None;
|
||||
};
|
||||
let Some(data) = first_image
|
||||
.checked_add(offset)
|
||||
.and_then(|index| record(bytes, records, index as usize))
|
||||
else {
|
||||
meta.note("the cover points past the last record");
|
||||
return None;
|
||||
};
|
||||
let Some(media_type) = image_type(data) else {
|
||||
meta.note("the cover record is not an image");
|
||||
return None;
|
||||
};
|
||||
if data.len() > MAX_COVER {
|
||||
meta.note(format!(
|
||||
"the cover record is larger than {}",
|
||||
crate::size(MAX_COVER)
|
||||
));
|
||||
return None;
|
||||
}
|
||||
Some(Cover {
|
||||
media_type: media_type.to_string(),
|
||||
bytes: data.to_vec(),
|
||||
guessed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The cover when the file names none: calibre takes the record at the first
|
||||
/// image index, and only that one.
|
||||
///
|
||||
/// When that record is not a JPEG, PNG or GIF there is no cover. The search
|
||||
/// does not walk on to the next image, because a later record may be an inline
|
||||
/// illustration, and kindlegen puts a font or a RESC record first.
|
||||
fn first_image_record(bytes: &[u8], records: &[usize], first_image: Option<u32>) -> Option<Cover> {
|
||||
let first = first_image.filter(|&index| index != NONE)?;
|
||||
let data = record(bytes, records, first as usize)?;
|
||||
if data.len() > MAX_COVER {
|
||||
return None;
|
||||
}
|
||||
let media_type = image_type(data).filter(|kind| *kind != "image/bmp")?;
|
||||
Some(Cover {
|
||||
media_type: media_type.to_string(),
|
||||
bytes: data.to_vec(),
|
||||
guessed: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// An ASIN is ten letters and digits; an ISBN-10 is one too.
|
||||
fn is_asin(value: &str) -> bool {
|
||||
value.len() == 10 && value.chars().all(|c| c.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
/// The Palm database's name, the last place a title can come from.
|
||||
///
|
||||
/// Converters write the title there with spaces made underscores; it is
|
||||
/// reported as written.
|
||||
fn palm_name(bytes: &[u8]) -> Option<String> {
|
||||
let raw = bytes.get(..NAME_LEN)?;
|
||||
let raw = raw.split(|&byte| byte == 0).next().unwrap_or(raw);
|
||||
text(raw, WINDOWS_1252)
|
||||
}
|
||||
|
||||
/// A string in the book's declared encoding, trimmed; empty is none.
|
||||
fn text(raw: &[u8], encoding: u32) -> Option<String> {
|
||||
let decoded: String = match (encoding, std::str::from_utf8(raw)) {
|
||||
(UTF_8, Ok(text)) => text.to_string(),
|
||||
(UTF_8, Err(_)) => String::from_utf8_lossy(raw).into_owned(),
|
||||
_ => raw.iter().map(|&byte| windows_1252(byte)).collect(),
|
||||
};
|
||||
let trimmed = decoded.trim_matches(|c: char| c == '\0' || c.is_whitespace());
|
||||
(!trimmed.is_empty()).then(|| trimmed.to_string())
|
||||
}
|
||||
|
||||
/// One Windows-1252 byte as a character.
|
||||
fn windows_1252(byte: u8) -> char {
|
||||
match byte {
|
||||
0x80..=0x9f => HIGH_CONTROLS[(byte - 0x80) as usize],
|
||||
_ => byte as char,
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters Windows-1252 puts where Latin-1 has C1 controls. The five
|
||||
/// positions it leaves undefined decode to themselves, as browsers do.
|
||||
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}',
|
||||
];
|
||||
|
||||
/// The language a MOBI locale names, for books with no EXTH language.
|
||||
///
|
||||
/// The low byte is a Windows primary language id; the region above it is
|
||||
/// dropped, since the file's own language field never carries one either.
|
||||
fn language_of(locale: u32) -> Option<&'static str> {
|
||||
Some(match locale & 0xff {
|
||||
0x01 => "ar",
|
||||
0x02 => "bg",
|
||||
0x03 => "ca",
|
||||
0x04 => "zh",
|
||||
0x05 => "cs",
|
||||
0x06 => "da",
|
||||
0x07 => "de",
|
||||
0x08 => "el",
|
||||
0x09 => "en",
|
||||
0x0a => "es",
|
||||
0x0b => "fi",
|
||||
0x0c => "fr",
|
||||
0x0d => "he",
|
||||
0x0e => "hu",
|
||||
0x0f => "is",
|
||||
0x10 => "it",
|
||||
0x11 => "ja",
|
||||
0x12 => "ko",
|
||||
0x13 => "nl",
|
||||
0x14 => "no",
|
||||
0x15 => "pl",
|
||||
0x16 => "pt",
|
||||
0x18 => "ro",
|
||||
0x19 => "ru",
|
||||
0x1a => "hr",
|
||||
0x1b => "sk",
|
||||
0x1d => "sv",
|
||||
0x1f => "tr",
|
||||
0x22 => "uk",
|
||||
0x29 => "fa",
|
||||
0x2a => "vi",
|
||||
0x36 => "af",
|
||||
0x39 => "hi",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn slice(bytes: &[u8], at: usize, len: usize) -> Option<&[u8]> {
|
||||
bytes.get(at..at.checked_add(len)?)
|
||||
}
|
||||
|
||||
fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(slice(bytes, at, 2)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(slice(bytes, at, 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const JPEG: &[u8] = &[0xff, 0xd8, 0xff, 0xe0, 0, 16, b'J', b'F', b'I', b'F'];
|
||||
|
||||
/// A Kindle book built field by field, so each test can break one thing.
|
||||
struct Book {
|
||||
name: &'static [u8],
|
||||
encoding: u32,
|
||||
encryption: u16,
|
||||
locale: u32,
|
||||
full_name: Vec<u8>,
|
||||
exth: Option<Vec<(u32, Vec<u8>)>>,
|
||||
first_image: u32,
|
||||
images: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Default for Book {
|
||||
fn default() -> Self {
|
||||
Book {
|
||||
name: b"A_Test_Book",
|
||||
encoding: UTF_8,
|
||||
encryption: 0,
|
||||
locale: 0x09,
|
||||
full_name: b"A Test Book".to_vec(),
|
||||
exth: Some(Vec::new()),
|
||||
first_image: 1,
|
||||
images: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Book {
|
||||
fn bytes(&self) -> Vec<u8> {
|
||||
const HEADER: usize = 232;
|
||||
let mut first = vec![0u8; MOBI_AT + HEADER];
|
||||
first[ENCRYPTION_AT..ENCRYPTION_AT + 2].copy_from_slice(&self.encryption.to_be_bytes());
|
||||
first[MOBI_AT..MOBI_AT + 4].copy_from_slice(MOBI_MAGIC);
|
||||
let put = |first: &mut Vec<u8>, at: usize, value: u32| {
|
||||
first[MOBI_AT + at..MOBI_AT + at + 4].copy_from_slice(&value.to_be_bytes());
|
||||
};
|
||||
put(&mut first, HEADER_LENGTH, HEADER as u32);
|
||||
put(&mut first, TEXT_ENCODING, self.encoding);
|
||||
put(&mut first, LOCALE, self.locale);
|
||||
put(&mut first, FIRST_IMAGE, self.first_image);
|
||||
if let Some(records) = &self.exth {
|
||||
put(&mut first, EXTH_FLAGS, HAS_EXTH);
|
||||
let mut body = Vec::new();
|
||||
for (kind, data) in records {
|
||||
body.extend_from_slice(&kind.to_be_bytes());
|
||||
body.extend_from_slice(&(data.len() as u32 + 8).to_be_bytes());
|
||||
body.extend_from_slice(data);
|
||||
}
|
||||
first.extend_from_slice(EXTH_MAGIC);
|
||||
first.extend_from_slice(&(body.len() as u32 + 12).to_be_bytes());
|
||||
first.extend_from_slice(&(records.len() as u32).to_be_bytes());
|
||||
first.extend_from_slice(&body);
|
||||
}
|
||||
let name_at = first.len();
|
||||
first.extend_from_slice(&self.full_name);
|
||||
put(&mut first, FULL_NAME_OFFSET, name_at as u32);
|
||||
put(&mut first, FULL_NAME_LENGTH, self.full_name.len() as u32);
|
||||
|
||||
let mut records = vec![first];
|
||||
records.extend(self.images.iter().cloned());
|
||||
|
||||
let mut out = vec![0u8; RECORD_LIST_AT + records.len() * 8];
|
||||
out[..self.name.len()].copy_from_slice(self.name);
|
||||
out[TYPE_AT..TYPE_AT + 8].copy_from_slice(BOOK_TYPE);
|
||||
out[RECORD_COUNT_AT..RECORD_COUNT_AT + 2]
|
||||
.copy_from_slice(&(records.len() as u16).to_be_bytes());
|
||||
for (at, record) in records.iter().enumerate() {
|
||||
let offset = out.len() as u32;
|
||||
let entry = RECORD_LIST_AT + at * 8;
|
||||
out[entry..entry + 4].copy_from_slice(&offset.to_be_bytes());
|
||||
out.extend_from_slice(record);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn exth(records: &[(u32, &[u8])]) -> Option<Vec<(u32, Vec<u8>)>> {
|
||||
Some(records.iter().map(|(k, v)| (*k, v.to_vec())).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exth_records_fill_the_record() {
|
||||
let book = Book {
|
||||
exth: exth(&[
|
||||
(UPDATED_TITLE, b"The Real Title"),
|
||||
(AUTHOR, b"First Author"),
|
||||
(AUTHOR, b"Second Author"),
|
||||
(PUBLISHER, b"A Press"),
|
||||
(DESCRIPTION, b"What it is about."),
|
||||
(ISBN, b"978-0-306-40615-7"),
|
||||
(SUBJECT, b"History"),
|
||||
(SUBJECT, b"Ships"),
|
||||
(PUBLISHED, b"1999-01-02"),
|
||||
(ASIN, b"B000TEST00"),
|
||||
(LANGUAGE, b"de"),
|
||||
]),
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.mobi", &book.bytes());
|
||||
assert_eq!(meta.source, "mobi");
|
||||
assert_eq!(meta.title.as_deref(), Some("The Real Title"));
|
||||
assert_eq!(meta.authors, ["First Author", "Second Author"]);
|
||||
assert_eq!(meta.publisher.as_deref(), Some("A Press"));
|
||||
assert_eq!(meta.description.as_deref(), Some("What it is about."));
|
||||
assert_eq!(meta.date.as_deref(), Some("1999-01-02"));
|
||||
assert_eq!(meta.subjects, ["History", "Ships"]);
|
||||
assert_eq!(meta.language.as_deref(), Some("de"));
|
||||
assert_eq!(meta.identifiers["isbn"], "9780306406157");
|
||||
assert_eq!(meta.identifiers["asin"], "B000TEST00");
|
||||
assert!(meta.notes.is_empty(), "{:?}", meta.notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_falls_back_to_the_full_name_and_then_the_database_name() {
|
||||
let meta = read("x.mobi", &Book::default().bytes());
|
||||
assert_eq!(meta.title.as_deref(), Some("A Test Book"));
|
||||
|
||||
let book = Book {
|
||||
full_name: Vec::new(),
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.mobi", &book.bytes());
|
||||
assert_eq!(meta.title.as_deref(), Some("A_Test_Book"));
|
||||
assert!(meta.notes[0].contains("Palm database name"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_language_falls_back_to_the_locale() {
|
||||
let book = Book {
|
||||
locale: 0x040c,
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(
|
||||
read("x.mobi", &book.bytes()).language.as_deref(),
|
||||
Some("fr")
|
||||
);
|
||||
|
||||
let book = Book {
|
||||
locale: 0,
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(read("x.mobi", &book.bytes()).language, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_1252_strings_decode_as_windows_1252() {
|
||||
let book = Book {
|
||||
encoding: WINDOWS_1252,
|
||||
exth: exth(&[
|
||||
(AUTHOR, b"Ren\xe9 Ch\x96ar"),
|
||||
(PUBLISHER, b"\x93Quoted\x94"),
|
||||
]),
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.mobi", &book.bytes());
|
||||
assert_eq!(meta.authors, ["René Ch–ar"]);
|
||||
assert_eq!(meta.publisher.as_deref(), Some("“Quoted”"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cover_is_the_image_record_the_offset_names() {
|
||||
let book = Book {
|
||||
exth: exth(&[(COVER_OFFSET, &1u32.to_be_bytes())]),
|
||||
images: vec![b"GIF89a-thumb".to_vec(), JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
let cover = read("x.mobi", &book.bytes()).cover.expect("a cover");
|
||||
assert_eq!(cover.media_type, "image/jpeg");
|
||||
assert_eq!(cover.bytes, JPEG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_thumbnail_stands_in_when_no_cover_is_named() {
|
||||
let book = Book {
|
||||
exth: exth(&[(THUMB_OFFSET, &0u32.to_be_bytes())]),
|
||||
images: vec![b"\x89PNG\r\n\x1a\nrest".to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
let cover = read("x.mobi", &book.bytes()).cover.expect("a cover");
|
||||
assert_eq!(cover.media_type, "image/png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_cover_named_only_the_record_at_first_image_can_be_the_cover() {
|
||||
let book = Book {
|
||||
images: vec![JPEG.to_vec(), b"GIF89a-later".to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
let cover = read("x.mobi", &book.bytes()).cover.expect("a cover");
|
||||
assert_eq!(cover.media_type, "image/jpeg");
|
||||
assert_eq!(cover.bytes, JPEG);
|
||||
|
||||
// The record at first_image is not an image: no cover, even though a
|
||||
// later record is one.
|
||||
let book = Book {
|
||||
images: vec![
|
||||
b"not an image".to_vec(),
|
||||
JPEG.to_vec(),
|
||||
b"GIF89a-later".to_vec(),
|
||||
],
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(read("x.mobi", &book.bytes()).cover, None);
|
||||
|
||||
let book = Book {
|
||||
images: vec![b"not an image".to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(read("x.mobi", &book.bytes()).cover, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_font_at_first_image_is_not_skipped_past_to_an_inline_image() {
|
||||
// No EXTH 201 or 202. The first resource record is a font, as in
|
||||
// kindlegen output; calibre reads only that record and finds no cover.
|
||||
let book = Book {
|
||||
images: vec![b"FONT\0\0\0\x18".to_vec(), JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(read("x.mobi", &book.bytes()).cover, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_kf8_boundary_below_first_image_does_not_hide_the_cover() {
|
||||
let book = Book {
|
||||
exth: exth(&[(121, &1u32.to_be_bytes())]),
|
||||
first_image: 2,
|
||||
images: vec![b"text".to_vec(), JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
assert!(read("x.mobi", &book.bytes()).cover.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_image_search_stops_at_the_kf8_boundary() {
|
||||
let book = Book {
|
||||
exth: exth(&[(121, &2u32.to_be_bytes())]),
|
||||
images: vec![b"text".to_vec(), JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
// Record 1 is not an image, and record 2 is past the boundary.
|
||||
assert_eq!(read("x.mobi", &book.bytes()).cover, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exth_113_is_an_asin_a_uuid_or_something_else() {
|
||||
let id = |value: &[u8]| {
|
||||
let book = Book {
|
||||
exth: exth(&[(ASIN, value)]),
|
||||
..Book::default()
|
||||
};
|
||||
read("x.mobi", &book.bytes()).identifiers
|
||||
};
|
||||
assert_eq!(id(b"B01A7RJGIW")["asin"], "B01A7RJGIW");
|
||||
assert_eq!(id(b"0306406152")["asin"], "0306406152");
|
||||
let uuid = id(b"69AE65CA-B644-499F-A78C-139771C7140A");
|
||||
assert_eq!(uuid["uuid"], "69ae65ca-b644-499f-a78c-139771c7140a");
|
||||
assert_eq!(uuid.get("asin"), None);
|
||||
let other = id(b"2AW6TL2JJEYYGXCOV3PWN6ZOYUORXAVX");
|
||||
assert_eq!(other["other"], "2AW6TL2JJEYYGXCOV3PWN6ZOYUORXAVX");
|
||||
assert_eq!(other.get("asin"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cover_that_points_nowhere_is_a_note_and_not_a_cover() {
|
||||
let book = Book {
|
||||
exth: exth(&[(COVER_OFFSET, &7u32.to_be_bytes())]),
|
||||
images: vec![JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.mobi", &book.bytes());
|
||||
assert_eq!(meta.cover, None);
|
||||
assert_eq!(meta.notes, ["the cover points past the last record"]);
|
||||
|
||||
let book = Book {
|
||||
exth: exth(&[(COVER_OFFSET, &u32::MAX.to_be_bytes())]),
|
||||
first_image: u32::MAX - 1,
|
||||
images: vec![JPEG.to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
assert_eq!(read("x.mobi", &book.bytes()).cover, None);
|
||||
|
||||
let book = Book {
|
||||
exth: exth(&[(COVER_OFFSET, &0u32.to_be_bytes())]),
|
||||
images: vec![b"not an image".to_vec()],
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.mobi", &book.bytes());
|
||||
assert_eq!(meta.cover, None);
|
||||
assert_eq!(meta.notes, ["the cover record is not an image"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encrypted_book_still_has_its_header_read() {
|
||||
let book = Book {
|
||||
encryption: 2,
|
||||
exth: exth(&[(AUTHOR, b"Somebody")]),
|
||||
..Book::default()
|
||||
};
|
||||
let meta = read("x.azw", &book.bytes());
|
||||
assert_eq!(meta.authors, ["Somebody"]);
|
||||
assert_eq!(meta.notes, ["drm"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exth_record_that_overruns_its_block_stops_the_reading() {
|
||||
let mut bytes = Book {
|
||||
exth: exth(&[(AUTHOR, b"Kept"), (PUBLISHER, b"Lost")]),
|
||||
..Book::default()
|
||||
}
|
||||
.bytes();
|
||||
// The second record's length, made to reach past the block.
|
||||
let at = find(&bytes, b"Lost") - 4;
|
||||
bytes[at..at + 4].copy_from_slice(&0x7fff_ffffu32.to_be_bytes());
|
||||
let meta = read("x.mobi", &bytes);
|
||||
assert_eq!(meta.authors, ["Kept"]);
|
||||
assert_eq!(meta.publisher, None);
|
||||
assert!(
|
||||
meta.notes
|
||||
.contains(&"the EXTH block ends early".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_length_shorter_than_its_own_header_stops_the_reading() {
|
||||
let mut bytes = Book {
|
||||
exth: exth(&[(AUTHOR, b"Kept")]),
|
||||
..Book::default()
|
||||
}
|
||||
.bytes();
|
||||
let at = find(&bytes, b"Kept") - 4;
|
||||
bytes[at..at + 4].copy_from_slice(&3u32.to_be_bytes());
|
||||
let meta = read("x.mobi", &bytes);
|
||||
assert!(meta.authors.is_empty());
|
||||
assert!(
|
||||
meta.notes
|
||||
.contains(&"the EXTH block ends early".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_kindle_book_says_so() {
|
||||
let meta = read("x.mobi", b"not a palm database at all");
|
||||
assert_eq!(meta.source, "none");
|
||||
assert!(meta.notes[0].starts_with("not a Kindle book"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_record_with_no_mobi_header_is_refused() {
|
||||
let mut bytes = Book::default().bytes();
|
||||
let at = mobi_header(&bytes);
|
||||
bytes[at] = b'X';
|
||||
let meta = read("x.mobi", &bytes);
|
||||
assert_eq!(meta.source, "none");
|
||||
assert_eq!(meta.notes, ["no MOBI header in the first record"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_too_short_for_a_field_does_not_have_that_field() {
|
||||
let mut bytes = Book::default().bytes();
|
||||
let at = mobi_header(&bytes) + HEADER_LENGTH;
|
||||
// Long enough for the encoding, too short for the full name.
|
||||
bytes[at..at + 4].copy_from_slice(&24u32.to_be_bytes());
|
||||
let meta = read("x.mobi", &bytes);
|
||||
assert_eq!(meta.title.as_deref(), Some("A_Test_Book"));
|
||||
assert_eq!(meta.language, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_returns_without_panicking() {
|
||||
let bytes = Book {
|
||||
exth: exth(&[
|
||||
(UPDATED_TITLE, b"Title"),
|
||||
(AUTHOR, b"Author"),
|
||||
(COVER_OFFSET, &0u32.to_be_bytes()),
|
||||
]),
|
||||
images: vec![JPEG.to_vec()],
|
||||
..Book::default()
|
||||
}
|
||||
.bytes();
|
||||
for len in 0..=bytes.len() {
|
||||
let _ = read("x.mobi", &bytes[..len]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the MOBI header starts: after the record list, so the `MOBI`
|
||||
/// at the end of the database type is not it.
|
||||
fn mobi_header(bytes: &[u8]) -> usize {
|
||||
RECORD_LIST_AT + find(&bytes[RECORD_LIST_AT..], MOBI_MAGIC)
|
||||
}
|
||||
|
||||
fn find(haystack: &[u8], needle: &[u8]) -> usize {
|
||||
haystack
|
||||
.windows(needle.len())
|
||||
.position(|window| window == needle)
|
||||
.expect("present")
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Fixtures
|
||||
|
||||
## MOBI and AZW3
|
||||
|
||||
`lantern.html` is a two-paragraph story written for these tests, and
|
||||
`lantern-cover.jpg` a 120×180 cover drawn for them with Pillow. Both are
|
||||
dedicated to the public domain (CC0 1.0), and so is everything made from them.
|
||||
|
||||
`lantern.mobi` (MOBI 6) and `lantern.azw3` (KF8) were made from them with
|
||||
calibre 9.14:
|
||||
|
||||
```sh
|
||||
common=(--title "A Lantern in the Orchard" --authors "Ada Quill & Tomás Reed"
|
||||
--publisher "Orchard Press" --isbn 9780306406157 --tags "Fiction,Villages"
|
||||
--language en --pubdate 2001-04-05 --comments "A short story written for testing."
|
||||
--cover lantern-cover.jpg)
|
||||
ebook-convert lantern.html lantern.mobi --mobi-file-type old "${common[@]}"
|
||||
ebook-convert lantern.html lantern.azw3 "${common[@]}"
|
||||
```
|
||||
|
||||
The other three are `lantern.mobi` with one thing broken. `r0` is the first
|
||||
record's offset, the big-endian 32-bit number at byte 78 (136 here).
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `lantern-no-exth.mobi` | The EXTH flag (`0x40`) cleared in the MOBI header's flags, at `r0 + 16 + 112` |
|
||||
| `lantern-drm.mobi` | The PalmDOC encryption type, at `r0 + 12`, set to 2 |
|
||||
| `lantern-truncated.mobi` | The first 1024 bytes only |
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
+5
@@ -0,0 +1,5 @@
|
||||
<html><head><meta charset="utf-8"><title>x</title></head><body>
|
||||
<h1>A Lantern in the Orchard</h1>
|
||||
<p>The lantern hung from the lowest branch of the pear tree, and every evening someone lit it. Nobody in the village could say who.</p>
|
||||
<p>Café owners swore it was the miller; the miller swore it was the wind.</p>
|
||||
</body></html>
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,146 @@
|
||||
//! MOBI and AZW3 files as a converter writes them, and as they break.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn read(name: &str) -> bookmeta::Metadata {
|
||||
bookmeta::read(&fixture(name))
|
||||
}
|
||||
|
||||
/// What the two converted fixtures were given, and so must say.
|
||||
fn says_what_it_was_given(meta: &bookmeta::Metadata) {
|
||||
assert_eq!(meta.source, "mobi");
|
||||
assert_eq!(meta.title.as_deref(), Some("A Lantern in the Orchard"));
|
||||
assert_eq!(meta.authors, ["Ada Quill", "Tomás Reed"]);
|
||||
assert_eq!(meta.publisher.as_deref(), Some("Orchard Press"));
|
||||
assert_eq!(
|
||||
meta.description.as_deref(),
|
||||
Some("A short story written for testing.")
|
||||
);
|
||||
assert_eq!(meta.date.as_deref(), Some("2001-04-05T04:00:00+00:00"));
|
||||
assert_eq!(meta.language.as_deref(), Some("en"));
|
||||
assert_eq!(meta.subjects, ["Fiction", "Villages"]);
|
||||
assert_eq!(meta.identifiers["isbn"], "9780306406157");
|
||||
assert_eq!(meta.identifiers.get("asin"), None);
|
||||
assert_eq!(meta.identifiers["uuid"].len(), 36);
|
||||
|
||||
let cover = meta.cover.as_ref().expect("a cover");
|
||||
assert_eq!(cover.media_type, "image/jpeg");
|
||||
assert!(!cover.guessed, "EXTH 201 names the cover");
|
||||
let original = std::fs::read(fixture("lantern-cover.jpg")).expect("the cover fixture");
|
||||
assert_eq!(cover.bytes, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mobi_6_file_says_what_it_was_given() {
|
||||
let meta = read("lantern.mobi");
|
||||
says_what_it_was_given(&meta);
|
||||
assert!(meta.notes.is_empty(), "{:?}", meta.notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_azw3_file_says_what_it_was_given() {
|
||||
let meta = read("lantern.azw3");
|
||||
says_what_it_was_given(&meta);
|
||||
assert!(meta.notes.is_empty(), "{:?}", meta.notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exth_113_uuid_is_not_an_asin() {
|
||||
for name in ["lantern.mobi", "lantern.azw3"] {
|
||||
let meta = read(name);
|
||||
assert_eq!(meta.identifiers.get("asin"), None, "{name}");
|
||||
assert!(meta.identifiers.contains_key("uuid"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `lantern.mobi` with its cover and thumbnail offsets (EXTH 201 and 202)
|
||||
/// retyped to an unused record type, so the file names no cover.
|
||||
fn lantern_naming_no_cover() -> Vec<u8> {
|
||||
let mut bytes = std::fs::read(fixture("lantern.mobi")).expect("the fixture");
|
||||
let exth = bytes.windows(4).position(|w| w == b"EXTH").expect("EXTH");
|
||||
let count = u32::from_be_bytes(bytes[exth + 8..exth + 12].try_into().unwrap());
|
||||
let mut cursor = exth + 12;
|
||||
let mut retyped = 0;
|
||||
for _ in 0..count {
|
||||
let kind = u32::from_be_bytes(bytes[cursor..cursor + 4].try_into().unwrap());
|
||||
let size = u32::from_be_bytes(bytes[cursor + 4..cursor + 8].try_into().unwrap());
|
||||
if kind == 201 || kind == 202 {
|
||||
bytes[cursor..cursor + 4].copy_from_slice(&999u32.to_be_bytes());
|
||||
retyped += 1;
|
||||
}
|
||||
cursor += size as usize;
|
||||
}
|
||||
assert!(retyped > 0, "the fixture names a cover");
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_naming_no_cover_gets_its_first_image_record() {
|
||||
let meta = bookmeta::from_bytes("x.mobi", &lantern_naming_no_cover());
|
||||
let cover = meta.cover.expect("the first image record");
|
||||
assert_eq!(cover.media_type, "image/jpeg");
|
||||
assert!(cover.guessed, "a cover taken by position is a guess");
|
||||
let original = std::fs::read(fixture("lantern-cover.jpg")).expect("the cover fixture");
|
||||
assert_eq!(cover.bytes, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_exth_still_has_its_full_name_and_locale() {
|
||||
let meta = read("lantern-no-exth.mobi");
|
||||
assert_eq!(meta.source, "mobi");
|
||||
assert_eq!(meta.title.as_deref(), Some("A Lantern in the Orchard"));
|
||||
assert_eq!(meta.language.as_deref(), Some("en"));
|
||||
assert!(meta.authors.is_empty());
|
||||
assert!(meta.identifiers.is_empty());
|
||||
// No EXTH names no cover, so the first image record stands in for one.
|
||||
let cover = meta.cover.expect("the first image record");
|
||||
assert_eq!(cover.media_type, "image/jpeg");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_file_is_an_empty_record_with_a_reason() {
|
||||
let meta = read("lantern-truncated.mobi");
|
||||
assert_eq!(meta.source, "none");
|
||||
assert!(meta.is_empty());
|
||||
assert_eq!(meta.notes, ["the first record lies outside the file"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drm_flagged_file_has_its_metadata_and_says_drm() {
|
||||
let meta = read("lantern-drm.mobi");
|
||||
says_what_it_was_given(&meta);
|
||||
assert_eq!(meta.notes, ["drm"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_of_the_mobi_fixture_returns() {
|
||||
let bytes = std::fs::read(fixture("lantern.mobi")).expect("the fixture");
|
||||
let first_record_end = u32::from_be_bytes(bytes[86..90].try_into().unwrap()) as usize;
|
||||
for len in 0..=bytes.len() {
|
||||
let meta = bookmeta::from_bytes("cut.mobi", &bytes[..len]);
|
||||
if len < first_record_end {
|
||||
assert!(meta.is_empty(), "cut at {len}: {meta:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_single_byte_corruption_of_the_header_returns() {
|
||||
let bytes = std::fs::read(fixture("lantern.mobi")).expect("the fixture");
|
||||
// The Palm header, the record list, and the whole of the first record:
|
||||
// every offset the reader follows is in there.
|
||||
let first_record_end = u32::from_be_bytes(bytes[86..90].try_into().unwrap()) as usize;
|
||||
for at in 0..first_record_end {
|
||||
for value in [0x00, 0x7f, 0xff] {
|
||||
let mut broken = bytes.clone();
|
||||
broken[at] = value;
|
||||
let _ = bookmeta::from_bytes("broken.mobi", &broken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,12 +89,12 @@ one bad file does not stop a sweep.
|
||||
| `ole2` | The compound-file header every binary Word document starts with |
|
||||
| `epub` | A zip holding `mimetype` and `META-INF/container.xml` |
|
||||
| `zip-wrapped-pdf` | A zip whose only real member is one PDF |
|
||||
| `zip-wrapped-fb2` | A zip whose only real member is one FictionBook — the `.fb2.zip` most of them are passed around as |
|
||||
| `cbz` | A zip whose every real member is a page image: JPEG, PNG, GIF or WebP |
|
||||
| `zip-wrapped-fb2` | A zip whose only real member is named `.fb2` — the `.fb2.zip` most FictionBooks are passed around as |
|
||||
| `cbz` | A zip whose every real member is a page image (JPEG, PNG, GIF or WebP), and which carries a `ComicInfo.xml` or is itself named `.cbz` or `.cbr` |
|
||||
| `azw3`, `mobi` | A Palm database tagged `BOOKMOBI`, told apart by the format version inside the first record |
|
||||
| `lit` | `ITOLITLS`, Microsoft Reader's signature |
|
||||
| `rtf` | `{\rtf` at the front, after any byte-order mark and blank space |
|
||||
| `fb2` | XML whose root element is `FictionBook`, found by stepping over the declaration, comments and doctype in the first four kilobytes |
|
||||
| `rtf` | `{\rtf` at the front, after any byte-order mark and blank space, followed by the version digit, a space or the next control word |
|
||||
| `fb2` | XML whose root element is `FictionBook`, found by stepping over the declaration, comments and doctype in the first four kilobytes; UTF-16 with a byte-order mark is decoded first |
|
||||
| `html` | Markup at the front, after any byte-order mark |
|
||||
| `txt` | Text that is none of the above |
|
||||
| `unknown` | Anything else, with a note saying what was seen |
|
||||
@@ -110,8 +110,17 @@ kind is there to stop exactly that.
|
||||
A comic is the pages and nothing else. Directories, the `ComicInfo.xml` a
|
||||
comic reader writes into the archive, and the desktop clutter every archive
|
||||
picks up are passed over; anything more — one PDF among the pages, a readme —
|
||||
and the zip is not a comic, and says what it holds instead. Only names are
|
||||
read, out of the archive's directory, so no member is ever unpacked.
|
||||
and the zip is not a comic, and says what it holds instead.
|
||||
|
||||
A zip of pictures is as often a holiday as a comic, so images alone are not
|
||||
enough. It is a comic when it carries a `ComicInfo.xml`, or when its own name
|
||||
ends `.cbz` or `.cbr`. Otherwise it is `unknown`, with a note saying it is a
|
||||
zip of so many images and would be a comic book if its name said `.cbz`.
|
||||
|
||||
Members are judged by name. Only the archive's directory is read, so no
|
||||
member is ever unpacked and a page called `001.jpg` is taken to be an image
|
||||
without its bytes being looked at. The same goes for a wrapped FictionBook:
|
||||
the one member is taken to be a FictionBook because its name ends `.fb2`.
|
||||
|
||||
FictionBook is read as bytes rather than as text. A great many are written in
|
||||
windows-1251, which spells its markup in ASCII but is not UTF-8, and would
|
||||
|
||||
@@ -9,9 +9,22 @@
|
||||
//! windows-1251, which is not UTF-8 but spells its markup in ASCII all the
|
||||
//! same, and a reader that insisted on UTF-8 would call every one of them
|
||||
//! binary.
|
||||
//!
|
||||
//! A FictionBook saved as UTF-16 is the one case where the markup is not
|
||||
//! ASCII bytes. Its byte-order mark says so, and the front is decoded before
|
||||
//! the same walk is made over it.
|
||||
|
||||
use crate::BOM;
|
||||
|
||||
/// The UTF-16 byte-order mark, little-endian.
|
||||
const UTF16_LE: &[u8] = b"\xff\xfe";
|
||||
/// The UTF-16 byte-order mark, big-endian.
|
||||
const UTF16_BE: &[u8] = b"\xfe\xff";
|
||||
|
||||
/// Most UTF-16 code units decoded from the front: the same window, in
|
||||
/// characters, as the bytes read for every other encoding.
|
||||
const UTF16_UNITS: usize = 2048;
|
||||
|
||||
/// What the root element of a FictionBook is called.
|
||||
const ROOT: &[u8] = b"FictionBook";
|
||||
|
||||
@@ -21,9 +34,41 @@ const ROOT: &[u8] = b"FictionBook";
|
||||
/// does not begin inside it is not found, so the answer is no rather than a
|
||||
/// guess.
|
||||
pub fn is_fictionbook(head: &[u8]) -> bool {
|
||||
match utf16(head) {
|
||||
Some(decoded) => is_fictionbook_root(decoded.as_bytes()),
|
||||
None => is_fictionbook_root(head),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_fictionbook_root(head: &[u8]) -> bool {
|
||||
root_element(head).is_some_and(|name| local_name(name) == ROOT)
|
||||
}
|
||||
|
||||
/// The front of a UTF-16 file as UTF-8, if a byte-order mark says it is one.
|
||||
///
|
||||
/// Only a bounded prefix is decoded. A half character at the end, or a
|
||||
/// surrogate without its pair, becomes a replacement character, which the
|
||||
/// walk takes as part of a name and so never as the end of one.
|
||||
fn utf16(head: &[u8]) -> Option<String> {
|
||||
let (body, big_endian) = match head.strip_prefix(UTF16_LE) {
|
||||
Some(body) => (body, false),
|
||||
None => (head.strip_prefix(UTF16_BE)?, true),
|
||||
};
|
||||
let units = body.chunks_exact(2).take(UTF16_UNITS).map(|pair| {
|
||||
let pair = [pair[0], pair[1]];
|
||||
if big_endian {
|
||||
u16::from_be_bytes(pair)
|
||||
} else {
|
||||
u16::from_le_bytes(pair)
|
||||
}
|
||||
});
|
||||
Some(
|
||||
char::decode_utf16(units)
|
||||
.map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The name of the first element, after the prolog.
|
||||
fn root_element(head: &[u8]) -> Option<&[u8]> {
|
||||
let mut rest = head.strip_prefix(BOM).unwrap_or(head);
|
||||
@@ -146,6 +191,60 @@ mod tests {
|
||||
assert!(!is_fictionbook(b"<!-- never closed <FictionBook>"));
|
||||
}
|
||||
|
||||
fn utf16(text: &str, big_endian: bool) -> Vec<u8> {
|
||||
let mut out = if big_endian {
|
||||
UTF16_BE.to_vec()
|
||||
} else {
|
||||
UTF16_LE.to_vec()
|
||||
};
|
||||
for unit in text.encode_utf16() {
|
||||
out.extend_from_slice(&if big_endian {
|
||||
unit.to_be_bytes()
|
||||
} else {
|
||||
unit.to_le_bytes()
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const UTF16_BOOK: &str = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\r\n\
|
||||
<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\">\
|
||||
<description><book-title>Мельница</book-title>";
|
||||
|
||||
#[test]
|
||||
fn a_little_endian_utf16_fictionbook_is_recognised() {
|
||||
assert!(is_fictionbook(&utf16(UTF16_BOOK, false)));
|
||||
assert!(!is_fictionbook(&utf16(
|
||||
"<?xml version=\"1.0\"?><rss>",
|
||||
false
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_big_endian_utf16_fictionbook_is_recognised() {
|
||||
assert!(is_fictionbook(&utf16(UTF16_BOOK, true)));
|
||||
assert!(!is_fictionbook(&utf16(
|
||||
"<?xml version=\"1.0\"?><rss>",
|
||||
true
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_read_in_the_wrong_order_is_not_a_fictionbook() {
|
||||
let mut swapped = utf16(UTF16_BOOK, false);
|
||||
swapped[..2].copy_from_slice(UTF16_BE);
|
||||
assert!(!is_fictionbook(&swapped));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_utf16_root_the_window_cut_short_is_not_taken() {
|
||||
let head = utf16("<FictionBook>", false);
|
||||
for cut in 0..head.len() {
|
||||
assert!(!is_fictionbook(&head[..cut]), "cut at {cut}");
|
||||
}
|
||||
assert!(is_fictionbook(&head));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_or_mangled_prolog_does_not_panic() {
|
||||
let head = b"\xef\xbb\xbf<?xml?><!--c--><!DOCTYPE x [ <!ENTITY a '>'> ] \"]\">\
|
||||
|
||||
+137
-13
@@ -36,7 +36,10 @@ const ARCHIVE_NOISE: &[&str] = &["__macosx/", ".ds_store", "thumbs.db"];
|
||||
|
||||
/// What a comic book archive carries besides its pages: the catalogue entry
|
||||
/// comic readers write into it.
|
||||
const COMIC_NOISE: &[&str] = &["comicinfo.xml"];
|
||||
const COMIC_CATALOGUE: &str = "comicinfo.xml";
|
||||
|
||||
/// The extensions that say an archive is a comic book.
|
||||
const COMIC_EXTENSIONS: &[&str] = &["cbz", "cbr"];
|
||||
|
||||
/// The extensions of the images a comic book archive is made of.
|
||||
const PAGE_IMAGES: &[&str] = &[".jpg", ".jpeg", ".png", ".gif", ".webp"];
|
||||
@@ -125,8 +128,23 @@ fn archive(source: &impl Bytes, doc: &mut Doc) -> Kind {
|
||||
doc.note(format!("a zip holding one FictionBook, {fb2:?}"));
|
||||
return Kind::ZipWrappedFb2;
|
||||
}
|
||||
if is_comic(&names) {
|
||||
return Kind::Cbz;
|
||||
if let Some(pages) = comic_pages(&names) {
|
||||
// A zip of pictures is as often a holiday as a comic, and only the
|
||||
// names have been read. It is a comic when something says so: the
|
||||
// catalogue entry a comic reader writes, or a name that claims it.
|
||||
let named_comic = doc
|
||||
.declared_ext
|
||||
.as_deref()
|
||||
.is_some_and(|ext| COMIC_EXTENSIONS.contains(&ext));
|
||||
if pages.catalogued || named_comic {
|
||||
return Kind::Cbz;
|
||||
}
|
||||
doc.note(format!(
|
||||
"a zip of {} image{}, which would be a comic book if its name said .cbz",
|
||||
pages.count,
|
||||
if pages.count == 1 { "" } else { "s" }
|
||||
));
|
||||
return Kind::Unknown;
|
||||
}
|
||||
if lower
|
||||
.iter()
|
||||
@@ -160,23 +178,39 @@ fn sole_member<'a>(names: &'a [String], extension: &str) -> Option<&'a str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an archive is the pages of a comic and nothing else.
|
||||
/// The pages of an archive that is images and nothing else.
|
||||
struct Pages {
|
||||
/// How many images there are.
|
||||
count: usize,
|
||||
/// Whether a comic reader's catalogue entry is there beside them.
|
||||
catalogued: bool,
|
||||
}
|
||||
|
||||
/// The pages, if an archive is images and nothing else.
|
||||
///
|
||||
/// Every real member has to be an image. One PDF or one text file among the
|
||||
/// pages makes it something else, and saying what would be a guess.
|
||||
fn is_comic(names: &[String]) -> bool {
|
||||
/// pages makes it something else, and saying what would be a guess. Images
|
||||
/// are known by their names alone: only the archive's directory is read.
|
||||
fn comic_pages(names: &[String]) -> Option<Pages> {
|
||||
let mut catalogued = false;
|
||||
let pages: Vec<String> = real_members(names)
|
||||
.into_iter()
|
||||
.map(|name| name.to_lowercase())
|
||||
.filter(|name| {
|
||||
let file = name.rsplit('/').next().unwrap_or(name);
|
||||
!COMIC_NOISE.contains(&file)
|
||||
let catalogue = file == COMIC_CATALOGUE;
|
||||
catalogued |= catalogue;
|
||||
!catalogue
|
||||
})
|
||||
.collect();
|
||||
!pages.is_empty()
|
||||
let all_images = !pages.is_empty()
|
||||
&& pages
|
||||
.iter()
|
||||
.all(|name| PAGE_IMAGES.iter().any(|image| name.ends_with(image)))
|
||||
.all(|name| PAGE_IMAGES.iter().any(|image| name.ends_with(image)));
|
||||
all_images.then_some(Pages {
|
||||
count: pages.len(),
|
||||
catalogued,
|
||||
})
|
||||
}
|
||||
|
||||
/// The members that carry content: no directories, no desktop clutter.
|
||||
@@ -198,7 +232,7 @@ fn front(head: &[u8], doc: &mut Doc) -> Kind {
|
||||
// design but not always in practice, and a FictionBook is as often
|
||||
// windows-1251 as UTF-8.
|
||||
let lead = head.strip_prefix(BOM).unwrap_or(head).trim_ascii_start();
|
||||
if lead.starts_with(RTF) {
|
||||
if is_rtf(lead) {
|
||||
return Kind::Rtf;
|
||||
}
|
||||
if fb2::is_fictionbook(head) {
|
||||
@@ -207,6 +241,17 @@ fn front(head: &[u8], doc: &mut Doc) -> Kind {
|
||||
text(head, doc)
|
||||
}
|
||||
|
||||
/// Whether `lead` opens an RTF document.
|
||||
///
|
||||
/// `{\rtf` has to be the whole control word: what follows it is the version,
|
||||
/// normally `1`, or the space or next control word that ends it. `{\rtfoo` is
|
||||
/// some other word that happens to start the same way.
|
||||
fn is_rtf(lead: &[u8]) -> bool {
|
||||
lead.strip_prefix(RTF)
|
||||
.and_then(|rest| rest.first())
|
||||
.is_some_and(|next| next.is_ascii_digit() || next.is_ascii_whitespace() || *next == b'\\')
|
||||
}
|
||||
|
||||
/// Text, markup, or nothing this knows.
|
||||
fn text(head: &[u8], doc: &mut Doc) -> Kind {
|
||||
if head.is_empty() {
|
||||
@@ -432,10 +477,23 @@ mod tests {
|
||||
#[test]
|
||||
fn rtf_cut_short_of_its_control_word_is_not_rtf() {
|
||||
assert_eq!(sniff(&br"{\rt".as_slice(), "a.rtf").kind, Kind::Txt);
|
||||
assert_eq!(sniff(&br"{\rtf".as_slice(), "a.rtf").kind, Kind::Txt);
|
||||
assert_eq!(kind_of(br"{\rtx1", "a.rtf"), Kind::Txt);
|
||||
assert_eq!(kind_of(br"text {\rtf1", "a.rtf"), Kind::Txt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtf_is_the_whole_control_word() {
|
||||
assert_eq!(kind_of(br"{\rtf\ansi\deff0", "a.rtf"), Kind::Rtf);
|
||||
assert_eq!(kind_of(b"{\\rtf \\ansi", "a.rtf"), Kind::Rtf);
|
||||
assert_eq!(kind_of(b"{\\rtf\r\n\\ansi", "a.rtf"), Kind::Rtf);
|
||||
assert_eq!(kind_of(br"{\rtf2", "a.rtf"), Kind::Rtf);
|
||||
|
||||
assert_eq!(kind_of(br"{\rtfoo bar}", "a.rtf"), Kind::Txt);
|
||||
assert_eq!(kind_of(br"{\rtf}", "a.rtf"), Kind::Txt);
|
||||
assert_eq!(kind_of(br"{\rtf-1", "a.rtf"), Kind::Txt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtf_named_as_a_word_document_is_remarked_on() {
|
||||
let doc = sniff(&padded(br"{\rtf1\ansi").as_slice(), "letter.doc");
|
||||
@@ -471,6 +529,28 @@ mod tests {
|
||||
assert_eq!(kind_of(feed, "feed.xml"), Kind::Html);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_utf16_fictionbook_is_recognised_in_either_byte_order() {
|
||||
let book = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<FictionBook>";
|
||||
for big_endian in [false, true] {
|
||||
let mut bytes = if big_endian {
|
||||
vec![0xfe, 0xff]
|
||||
} else {
|
||||
vec![0xff, 0xfe]
|
||||
};
|
||||
for unit in book.encode_utf16() {
|
||||
bytes.extend_from_slice(&if big_endian {
|
||||
unit.to_be_bytes()
|
||||
} else {
|
||||
unit.to_le_bytes()
|
||||
});
|
||||
}
|
||||
let doc = sniff(&padded(&bytes).as_slice(), "mill.fb2");
|
||||
assert_eq!(doc.kind, Kind::Fb2, "big-endian: {big_endian}");
|
||||
assert!(doc.notes.is_empty(), "{:?}", doc.notes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fictionbook_named_as_something_else_is_remarked_on() {
|
||||
let doc = sniff(&padded(b"<FictionBook>").as_slice(), "mill.txt");
|
||||
@@ -526,11 +606,55 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comic_saved_as_a_zip_is_remarked_on() {
|
||||
let doc = archive_of(&["001.jpg", "002.jpg"], "issue-1.zip");
|
||||
fn a_zip_of_photographs_is_not_a_comic() {
|
||||
let doc = archive_of(&["IMG_0001.jpg", "IMG_0002.jpg"], "holiday.zip");
|
||||
assert_eq!(doc.kind, Kind::Unknown);
|
||||
assert!(
|
||||
doc.notes.iter().any(|note| note
|
||||
== "a zip of 2 images, which would be a comic book if its name said .cbz"),
|
||||
"{:?}",
|
||||
doc.notes
|
||||
);
|
||||
|
||||
let one = archive_of(&["IMG_0001.jpg"], "holiday.zip");
|
||||
assert!(
|
||||
one.notes
|
||||
.iter()
|
||||
.any(|note| note.starts_with("a zip of 1 image,")),
|
||||
"{:?}",
|
||||
one.notes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_images_named_as_a_comic_are_one() {
|
||||
let doc = archive_of(&["IMG_0001.jpg", "IMG_0002.jpg"], "holiday.cbz");
|
||||
assert_eq!(doc.kind, Kind::Cbz);
|
||||
assert!(
|
||||
doc.notes.iter().any(|note| note.contains("comic")),
|
||||
!doc.notes.iter().any(|note| note.contains("named .")),
|
||||
"{:?}",
|
||||
doc.notes
|
||||
);
|
||||
|
||||
// A comic zipped and named as if it were RAR is still a comic, and
|
||||
// the name is remarked on.
|
||||
let rar = archive_of(&["001.jpg", "002.jpg"], "issue-1.cbr");
|
||||
assert_eq!(rar.kind, Kind::Cbz);
|
||||
assert!(
|
||||
rar.notes.iter().any(|note| note.contains("named .cbr")),
|
||||
"{:?}",
|
||||
rar.notes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comic_saved_as_a_zip_is_known_by_its_catalogue_and_remarked_on() {
|
||||
let doc = archive_of(&["001.jpg", "002.jpg", "ComicInfo.xml"], "issue-1.zip");
|
||||
assert_eq!(doc.kind, Kind::Cbz);
|
||||
assert!(
|
||||
doc.notes
|
||||
.iter()
|
||||
.any(|note| note == "named .zip, but the bytes say a comic book archive"),
|
||||
"{:?}",
|
||||
doc.notes
|
||||
);
|
||||
|
||||
+173
-13
@@ -95,34 +95,138 @@ fn tidy(s: &str) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Where a statement of responsibility stops naming people: the physical
|
||||
/// description ("p. cm.") and the identifiers a cataloguing block runs on to.
|
||||
static STATEMENT_END: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"(?i)\b(?:p\.\s?cm\b|pages\s+cm\b|cm\.|ISSN\b|ISBN\b)").expect("a valid pattern")
|
||||
});
|
||||
|
||||
/// A role written before the names it applies to, and whose names they are.
|
||||
const LEADING_ROLES: &[(&str, Role)] = &[
|
||||
("edited and translated by ", Role::Editor),
|
||||
("edited with an introduction by ", Role::Editor),
|
||||
("edited by ", Role::Editor),
|
||||
("selected and edited by ", Role::Editor),
|
||||
("compiled by ", Role::Editor),
|
||||
("general editor ", Role::Editor),
|
||||
("translated by ", Role::Skip),
|
||||
("translated from ", Role::Skip),
|
||||
("translated with ", Role::Skip),
|
||||
("with ", Role::Skip),
|
||||
("foreword by ", Role::Skip),
|
||||
("introduction by ", Role::Skip),
|
||||
("illustrated by ", Role::Skip),
|
||||
("notes by ", Role::Skip),
|
||||
("by ", Role::Author),
|
||||
];
|
||||
|
||||
/// A role written after a name: "Irving B. Weiner, editor-in-chief".
|
||||
const TRAILING_ROLES: &[&str] = &[
|
||||
"editor-in-chief",
|
||||
"general editor",
|
||||
"editors",
|
||||
"editor",
|
||||
"eds.",
|
||||
"eds",
|
||||
"ed.",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Role {
|
||||
Author,
|
||||
Editor,
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Split a statement of responsibility into who wrote and who edited.
|
||||
///
|
||||
/// Every name is held to the shape of a person's name, so the role words,
|
||||
/// fragments and page counts a cataloguing block is full of ("edited by" on
|
||||
/// a line of its own, "translated from the French", "p. cm") are dropped
|
||||
/// rather than read as people.
|
||||
fn people(statement: &str) -> (Vec<String>, Vec<String>) {
|
||||
let statement = match STATEMENT_END.find(statement) {
|
||||
Some(found) => &statement[..found.start()],
|
||||
None => statement,
|
||||
};
|
||||
let mut authors = Vec::new();
|
||||
let mut editors = Vec::new();
|
||||
for part in statement.split(';') {
|
||||
// "[edited by] Konrad H. Kinzl": the role in the brackets a
|
||||
// cataloguer adds when the book did not state it.
|
||||
let part = part.trim().replacen('[', "", 1).replacen(']', "", 1);
|
||||
let part = part.trim();
|
||||
let lower = part.to_lowercase();
|
||||
let (target, rest) = if let Some(rest) = lower.strip_prefix("edited by ") {
|
||||
(&mut editors, &part[part.len() - rest.len()..])
|
||||
} else if lower.starts_with("translated by ")
|
||||
|| lower.starts_with("with ")
|
||||
|| lower.starts_with("foreword by ")
|
||||
|| lower.starts_with("introduction by ")
|
||||
{
|
||||
let (mut role, mut rest) = (Role::Author, part);
|
||||
for (prefix, given) in LEADING_ROLES {
|
||||
if lower.starts_with(prefix) {
|
||||
role = *given;
|
||||
rest = &part[prefix.len()..];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if role == Role::Skip {
|
||||
continue;
|
||||
} else {
|
||||
(&mut authors, part)
|
||||
};
|
||||
}
|
||||
// "Alan Carr.— 2nd ed": the edition statement that follows the names.
|
||||
let rest = EDITION_TAIL.replace(rest, "");
|
||||
for name in rest.split(" and ").flat_map(|n| n.split(',')) {
|
||||
let name = tidy(name);
|
||||
if name.len() >= 3 && name.split_whitespace().count() <= 5 {
|
||||
target.push(name);
|
||||
let mut name = tidy(name);
|
||||
let mut this_role = role;
|
||||
let lowered = name.to_lowercase();
|
||||
if let Some(suffix) = TRAILING_ROLES.iter().find(|r| lowered.ends_with(*r)) {
|
||||
name = tidy(&name[..name.len() - suffix.len()]);
|
||||
this_role = Role::Editor;
|
||||
}
|
||||
// A role alone on its part names whoever came before it.
|
||||
if name.is_empty() && this_role == Role::Editor {
|
||||
if let Some(last) = authors.pop() {
|
||||
editors.push(last);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if name.split_whitespace().count() > 5 {
|
||||
continue;
|
||||
}
|
||||
let Some(person) = bibclean::author::clean(&name) else {
|
||||
continue;
|
||||
};
|
||||
if !reads_as_a_name(&person) {
|
||||
continue;
|
||||
}
|
||||
if person.split_whitespace().count() < 2 {
|
||||
continue;
|
||||
}
|
||||
match this_role {
|
||||
Role::Editor => editors.push(person),
|
||||
_ => authors.push(person),
|
||||
}
|
||||
}
|
||||
}
|
||||
(authors, editors)
|
||||
}
|
||||
|
||||
/// Whether a candidate reads as a name rather than a line of a title: no
|
||||
/// little words ("Paths TO"), and no word left in capitals beside words that
|
||||
/// are not ("WISDOM’S Journey").
|
||||
pub(crate) fn reads_as_a_name(name: &str) -> bool {
|
||||
const LITTLE: &[&str] = &[
|
||||
"a", "an", "and", "for", "in", "of", "on", "the", "to", "with",
|
||||
];
|
||||
let words: Vec<&str> = name.split_whitespace().collect();
|
||||
if words
|
||||
.iter()
|
||||
.any(|w| LITTLE.contains(&w.to_lowercase().as_str()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let shouting = |w: &&str| {
|
||||
let letters: Vec<char> = w.chars().filter(|c| c.is_alphabetic()).collect();
|
||||
letters.len() > 3 && letters.iter().all(|c| c.is_uppercase())
|
||||
};
|
||||
!(words.iter().any(shouting) && !words.iter().all(shouting))
|
||||
}
|
||||
|
||||
fn filed_to_reading(line: &str) -> Option<String> {
|
||||
let caps = FILED_NAME.captures(line)?;
|
||||
Some(format!(
|
||||
@@ -272,3 +376,59 @@ pub fn read(front: &str) -> Option<Cip> {
|
||||
cip.isbns.dedup();
|
||||
if cip.is_empty() { None } else { Some(cip) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod people_tests {
|
||||
use super::people;
|
||||
|
||||
#[test]
|
||||
fn role_words_are_not_people() {
|
||||
for statement in [
|
||||
"edited by",
|
||||
"translated from the French",
|
||||
"selected and",
|
||||
"index",
|
||||
"ISSN 0920-",
|
||||
] {
|
||||
assert_eq!(people(statement), (vec![], vec![]), "{statement}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_names_are_read_and_the_roles_kept() {
|
||||
assert_eq!(
|
||||
people("Greg Palast. p. cm"),
|
||||
(vec!["Greg Palast".to_string()], vec![])
|
||||
);
|
||||
assert_eq!(
|
||||
people("Alan Carr.— 2nd ed"),
|
||||
(vec!["Alan Carr".to_string()], vec![])
|
||||
);
|
||||
assert_eq!(
|
||||
people("[edited by] Konrad H. Kinzl"),
|
||||
(vec![], vec!["Konrad H. Kinzl".to_string()])
|
||||
);
|
||||
assert_eq!(people("Paths TO"), (vec![], vec![]));
|
||||
assert_eq!(
|
||||
people("Irving B. Weiner, editor-in-chief"),
|
||||
(vec![], vec!["Irving B. Weiner".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
people("edited by Stanley Hauerwas and Samuel Wells"),
|
||||
(
|
||||
vec![],
|
||||
vec!["Stanley Hauerwas".to_string(), "Samuel Wells".to_string()]
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
people("by David W. Fischer and Alan E. Bessette ; foreword by Gary Lincoff"),
|
||||
(
|
||||
vec![
|
||||
"David W. Fischer".to_string(),
|
||||
"Alan E. Bessette".to_string()
|
||||
],
|
||||
vec![]
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,17 @@ pub struct Imprint {
|
||||
pub place: Option<String>,
|
||||
/// The year of this edition, preferring first publication.
|
||||
pub year: Option<u16>,
|
||||
/// Every checksum-valid ISBN printed on the page, in the order printed.
|
||||
/// Every checksum-valid ISBN printed on the page, the book's own first.
|
||||
///
|
||||
/// A page that lists the other titles in a series prints each of their
|
||||
/// ISBNs once, often before the book's own; the book's own is printed
|
||||
/// again in its cataloguing block and on its copyright line. So the
|
||||
/// ISBNs are ranked by how often the page prints them, and the order
|
||||
/// printed only breaks a tie.
|
||||
pub isbns: Vec<String>,
|
||||
/// What the page says about an ISBN, where it says something: "vol. 2",
|
||||
/// "hardback", "ebook". Keyed by the ISBN.
|
||||
pub notes: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
static PUBLISHED_BY: LazyLock<Regex> = LazyLock::new(|| {
|
||||
@@ -62,25 +71,69 @@ fn tidy(s: &str) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Every checksum-valid ISBN announced in a piece of text.
|
||||
/// Every checksum-valid ISBN announced in a piece of text, the most often
|
||||
/// printed first.
|
||||
pub fn isbns(text: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
stated(text).into_iter().map(|(isbn, _)| isbn).collect()
|
||||
}
|
||||
|
||||
/// The ISBNs a text announces, each with what is printed after it, ranked as
|
||||
/// [`Imprint::isbns`] says.
|
||||
fn stated(text: &str) -> Vec<(String, Option<String>)> {
|
||||
// (isbn, times printed, first printed at, note)
|
||||
let mut seen: Vec<(String, usize, usize, Option<String>)> = Vec::new();
|
||||
for caps in ISBN.captures_iter(text) {
|
||||
let digits = bibclean::isbn::digits(&caps[1]);
|
||||
if matches!(digits.len(), 10 | 13)
|
||||
&& bibclean::isbn::valid(&digits)
|
||||
&& !out.contains(&digits)
|
||||
{
|
||||
out.push(digits);
|
||||
if !(matches!(digits.len(), 10 | 13) && bibclean::isbn::valid(&digits)) {
|
||||
continue;
|
||||
}
|
||||
let end = caps.get(0).map_or(0, |whole| whole.end());
|
||||
let note = note_after(&text[end..]);
|
||||
match seen.iter_mut().find(|(isbn, ..)| *isbn == digits) {
|
||||
Some(entry) => {
|
||||
entry.1 += 1;
|
||||
if entry.3.is_none() {
|
||||
entry.3 = note;
|
||||
}
|
||||
}
|
||||
None => seen.push((digits, 1, end, note)),
|
||||
}
|
||||
}
|
||||
out
|
||||
seen.sort_by(|a, b| b.1.cmp(&a.1).then(a.2.cmp(&b.2)));
|
||||
seen.into_iter()
|
||||
.map(|(isbn, _, _, note)| (isbn, note))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// "(vol. 2, doml 29: alk. paper)", "hardback", "(pbk.)": what follows an
|
||||
/// ISBN on its line, up to the next ISBN.
|
||||
fn note_after(rest: &str) -> Option<String> {
|
||||
let line = rest.split('\n').next().unwrap_or("");
|
||||
let line = match line.to_lowercase().find("isbn") {
|
||||
Some(at) => &line[..at],
|
||||
None => line,
|
||||
};
|
||||
let note = line
|
||||
.trim_start_matches(|c: char| c.is_whitespace() || c == '(' || c == '-' || c == '–')
|
||||
.split(')')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.trim_end_matches([',', ';', '.', '–', '-'])
|
||||
.trim();
|
||||
let has_words = note.chars().filter(|c| c.is_alphabetic()).count() >= 2;
|
||||
(has_words && note.chars().count() <= 60).then(|| note.to_string())
|
||||
}
|
||||
|
||||
/// Read the copyright page.
|
||||
pub fn read(text: &str) -> Imprint {
|
||||
let found = stated(text);
|
||||
let mut out = Imprint {
|
||||
isbns: isbns(text),
|
||||
isbns: found.iter().map(|(isbn, _)| isbn.clone()).collect(),
|
||||
notes: found
|
||||
.into_iter()
|
||||
.filter_map(|(isbn, note)| note.map(|note| (isbn, note)))
|
||||
.collect(),
|
||||
..Imprint::default()
|
||||
};
|
||||
|
||||
@@ -111,3 +164,36 @@ pub fn read(text: &str) -> Imprint {
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_books_own_isbn_outranks_a_series_list() {
|
||||
let page = "Other titles in the series\n\
|
||||
THE CAMBRIDGE COMPANION TO CHRISTIAN DOCTRINE edited by Colin Gunton\n\
|
||||
ISBN 0 521 47118 4 hardback ISBN 0 521 47695 8 paperback\n\
|
||||
THE CAMBRIDGE COMPANION TO BIBLICAL INTERPRETATION edited by John Barton\n\
|
||||
ISBN 0 521 48144 9 hardback ISBN 0 521 48593 2 paperback\n\
|
||||
Library of Congress cataloguing in publication data\n\
|
||||
ISBN 0 521 48144 9 (hardback) – ISBN 0 521 48593 2 (paperback)\n\
|
||||
ISBN 0 521 48144 9 hardback\n";
|
||||
let found = read(page);
|
||||
assert_eq!(found.isbns[0], "0521481449");
|
||||
assert!(
|
||||
found
|
||||
.notes
|
||||
.contains(&("0521481449".to_string(), "hardback".to_string()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_volumes_isbn_keeps_its_note() {
|
||||
let page = "ISBN 978-0-674-72666-6 (vol. 1, doml 28 : alk. paper)\n\
|
||||
ISBN 978-0-674-73083-0 (vol. 2, doml 29: alk. paper)\n";
|
||||
let found = read(page);
|
||||
assert_eq!(found.isbns, ["9780674726666", "9780674730830"]);
|
||||
assert_eq!(found.notes[1].1, "vol. 2, doml 29: alk. paper");
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,45 @@ impl Printed {
|
||||
}
|
||||
}
|
||||
|
||||
/// "Volume II", "vol. 2", "Part Three": the number of the volume a text names.
|
||||
fn volume_of(text: &str) -> Option<u32> {
|
||||
static VOLUME: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
|
||||
regex::Regex::new(
|
||||
r"(?i)\b(?:vol(?:ume)?|part|book|tome|band)\.?\s*([0-9]{1,2}|[ivxlc]{1,6}|one|two|three|four|five|six|seven|eight|nine|ten)\b",
|
||||
)
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
let word = VOLUME.captures(text)?.get(1)?.as_str().to_lowercase();
|
||||
if let Ok(n) = word.parse() {
|
||||
return Some(n);
|
||||
}
|
||||
let words = [
|
||||
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
|
||||
];
|
||||
if let Some(at) = words.iter().position(|w| *w == word) {
|
||||
return u32::try_from(at + 1).ok();
|
||||
}
|
||||
let mut total = 0u32;
|
||||
let mut last = 0u32;
|
||||
for c in word.chars().rev() {
|
||||
let value = match c {
|
||||
'i' => 1,
|
||||
'v' => 5,
|
||||
'x' => 10,
|
||||
'l' => 50,
|
||||
'c' => 100,
|
||||
_ => return None,
|
||||
};
|
||||
if value < last {
|
||||
total = total.checked_sub(value)?;
|
||||
} else {
|
||||
total += value;
|
||||
last = value;
|
||||
}
|
||||
}
|
||||
(total > 0).then_some(total)
|
||||
}
|
||||
|
||||
/// Which page holds the title, given where the copyright page is.
|
||||
///
|
||||
/// The title page is the last page before the copyright page that is a page
|
||||
@@ -193,7 +232,10 @@ fn longest_printing<'a>(pages: &'a [page::Page], title: &str) -> Option<&'a str>
|
||||
.flat_map(|p| p.lines.iter())
|
||||
.filter(|line| {
|
||||
let candidate = squash(line);
|
||||
candidate.starts_with(&wanted) && candidate.len() > wanted.len()
|
||||
candidate.starts_with(&wanted)
|
||||
&& candidate.len() > wanted.len()
|
||||
&& !title::is_furniture(line)
|
||||
&& !title::is_structural(line)
|
||||
})
|
||||
.min_by_key(|line| line.len())
|
||||
.map(String::as_str)
|
||||
@@ -325,14 +367,45 @@ pub fn read(text: &str, budget: usize) -> Printed {
|
||||
|
||||
let imprint_text = copyright.map_or(front.as_str(), |i| pages[i].text.as_str());
|
||||
let stated = imprint::read(imprint_text);
|
||||
for isbn in stated.isbns {
|
||||
if !out.isbns.contains(&isbn) {
|
||||
out.isbns.push(isbn);
|
||||
// ISBNs are ranked over the whole front matter, not the one page taken
|
||||
// for the copyright page: a page listing the series' other titles is
|
||||
// full of ISBNs and is taken for it, and on that page alone every ISBN
|
||||
// is printed once.
|
||||
let ranked = imprint::read(&front);
|
||||
for isbn in &ranked.isbns {
|
||||
if !out.isbns.contains(isbn) {
|
||||
out.isbns.push(isbn.clone());
|
||||
out.read_from
|
||||
.entry("isbns".into())
|
||||
.or_insert(Source::CopyrightPage);
|
||||
}
|
||||
}
|
||||
// The page's own ranking, most often printed first, wins over the
|
||||
// cataloguing block's, which is only sorted.
|
||||
out.isbns.sort_by_key(|isbn| {
|
||||
ranked
|
||||
.isbns
|
||||
.iter()
|
||||
.position(|seen| seen == isbn)
|
||||
.unwrap_or(usize::MAX)
|
||||
});
|
||||
// A set prints every volume's ISBN in every volume. The one whose note
|
||||
// names this book's volume is this book's.
|
||||
let heading = format!(
|
||||
"{} {}",
|
||||
out.title.as_deref().unwrap_or(""),
|
||||
out.subtitle.as_deref().unwrap_or("")
|
||||
);
|
||||
if let Some(volume) = volume_of(&heading)
|
||||
&& let Some((isbn, _)) = ranked
|
||||
.notes
|
||||
.iter()
|
||||
.find(|(_, note)| volume_of(note) == Some(volume))
|
||||
&& let Some(at) = out.isbns.iter().position(|held| held == isbn)
|
||||
{
|
||||
let isbn = out.isbns.remove(at);
|
||||
out.isbns.insert(0, isbn);
|
||||
}
|
||||
if let Some(publisher) = stated.publisher {
|
||||
out.publisher = Some(publisher);
|
||||
out.note("publisher", Source::CopyrightPage);
|
||||
@@ -360,3 +433,20 @@ pub fn read(text: &str, budget: usize) -> Printed {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod volume_tests {
|
||||
use super::volume_of;
|
||||
|
||||
#[test]
|
||||
fn volume_numbers_are_read() {
|
||||
assert_eq!(
|
||||
volume_of("On Difficulties in the Church Fathers: The Ambigua, Volume II"),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(volume_of("vol. 2, doml 29: alk. paper"), Some(2));
|
||||
assert_eq!(volume_of("Part Three"), Some(3));
|
||||
assert_eq!(volume_of("Book XIV"), Some(14));
|
||||
assert_eq!(volume_of("The Book of Disquiet"), None);
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,48 @@ static CATALOGUE_ENTRY: LazyLock<Regex> = LazyLock::new(|| {
|
||||
static DEDICATION: LazyLock<Regex> = 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<Regex> = 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<Regex> = 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")
|
||||
});
|
||||
/// "For Tom, Burney, and Bruce", "TO JILL PREWETT AND", "For Anna P., of
|
||||
/// course.": a dedication, set alone on its page, that names somebody and
|
||||
/// then runs on or stops short.
|
||||
static DEDICATION_TO_SOMEONE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(
|
||||
r"^(?i:to|for)\s+\p{Lu}[\p{L}.'’-]*(?:\s+\p{Lu}[\p{L}.'’-]*)?(?:,|\s+(?i:and)\s*$|\.\s*$)",
|
||||
)
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
/// A library's ownership stamp: "Trent University Library".
|
||||
static LIBRARY_STAMP: LazyLock<Regex> = 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<Regex> = 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<Regex> = 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.
|
||||
@@ -136,7 +178,7 @@ static STRUCTURAL: &[&str] = &[
|
||||
"translator's note",
|
||||
];
|
||||
|
||||
fn is_structural(line: &str) -> bool {
|
||||
pub(crate) fn is_structural(line: &str) -> bool {
|
||||
let norm: String = line
|
||||
.chars()
|
||||
.filter(|c| c.is_alphanumeric() || c.is_whitespace())
|
||||
@@ -182,9 +224,11 @@ fn strip_folio(norm: &str) -> &str {
|
||||
/// a copyright notice, a translator's credit, a part heading in brackets, a
|
||||
/// span of HTML a converter left behind, and a volume entry from a collected
|
||||
/// edition's own list of volumes.
|
||||
fn is_furniture(line: &str) -> bool {
|
||||
pub(crate) 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,12 +268,79 @@ fn is_furniture(line: &str) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if DEDICATION.is_match(t) {
|
||||
// The headings of the pages before the text, and its first chapter.
|
||||
let heading = t.to_lowercase();
|
||||
if [
|
||||
"endorsements",
|
||||
"about the author",
|
||||
"about the authors",
|
||||
"author's preface",
|
||||
"author’s preface",
|
||||
"note on orthography",
|
||||
"note on the text",
|
||||
"note on the translation",
|
||||
"chapter one",
|
||||
"chapter 1",
|
||||
"dedicated to",
|
||||
"cover",
|
||||
"front cover",
|
||||
"back cover",
|
||||
]
|
||||
.contains(&heading.trim_end_matches(['.', ':']))
|
||||
|| heading.starts_with("books by ")
|
||||
|| heading.starts_with("also available")
|
||||
|| heading.starts_with("dedicated to ")
|
||||
|| DEDICATION_TO_SOMEONE.is_match(t)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
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();
|
||||
// What the pages around a title page carry about the edition, the
|
||||
// scan, the shop and the reviews, none of which is ever the title.
|
||||
for phrase in [
|
||||
"has asserted",
|
||||
"moral right of the author",
|
||||
"moral rights of the author",
|
||||
"library of congress control number",
|
||||
"this ebook was prepared",
|
||||
"ebook edition",
|
||||
"e-book edition",
|
||||
"kindle edition",
|
||||
" printing:",
|
||||
"printing, ",
|
||||
"revised and expanded edition",
|
||||
"registered office",
|
||||
"visit us online",
|
||||
"visit us at",
|
||||
"reviewers have said",
|
||||
"praise for",
|
||||
"a division of",
|
||||
"p.o. box",
|
||||
"po box",
|
||||
"award winner",
|
||||
"reproduction of a library book",
|
||||
"digitized by",
|
||||
"was digitized",
|
||||
"with funding from",
|
||||
"kahle/austin",
|
||||
"trademarks of",
|
||||
"all rights reserved",
|
||||
"no part of this book",
|
||||
"isbn",
|
||||
"no part of this publication",
|
||||
"british library cataloguing",
|
||||
"library of congress cataloging",
|
||||
@@ -266,14 +377,59 @@ fn is_furniture(line: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The people a byline names, each held to the shape of a person's name:
|
||||
/// a title page sets a series name or a line of the title in the same
|
||||
/// capitals as its author ("MARESFIELD LIBRARY", "A BASIC THEORY OF").
|
||||
fn people(who: &str) -> Vec<String> {
|
||||
who.split(&[';', '&'][..])
|
||||
.flat_map(|part| part.split(" and "))
|
||||
.map(|name| name.trim().trim_end_matches(['.', ',']).trim().to_string())
|
||||
.filter(|name| name.len() >= 3 && name.split_whitespace().count() <= 5)
|
||||
// "A Novel", "A History": an article opens a line of the title, and
|
||||
// would otherwise be read as the initial A.
|
||||
.filter(|name| {
|
||||
let first = name.split_whitespace().next().unwrap_or("");
|
||||
!["a", "an", "the"].contains(&first.to_lowercase().as_str())
|
||||
})
|
||||
.filter_map(|name| bibclean::author::clean(&name))
|
||||
.filter(|name| crate::cip::reads_as_a_name(name))
|
||||
.filter(|name| name.split_whitespace().count() >= 2 || is_known_mononym(name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A single name is a person only where it is one of the handful that go by
|
||||
/// one: anything else alone on a byline line is a word of the title.
|
||||
fn is_known_mononym(name: &str) -> bool {
|
||||
const MONONYMS: &[&str] = &[
|
||||
"Aeschylus",
|
||||
"Aristotle",
|
||||
"Augustine",
|
||||
"Cicero",
|
||||
"Dante",
|
||||
"Epictetus",
|
||||
"Euripides",
|
||||
"Herodotus",
|
||||
"Hesiod",
|
||||
"Homer",
|
||||
"Josephus",
|
||||
"Livy",
|
||||
"Lucretius",
|
||||
"Ovid",
|
||||
"Plato",
|
||||
"Plotinus",
|
||||
"Plutarch",
|
||||
"Proclus",
|
||||
"Seneca",
|
||||
"Sophocles",
|
||||
"Tacitus",
|
||||
"Thucydides",
|
||||
"Virgil",
|
||||
"Voltaire",
|
||||
"Xenophon",
|
||||
];
|
||||
MONONYMS.contains(&name)
|
||||
}
|
||||
|
||||
/// Words a line ends on when the typesetter broke a title across it.
|
||||
///
|
||||
/// `Esotericism in` / `Western Culture` is one title set on two lines, and
|
||||
@@ -304,6 +460,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 +534,11 @@ pub fn read(lines: &[String]) -> Option<TitlePage> {
|
||||
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 +636,48 @@ 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",
|
||||
"For Tom, Burney, and Bruce",
|
||||
"TO JILL PREWETT AND",
|
||||
"For Anna P., of course.",
|
||||
"To Michel Callon, this outcome of a seven-year discussion",
|
||||
"ENDORSEMENTS",
|
||||
"About the Authors",
|
||||
"Books by Arthur C. Clarke",
|
||||
"Author's Preface",
|
||||
"CHAPTER ONE",
|
||||
"J.K. Rowling has asserted her moral rights",
|
||||
"Library of Congress Control Number: 2007932082",
|
||||
"This eBook was prepared by Matthew Stapleton.",
|
||||
"E-book edition created 2011",
|
||||
"Third printing: August 2010",
|
||||
"Revised and Expanded Edition 2022",
|
||||
"Hugo Award Winner, Locus Poll Award Nominee",
|
||||
"This is a reproduction of a library book that was digitized",
|
||||
"in 2023 with funding from Kahle/Austin Foundation",
|
||||
"Humanix Books, P.O. Box 20989, West Palm Beach, FL 33416",
|
||||
"AVON BOOKS: A division of",
|
||||
"Or visit us online at",
|
||||
"What Reviewers Have Said About",
|
||||
"ISBN: 0-89555-315-5",
|
||||
] {
|
||||
assert!(
|
||||
is_structural(line) || is_furniture(line),
|
||||
@@ -486,6 +697,19 @@ 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",
|
||||
"To the Lighthouse",
|
||||
"For the Love of God",
|
||||
"To Have and Have Not",
|
||||
"The Cover-Up",
|
||||
] {
|
||||
assert!(
|
||||
!(is_structural(line) || is_furniture(line)),
|
||||
@@ -505,6 +729,59 @@ mod furniture_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod part_tests {
|
||||
use super::*;
|
||||
|
||||
fn lines(text: &[&str]) -> Vec<String> {
|
||||
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 a_line_opening_on_an_article_names_nobody() {
|
||||
assert!(people("A Novel").is_empty());
|
||||
assert!(people("A Psychoanalytic View").is_empty());
|
||||
assert_eq!(people("A. J. Ayer"), ["A. J. Ayer"]);
|
||||
}
|
||||
|
||||
#[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::*;
|
||||
|
||||
@@ -30,6 +30,8 @@ pub const UNAVAILABLE: u8 = 69;
|
||||
pub const SOFTWARE: u8 = 70;
|
||||
/// Reading or writing failed.
|
||||
pub const IO: u8 = 74;
|
||||
/// A service refused for now, and asking again later will work.
|
||||
pub const TEMPFAIL: u8 = 75;
|
||||
|
||||
/// The answer a predicate tool gives.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! An ISBN's two forms, ten digits and thirteen.
|
||||
//!
|
||||
//! A book printed before 2007 carries a ten-digit ISBN, one printed since
|
||||
//! carries thirteen, and every ten-digit one has a thirteen-digit twin: `978`
|
||||
//! in front and the check digit worked out again. A catalogue may file a
|
||||
//! book under either, so asking about one form and not the other misses
|
||||
//! books that are there.
|
||||
//!
|
||||
//! Only a well-formed ISBN is converted. Working out a fresh check digit for
|
||||
//! one whose own check digit is wrong would not correct the typing error, it
|
||||
//! would turn the number into a different book's.
|
||||
|
||||
/// Just the digits of an ISBN, with a check character of ten as `X`.
|
||||
pub fn digits(text: &str) -> String {
|
||||
bibclean::isbn::digits(text).to_ascii_uppercase()
|
||||
}
|
||||
|
||||
/// The thirteen-digit form of an ISBN, from either form.
|
||||
///
|
||||
/// `None` when the text is not an ISBN whose check digit agrees.
|
||||
pub fn to_13(text: &str) -> Option<String> {
|
||||
let digits = digits(text);
|
||||
if !bibclean::isbn::valid(&digits) {
|
||||
return None;
|
||||
}
|
||||
match digits.len() {
|
||||
13 => Some(digits),
|
||||
10 => {
|
||||
let body = format!("978{}", &digits[..9]);
|
||||
let sum: u32 = body
|
||||
.bytes()
|
||||
.enumerate()
|
||||
.map(|(at, b)| u32::from(b - b'0') * if at % 2 == 0 { 1 } else { 3 })
|
||||
.sum();
|
||||
Some(format!("{body}{}", (10 - sum % 10) % 10))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ten-digit form of an ISBN, from either form.
|
||||
///
|
||||
/// `None` when the text is not an ISBN whose check digit agrees, or when it
|
||||
/// is a thirteen-digit one starting `979`, which was never issued in ten.
|
||||
pub fn to_10(text: &str) -> Option<String> {
|
||||
let digits = digits(text);
|
||||
if !bibclean::isbn::valid(&digits) {
|
||||
return None;
|
||||
}
|
||||
match digits.len() {
|
||||
10 => Some(digits),
|
||||
13 if digits.starts_with("978") => {
|
||||
let body = &digits[3..12];
|
||||
let sum: u32 = body
|
||||
.bytes()
|
||||
.enumerate()
|
||||
.map(|(at, b)| u32::from(b - b'0') * (10 - at as u32))
|
||||
.sum();
|
||||
let check = match (11 - sum % 11) % 11 {
|
||||
10 => 'X',
|
||||
n => char::from(b'0' + n as u8),
|
||||
};
|
||||
Some(format!("{body}{check}"))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_form_becomes_the_other() {
|
||||
assert_eq!(to_13("0-306-40615-2").as_deref(), Some("9780306406157"));
|
||||
assert_eq!(to_10("978-0-306-40615-7").as_deref(), Some("0306406152"));
|
||||
assert_eq!(to_13("9780306406157").as_deref(), Some("9780306406157"));
|
||||
assert_eq!(to_10("0306406152").as_deref(), Some("0306406152"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_digit_of_ten_is_written_x() {
|
||||
assert_eq!(to_10("9780804429573").as_deref(), Some("080442957X"));
|
||||
assert_eq!(to_13("080442957x").as_deref(), Some("9780804429573"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_979_isbn_has_no_ten_digit_form() {
|
||||
assert_eq!(to_10("979-10-90636-07-1"), None);
|
||||
assert_eq!(to_13("979-10-90636-07-1").as_deref(), Some("9791090636071"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mistyped_isbn_is_not_converted_into_a_different_book() {
|
||||
assert_eq!(to_13("0-306-40615-3"), None);
|
||||
assert_eq!(to_10("978-0-306-40615-8"), None);
|
||||
assert_eq!(to_13("12345"), None);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
pub mod arxiv;
|
||||
pub mod doi;
|
||||
pub mod isbn;
|
||||
pub mod issn;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
|
||||
@@ -98,6 +98,17 @@ with its thirty commonest function words. The score is the share of a text's
|
||||
words found in each list, and the lists are the same length so the scores
|
||||
compare.
|
||||
|
||||
**Markup is not language.** HTML comments such as page markers, and the
|
||||
targets of markdown links and images, are left out before anything is
|
||||
counted: an image named by a hash reads as a run of two-letter words.
|
||||
|
||||
**Letter-spaced type is read by its whole words.** A scan of type set
|
||||
letter-spaced comes out of OCR as "w i t h" and "n o t". Single letters are
|
||||
not words of any language, but "a", "e", "o" and "y" are among the commonest
|
||||
words of several, so when more than a quarter of the words are single letters
|
||||
they are left out. If what remains is mostly one- and two-letter fragments, as
|
||||
text decoded with the wrong font table is, there is no answer.
|
||||
|
||||
**A close call is no answer.** The winner must be a quarter ahead of the
|
||||
runner-up. `de` is among the commonest words of four languages at once, and on
|
||||
its own settles none of them — so a text that short comes back with the script
|
||||
|
||||
@@ -66,6 +66,7 @@ impl corpus_core::Record for Verdict {
|
||||
/// Read a text's language.
|
||||
pub fn detect(path: &str, text: &str) -> Verdict {
|
||||
let sample: String = text.chars().take(SAMPLE_CHARS).collect();
|
||||
let sample = prose(&sample);
|
||||
let (script, share) = script::detect(&sample);
|
||||
|
||||
let mut verdict = Verdict {
|
||||
@@ -135,6 +136,36 @@ pub fn detect(path: &str, text: &str) -> Verdict {
|
||||
verdict
|
||||
}
|
||||
|
||||
/// The text without the markup that is no language: HTML comments such as
|
||||
/// page markers, and the targets of markdown links and images, whose file
|
||||
/// names and hashes read as words.
|
||||
fn prose(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
loop {
|
||||
let comment = rest.find("<!--");
|
||||
let target = rest.find("](");
|
||||
let (at, open, close) = match (comment, target) {
|
||||
(Some(c), Some(t)) if t < c => (t, 2, ")"),
|
||||
(Some(c), _) => (c, 4, "-->"),
|
||||
(None, Some(t)) => (t, 2, ")"),
|
||||
(None, None) => break,
|
||||
};
|
||||
out.push_str(&rest[..at]);
|
||||
out.push(' ');
|
||||
let after = &rest[at + open..];
|
||||
match after.find(close) {
|
||||
Some(end) => rest = &after[end + close.len()..],
|
||||
None => {
|
||||
rest = "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The one language a script is used for, where there is only one.
|
||||
fn sole_language(script: Script) -> Option<(&'static str, &'static str, &'static str)> {
|
||||
Some(match script {
|
||||
@@ -180,6 +211,20 @@ mod tests {
|
||||
assert!(found.confidence > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_markers_and_image_hashes_are_not_read() {
|
||||
assert_eq!(
|
||||
prose("one <!-- Page 7 --> two  three [x](y.html) four"),
|
||||
"one two  ".repeat(40);
|
||||
let found = detect(
|
||||
"x.md",
|
||||
&format!("{hashes} The Wall: Growing Up Behind the Iron Curtain"),
|
||||
);
|
||||
assert_ne!(found.language.as_deref(), Some("la"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_only_one_language_uses_needs_no_words() {
|
||||
for (text, code) in [
|
||||
|
||||
@@ -215,7 +215,26 @@ pub const MARGIN: f64 = 1.25;
|
||||
/// commonest. It is comparable across languages because each list is the same
|
||||
/// length.
|
||||
pub fn score(text: &str, script: Script) -> Vec<(&'static Language, f64)> {
|
||||
let words = tokens(text);
|
||||
let mut words = tokens(text);
|
||||
// Scanned type set letter-spaced comes out of OCR as "w i t h" and
|
||||
// "n o t": the letters are not words of any language, but "a", "e", "o"
|
||||
// and "y" are among the commonest words of several, which hands the text
|
||||
// to whichever has most of them. Ordinary prose is a few percent single
|
||||
// letters; past a quarter they are spacing and are left out.
|
||||
let singles = words
|
||||
.iter()
|
||||
.filter(|word| word.chars().count() == 1)
|
||||
.count();
|
||||
if singles * 4 > words.len() {
|
||||
words.retain(|word| word.chars().count() > 1);
|
||||
// Most of what is left of real prose has three letters or more;
|
||||
// text decoded with the wrong font table leaves mostly pairs like
|
||||
// "gf" and "hg", which are no language however they score.
|
||||
let long = words.iter().filter(|word| word.chars().count() > 2).count();
|
||||
if long * 2 < words.len() {
|
||||
words.clear();
|
||||
}
|
||||
}
|
||||
if words.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -294,6 +313,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letter_spaced_scanning_is_read_by_its_whole_words() {
|
||||
let text = "charges. Smith said the young man's family was grateful to h i m \
|
||||
for guidance he gave. Smith always managed to get o u t o f bad situations. \
|
||||
But he could n o t stop his body clock. I felt m o r e at ease after the crises w i t h \
|
||||
work passed, and Smith continued working. I t d i d n o t occur to me that he had \
|
||||
come to therapy to die. He seemed to be battling f o r life. T o me, Smith seemed";
|
||||
assert_eq!(best(text, Script::Latin), Some("en"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrongly_decoded_font_is_no_language() {
|
||||
let text = "9G::99$>9$4?FH>6$H3:999$3$ 9H:>>:@>6 >6@30?>6$F9B$3@9$64$H34G:@9 3W:@$;64$0>@5$9@36$ \
|
||||
3:99$;64$0>@5$9@36$;H59>9$6$ 3XG>3;6@$@$;6>@3$:6@3:@3 4>FG$64$W>6@$H37F;$9F gf hg ab fa ff ge ea \
|
||||
ABCDEBFGHFAIJKFLEMNCEOFPJQMEKREFASFPHKKFTMSOFJKBFUVMCWDXYVEMFZXNNCDD page ba aa cb";
|
||||
assert_eq!(best(text, Script::Latin), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cyrillic_pair_are_told_apart() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -18,13 +18,19 @@
|
||||
//! numbered, so filing one under a numbered series makes every one of them
|
||||
//! display as volume one, asserting an order the data does not have. Those
|
||||
//! get a series and no number.
|
||||
//!
|
||||
//! A **numbered title** — "Known Space-038-The Soft Weapon" — is a position
|
||||
//! written the way a filename writes it, series and number in front. It
|
||||
//! gives the series, the number, and the title with both taken off.
|
||||
|
||||
pub mod numbered;
|
||||
pub mod publisher;
|
||||
pub mod volume;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use numbered::parse_numbered;
|
||||
pub use publisher::publisher_series;
|
||||
pub use volume::{parse_volume, roman_or_int};
|
||||
|
||||
@@ -60,6 +66,9 @@ pub enum Method {
|
||||
Volume,
|
||||
/// Publisher shorthand in a parenthetical: membership, not position.
|
||||
Publisher,
|
||||
/// A series and a number written in front of the title, filename
|
||||
/// fashion: a position, and the title without them.
|
||||
Numbered,
|
||||
}
|
||||
|
||||
fn version() -> u32 {
|
||||
@@ -74,9 +83,25 @@ impl corpus_core::Record for Proposal {
|
||||
|
||||
/// What a title and author say about the series, if anything.
|
||||
///
|
||||
/// The volume marker is looked for first: it carries a number, and a number
|
||||
/// is worth more than membership.
|
||||
/// A numbered title is looked for first, then a volume marker: both carry a
|
||||
/// number, and a number is worth more than membership.
|
||||
pub fn series_of(title: &str, author: Option<&str>) -> Option<Proposal> {
|
||||
// A numbered title first: "Known Space-017-The Ethics of Madness (Part
|
||||
// 1)" is the seventeenth of Known Space, and the "Part 1" after it is the
|
||||
// story's own business, not a series called "Known Space-017-The Ethics
|
||||
// of Madness".
|
||||
if let Some((series, volume, rest)) = parse_numbered(title) {
|
||||
return Some(Proposal {
|
||||
v: corpus_core::V,
|
||||
title: title.to_string(),
|
||||
author: author.map(str::to_string),
|
||||
series,
|
||||
volume: Some(volume),
|
||||
proposed_title: Some(rest),
|
||||
method: Method::Numbered,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some((series, volume)) = parse_volume(title) {
|
||||
return Some(Proposal {
|
||||
v: corpus_core::V,
|
||||
@@ -132,6 +157,19 @@ mod tests {
|
||||
assert_eq!(found.volume, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_numbered_title_wins_over_a_part_inside_it() {
|
||||
let found =
|
||||
series_of("Known Space-017-The Ethics of Madness (Part 1)", None).expect("a series");
|
||||
assert_eq!(found.series, "Known Space");
|
||||
assert_eq!(found.volume, Some(17));
|
||||
assert_eq!(found.method, Method::Numbered);
|
||||
assert_eq!(
|
||||
found.proposed_title.as_deref(),
|
||||
Some("The Ethics of Madness (Part 1)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_title_proposes_nothing() {
|
||||
assert_eq!(series_of("Being and Time", Some("Heidegger")), None);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! A series and a number written in front of the title, as a filename
|
||||
//! writes them: "Known Space-038-The Soft Weapon", "Ice and Fire 2 - A Clash
|
||||
//! of Kings", "James Bond - 032 - Blast from the Past".
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use fancy_regex::Regex;
|
||||
|
||||
use crate::volume::roman_or_int;
|
||||
|
||||
/// The series, the number between separators, then the title. The number
|
||||
/// has to stand between separators on both sides, so "The 200-Year Plot"
|
||||
/// and "The 12-Month Gardener" are titles with numbers in them, not
|
||||
/// numbered titles.
|
||||
static NUMBERED: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(
|
||||
r"^(?P<series>[\p{L}][^:\d]{1,60}?)(?:\s+(?P<a>\d{1,3})\s+[-–—.]\s+|\s*[-–—]\s*(?P<b>\d{1,3})\s*[-–—]\s*)(?P<title>\p{Lu}.*)$",
|
||||
)
|
||||
.expect("a valid pattern")
|
||||
});
|
||||
|
||||
/// A series name, a volume and the title without them, or `None` when the
|
||||
/// title does not open that way.
|
||||
pub fn parse_numbered(title: &str) -> Option<(String, u32, String)> {
|
||||
let found = NUMBERED.captures(title.trim()).ok().flatten()?;
|
||||
let series = found["series"].trim_matches(|c: char| c.is_whitespace() || "-–—".contains(c));
|
||||
if series.split_whitespace().count() > 6 || !series.chars().any(char::is_alphabetic) {
|
||||
return None;
|
||||
}
|
||||
// "00 - The Hedge Knight": a prequel numbered zero is still in the
|
||||
// series, and zero is its place.
|
||||
let number = found.name("a").or_else(|| found.name("b"))?.as_str();
|
||||
let volume = if number.chars().all(|c| c == '0') {
|
||||
0
|
||||
} else {
|
||||
roman_or_int(number)?
|
||||
};
|
||||
let rest = found["title"].trim().trim_end_matches('.').trim();
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((series.to_string(), volume, rest.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_numbered_title_gives_series_volume_and_title() {
|
||||
for (title, series, volume, rest) in [
|
||||
(
|
||||
"Known Space-038-The Soft Weapon",
|
||||
"Known Space",
|
||||
38,
|
||||
"The Soft Weapon",
|
||||
),
|
||||
(
|
||||
"Ice and Fire 2 - A Clash of Kings",
|
||||
"Ice and Fire",
|
||||
2,
|
||||
"A Clash of Kings",
|
||||
),
|
||||
(
|
||||
"Ice and Fire 00 - The Hedge Knight",
|
||||
"Ice and Fire",
|
||||
0,
|
||||
"The Hedge Knight",
|
||||
),
|
||||
(
|
||||
"James Bond - 032 - Blast from the Past",
|
||||
"James Bond",
|
||||
32,
|
||||
"Blast from the Past",
|
||||
),
|
||||
("Time Odyssey 2 - Sunstorm", "Time Odyssey", 2, "Sunstorm"),
|
||||
(
|
||||
"Known Space-040-Destroyer of Worlds.",
|
||||
"Known Space",
|
||||
40,
|
||||
"Destroyer of Worlds",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
parse_numbered(title),
|
||||
Some((series.to_string(), volume, rest.to_string())),
|
||||
"{title}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_with_a_number_in_it_is_not_numbered() {
|
||||
for title in [
|
||||
"Infiltration: The 200-Year Plot to Destroy the Catholic Church",
|
||||
"The 12-Month Vegetable Gardener's Handbook",
|
||||
"The Cambridge History of Medieval Political Thought C.350-C.1450",
|
||||
"The Chronicles of Narnia Complete 7-Book Collection",
|
||||
"CUUS309-FM p1-16",
|
||||
"01 - The Three Musketeers",
|
||||
"Being and Time",
|
||||
] {
|
||||
assert_eq!(parse_numbered(title), None, "{title}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> {
|
||||
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<String> {
|
||||
if text.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let bytes = text.chars().map(byte_of).collect::<Option<Vec<u8>>>()?;
|
||||
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<u8> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -47,6 +47,7 @@ that was concatenated or written on Windows still reads.
|
||||
| `69` | A program it needs is not installed |
|
||||
| `70` | Its own fault |
|
||||
| `74` | Reading or writing failed |
|
||||
| `75` | A service refused for now; try again later |
|
||||
|
||||
Failures start where `sysexits.h` puts them, so "no" and "broke" are never the
|
||||
same number. That is what makes this work:
|
||||
@@ -64,7 +65,7 @@ No network, no database, no configuration file, no state kept between runs.
|
||||
Five exceptions, each declared in `--help`:
|
||||
|
||||
- [`emb`](../crates/emb/README.md) makes an HTTP call, which is the whole of what it does.
|
||||
- [`bibfetch`](../crates/bibfetch/README.md) asks a register about an identifier, likewise.
|
||||
- [`bibfetch`](../crates/bibfetch/README.md) asks a register about an identifier or a title, likewise.
|
||||
- [`pdftriage`](../crates/pdftriage/README.md) runs `pdftotext` and `pdfinfo`.
|
||||
- [`pdfgutter`](../crates/pdfgutter/README.md) runs `pdftoppm` to look at a page.
|
||||
- [`avplan`](../crates/avplan/README.md) runs `ffprobe` to read a file's streams, and
|
||||
|
||||
@@ -20,6 +20,7 @@ to any of them is a change to a decision rather than to an accident.
|
||||
- [pdfgutter — a page tree that does not add up is refused](#pdfgutter--a-page-tree-that-does-not-add-up-is-refused)
|
||||
- [pdfgutter — a sheet on its side is cut the way it is read](#pdfgutter--a-sheet-on-its-side-is-cut-the-way-it-is-read)
|
||||
- [pdfgutter — an unreadable file is an answer, not a false](#pdfgutter--an-unreadable-file-is-an-answer-not-a-false)
|
||||
- [bookmeta — a cover is what its bytes say it is](#bookmeta--a-cover-is-what-its-bytes-say-it-is)
|
||||
- [Every pattern — two regex engines, two Unicode tables](#every-pattern--two-regex-engines-two-unicode-tables)
|
||||
|
||||
## cuenorm — settings after the end time are the format, not a malformation
|
||||
@@ -243,6 +244,23 @@ answers, and the [contract](contract.md) gives them three different numbers. A
|
||||
caller wanting them collapsed treats 1 and 2 alike; a caller wanting to know
|
||||
which files it failed on can now find out.
|
||||
|
||||
## bookmeta — a cover is what its bytes say it is
|
||||
|
||||
An EPUB's manifest gives every image a media type, and the cover's is not
|
||||
used: the type comes from the image's first bytes, and a disagreement is a
|
||||
note. Elsewhere `bookmeta` reports what the file says rather than what is
|
||||
true, and this is the one place it does not.
|
||||
|
||||
The difference is that a title nobody believes is still a title, while a
|
||||
media type that is wrong is an image that does not open. A caller handed
|
||||
`image/png` for a JPEG writes `cover.png`, serves it as PNG, or hands it to a
|
||||
decoder that refuses it. An image can be replaced by a converter or by hand
|
||||
without its manifest entry changing, and the note keeps what the file said,
|
||||
so nothing is lost by correcting it.
|
||||
|
||||
The same reasoning goes the other way: bytes that are not an image are not a
|
||||
cover, whatever the manifest calls them.
|
||||
|
||||
## Every pattern — two regex engines, two Unicode tables
|
||||
|
||||
Patterns here spell their character classes explicitly rather than leaning on
|
||||
|
||||
Generated
+9
-9
@@ -75,7 +75,7 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bibclean"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -107,7 +107,7 @@ checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "booksniff"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -129,7 +129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "catena-cli"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_mangen",
|
||||
@@ -150,7 +150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "chunkmd"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -162,7 +162,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "citefind"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"chunkmd",
|
||||
@@ -233,7 +233,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "corpus-core"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
@@ -283,7 +283,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "idnorm"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"bibclean",
|
||||
"catena-cli",
|
||||
@@ -315,7 +315,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "mdscrub"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"catena-cli",
|
||||
"clap",
|
||||
@@ -514,7 +514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "textkit"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"tiktoken-rs",
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user