Find a number for books the catalogues have no LC number for
Google Books joins Open Library and the Library of Congress as a source of title, authors, publisher and categories when no number is in hand. The similar-books tier widens its search step by step (other word forms, place and topic words from the subtitle and publisher, fewer words) when the first search finds no class, and needs at least two agreeing books before it accepts one. The result is marked approximate. Books with no number or an approximate one are looked up again at startup once the last lookup is a week old. An ISBN no catalogue knows that is within three digits of a book already here says it may be a misread of that book. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
ddf6020731
commit
a08fbff685
21 files changed
+750
-30
No files matched your search
@@ -150,3 +150,24 @@ test('edition: NULL means not looked up, empty means none, text is kept as given
|
||||
assert.deepEqual(db.listEditionMissingIds(), [a.id]);
|
||||
db.close();
|
||||
});
|
||||
|
||||
test('a database made before lookups were timestamped gets the column, and its finished books take the time of their last change', async () => {
|
||||
const { mkdtempSync } = await import('node:fs');
|
||||
const { tmpdir } = await import('node:os');
|
||||
const { DatabaseSync } = await import('node:sqlite');
|
||||
const path = `${mkdtempSync(`${tmpdir()}/bs-`)}/old.db`;
|
||||
const old = new DatabaseSync(path);
|
||||
old.exec(`CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, isbn13 TEXT UNIQUE, lccn TEXT, title TEXT NOT NULL, subtitle TEXT,
|
||||
authors TEXT NOT NULL DEFAULT '[]', publisher TEXT, year INTEGER, subjects TEXT NOT NULL DEFAULT '[]', call_number TEXT, sort_key TEXT,
|
||||
confidence TEXT, source TEXT, dewey TEXT, status TEXT NOT NULL DEFAULT 'pending', attention_reason TEXT, manual_override INTEGER NOT NULL DEFAULT 0,
|
||||
in_queue INTEGER NOT NULL DEFAULT 0, printed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
INSERT INTO books (isbn13, title, status, created_at, updated_at) VALUES ('9780000000001', 'a', 'needs_attention', '2026-01-01T00:00:00Z', '2026-02-02T00:00:00Z');
|
||||
INSERT INTO books (isbn13, title, status, created_at, updated_at) VALUES ('9780000000002', 'b', 'pending', '2026-01-01T00:00:00Z', '2026-02-03T00:00:00Z');`);
|
||||
old.close();
|
||||
const db = openDb(path);
|
||||
assert.equal(db.findByIsbn('9780000000001')!.lookedUpAt, '2026-02-02T00:00:00Z');
|
||||
assert.equal(db.findByIsbn('9780000000002')!.lookedUpAt, null);
|
||||
assert.deepEqual(db.listRecheckIds('2026-03-01T00:00:00Z'), [db.findByIsbn('9780000000001')!.id]);
|
||||
assert.deepEqual(db.listRecheckIds('2026-02-01T00:00:00Z'), []);
|
||||
db.close();
|
||||
});
|
||||
+23
-5
@@ -13,7 +13,7 @@ export interface NewBook {
|
||||
authors?: string[]; publisher?: string | null; year?: number | null; subjects?: string[];
|
||||
callNumber?: string | null; sortKey?: string | null; confidence?: Confidence | null;
|
||||
source?: Source | null; dewey?: string | null; status?: Status; attentionReason?: string | null;
|
||||
manualOverride?: boolean; inQueue?: boolean; hierarchyTail?: string[] | null; edition?: string | null;
|
||||
manualOverride?: boolean; inQueue?: boolean; hierarchyTail?: string[] | null; edition?: string | null; lookedUpAt?: string | null;
|
||||
}
|
||||
export type BookPatch = Partial<Omit<Book, 'id' | 'createdAt' | 'updatedAt' | 'retry'>>;
|
||||
export type Filter = 'all' | 'queue' | 'attention';
|
||||
@@ -33,6 +33,11 @@ export interface Db {
|
||||
* timeout, 5xx, block page): they go back to pending, not hand-entered ones. Returns how many.
|
||||
*/
|
||||
requeueTemporaryFailures(): number;
|
||||
/**
|
||||
* Books worth asking the catalogues about again, since they add records: not pending, not hand-entered, with no number
|
||||
* or only an approximate one, and last looked up before `before` (an ISO time). Oldest first.
|
||||
*/
|
||||
listRecheckIds(before: string): number[];
|
||||
/** Books that are not pending and whose hierarchy tail has not been looked for yet. */
|
||||
listTailMissingIds(): number[];
|
||||
/** Books that are not pending and whose edition has not been looked for yet (NULL). */
|
||||
@@ -56,6 +61,7 @@ const COLUMNS: Record<keyof BookPatch, string> = {
|
||||
sortKey: 'sort_key', confidence: 'confidence', source: 'source', dewey: 'dewey',
|
||||
status: 'status', attentionReason: 'attention_reason', manualOverride: 'manual_override',
|
||||
inQueue: 'in_queue', printedAt: 'printed_at', hierarchyTail: 'hierarchy_tail', edition: 'edition',
|
||||
lookedUpAt: 'looked_up_at',
|
||||
};
|
||||
const JSON_FIELDS = new Set(['authors', 'subjects']);
|
||||
const BOOL_FIELDS = new Set(['manualOverride', 'inQueue']);
|
||||
@@ -76,7 +82,7 @@ function toBook(r: Row): Book {
|
||||
attentionReason: r.attention_reason, manualOverride: !!r.manual_override,
|
||||
inQueue: !!r.in_queue, printedAt: r.printed_at, createdAt: r.created_at, updatedAt: r.updated_at,
|
||||
hierarchyTail: r.hierarchy_tail == null ? null : JSON.parse(r.hierarchy_tail),
|
||||
edition: r.edition ?? null,
|
||||
edition: r.edition ?? null, lookedUpAt: r.looked_up_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -124,12 +130,18 @@ export function openDb(path: string): Db {
|
||||
db.exec('ALTER TABLE books ADD COLUMN edition TEXT');
|
||||
}
|
||||
|
||||
// Likewise for when the catalogues were last asked. Books made before it was kept take the time of their last change.
|
||||
if (!(db.prepare('PRAGMA table_info(books)').all() as Row[]).some((c) => c.name === 'looked_up_at')) {
|
||||
db.exec('ALTER TABLE books ADD COLUMN looked_up_at TEXT');
|
||||
db.exec("UPDATE books SET looked_up_at = updated_at WHERE status != 'pending'");
|
||||
}
|
||||
|
||||
const getById = db.prepare('SELECT * FROM books WHERE id = ?');
|
||||
const getByIsbn = db.prepare('SELECT * FROM books WHERE isbn13 = ?');
|
||||
const insert = db.prepare(`INSERT INTO books (isbn13, lccn, title, subtitle, authors, publisher, year,
|
||||
subjects, call_number, sort_key, confidence, source, dewey, status, attention_reason,
|
||||
manual_override, in_queue, created_at, updated_at, hierarchy_tail, edition)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
manual_override, in_queue, created_at, updated_at, hierarchy_tail, edition, looked_up_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(isbn13) DO NOTHING`);
|
||||
|
||||
// Why pending lookups are waiting (see Db.setRetry): never saved, a restart starts the lookups over anyway.
|
||||
@@ -150,7 +162,7 @@ export function openDb(path: string): Db {
|
||||
f.sortKey ?? null, f.confidence ?? null, f.source ?? null, f.dewey ?? null,
|
||||
f.status ?? 'pending', f.attentionReason ?? null, f.manualOverride ? 1 : 0,
|
||||
(f.inQueue ?? true) ? 1 : 0, now, now, f.hierarchyTail == null ? null : JSON.stringify(f.hierarchyTail),
|
||||
f.edition ?? null,
|
||||
f.edition ?? null, f.lookedUpAt ?? null,
|
||||
);
|
||||
if (r.changes === 0 && f.isbn13) return { book: self.findByIsbn(f.isbn13)!, created: false };
|
||||
return { book: self.getBook(Number(r.lastInsertRowid))!, created: true };
|
||||
@@ -210,6 +222,12 @@ export function openDb(path: string): Db {
|
||||
listPendingIds() {
|
||||
return (db.prepare("SELECT id FROM books WHERE status = 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
|
||||
},
|
||||
listRecheckIds(before) {
|
||||
return (db.prepare(`SELECT id FROM books WHERE status != 'pending' AND manual_override = 0
|
||||
AND (source IS NULL OR source != 'manual') AND (call_number IS NULL OR confidence = 'approximate')
|
||||
AND looked_up_at < ? ORDER BY looked_up_at, id`)
|
||||
.all(before) as Row[]).map((r) => r.id);
|
||||
},
|
||||
listTailMissingIds() {
|
||||
return (db.prepare("SELECT id FROM books WHERE hierarchy_tail IS NULL AND status != 'pending' ORDER BY id").all() as Row[]).map((r) => r.id);
|
||||
},
|
||||
|
||||
@@ -624,3 +624,96 @@ test('a failing change notification cannot leave a book pending without a retry
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(book.id)!.status, 'resolved');
|
||||
});
|
||||
|
||||
// ---- looking again later, and the misread hint ----
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const NOW = Date.parse('2026-11-22T12:00:00Z');
|
||||
const ago = (days: number) => new Date(NOW - days * DAY).toISOString();
|
||||
const noNumber: Resolution = { meta: null, callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, reason: 'No Library of Congress number found' };
|
||||
|
||||
function setupAt(resolve: ResolverLike['resolve']) {
|
||||
const db = openDb(':memory:');
|
||||
const logs: string[] = [];
|
||||
const resolver: ResolverLike = { resolve, tail: async () => [], edition: async () => '', search: async () => [] };
|
||||
const jobs = createJobs({ db, resolver, onChange: () => {}, now: () => NOW, backoff: () => 0, retryDelaysMs: [0], log: (l) => logs.push(l) });
|
||||
return { db, jobs, logs };
|
||||
}
|
||||
|
||||
test('start: books with no number or an approximate one, last looked up over 7 days ago, are looked up again; nothing else is', async () => {
|
||||
const seen: string[] = [];
|
||||
const { db, jobs } = setupAt(async (i) => { seen.push(i.isbn13!); return noNumber; });
|
||||
const mk = (isbn: string, f: Partial<NewBook>) => db.insertPending({ isbn13: isbn, title: isbn, status: 'resolved', lookedUpAt: ago(8), ...f }).book;
|
||||
mk('9780000000001', { status: 'needs_attention', attentionReason: 'No Library of Congress number found' });
|
||||
mk('9780000000002', { callNumber: 'GV199.42 X', sortKey: 'a', confidence: 'approximate', source: 'similar' });
|
||||
mk('9780000000003', { callNumber: 'GV199.42 Y', sortKey: 'b', confidence: 'exact', source: 'loc-isbn' });
|
||||
mk('9780000000004', { callNumber: 'GV199.42 Z', sortKey: 'c', confidence: 'approximate', source: 'similar', lookedUpAt: ago(6) });
|
||||
mk('9780000000005', { callNumber: 'GV199.42 H', sortKey: 'd', confidence: 'manual', source: 'manual', manualOverride: true });
|
||||
mk('9780000000006', { status: 'needs_attention', manualOverride: true });
|
||||
jobs.resume();
|
||||
await jobs.idle();
|
||||
assert.deepEqual(seen.sort(), ['9780000000001', '9780000000002']);
|
||||
});
|
||||
|
||||
test('a recheck never takes a number away, never swaps one guess for another, and takes an exact number', async () => {
|
||||
let next: Resolution = noNumber;
|
||||
const { db, jobs } = setupAt(async () => next);
|
||||
const approx = (isbn: string) => db.insertPending({ isbn13: isbn, title: isbn, status: 'resolved', callNumber: 'GV199.42 K37', sortKey: 'k', confidence: 'approximate', source: 'similar', lookedUpAt: ago(9) }).book;
|
||||
const a = approx('9780000000011'); const b = approx('9780000000012'); const c = approx('9780000000013');
|
||||
const run = async (book: { id: number }, r: Resolution) => { next = r; jobs.enqueue(book.id, { recheck: true }); await jobs.idle(); return db.getBook(book.id)!; };
|
||||
const none = await run(a, noNumber);
|
||||
assert.equal(none.callNumber, 'GV199.42 K37'); assert.equal(none.status, 'resolved'); assert.equal(none.lookedUpAt, new Date(NOW).toISOString());
|
||||
const guess = await run(b, { ...noNumber, callNumber: 'F784.D9 M2', sortKey: 'f', confidence: 'approximate', source: 'similar' });
|
||||
assert.equal(guess.callNumber, 'GV199.42 K37');
|
||||
const exact = await run(c, { ...noNumber, callNumber: 'GV199.42.C6 D87 2011', sortKey: 'g', confidence: 'exact', source: 'loc-isbn' });
|
||||
assert.equal(exact.callNumber, 'GV199.42.C6 D87 2011'); assert.equal(exact.confidence, 'exact'); assert.equal(exact.status, 'resolved');
|
||||
});
|
||||
|
||||
test('a recheck of a book with no number that now finds one resolves it; a hand-entered number is never touched', async () => {
|
||||
const { db, jobs } = setupAt(async () => ({ ...noNumber, callNumber: 'E160 .L66 2026', sortKey: 'e', confidence: 'approximate', source: 'similar' }));
|
||||
const attn = db.insertPending({ isbn13: '9798886472189', title: 'x', status: 'needs_attention', attentionReason: 'No Library of Congress number found', lookedUpAt: ago(30) }).book;
|
||||
const hand = db.insertPending({ isbn13: '9780000000021', title: 'y', status: 'resolved', callNumber: 'AB1', sortKey: 'a', confidence: 'manual', source: 'manual', manualOverride: true, lookedUpAt: ago(30) }).book;
|
||||
jobs.enqueue(attn.id, { recheck: true });
|
||||
jobs.enqueue(hand.id, { recheck: true }); // even if asked, it keeps its number
|
||||
await jobs.idle();
|
||||
const b = db.getBook(attn.id)!;
|
||||
assert.equal(b.status, 'resolved'); assert.equal(b.callNumber, 'E160 .L66 2026'); assert.equal(b.attentionReason, null);
|
||||
assert.equal(db.getBook(hand.id)!.callNumber, 'AB1');
|
||||
});
|
||||
|
||||
test('a recheck that cannot reach a source leaves the book and its time alone, to be tried at the next start', async () => {
|
||||
const { db, jobs } = setupAt(async () => { throw new RealTemporaryError('down'); });
|
||||
const book = db.insertPending({ isbn13: '9780000000031', title: 'z', status: 'needs_attention', attentionReason: 'No Library of Congress number found', lookedUpAt: ago(10) }).book;
|
||||
jobs.enqueue(book.id, { recheck: true });
|
||||
await jobs.idle();
|
||||
const b = db.getBook(book.id)!;
|
||||
assert.equal(b.status, 'needs_attention'); assert.equal(b.lookedUpAt, ago(10));
|
||||
});
|
||||
|
||||
test('every finished lookup records when it happened', async () => {
|
||||
const { db, jobs } = setupAt(async () => found);
|
||||
const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' });
|
||||
jobs.enqueue(book.id);
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(book.id)!.lookedUpAt, new Date(NOW).toISOString());
|
||||
});
|
||||
|
||||
test('an ISBN no catalogue has, within 3 digits of a book already here, is named as a likely misread; further away it is not', async () => {
|
||||
const { db, jobs } = setupAt(async () => ({ ...noNumber, reason: 'Not found in Open Library, Google Books or the Library of Congress' }));
|
||||
db.insertPending({ isbn13: '9781937052898', title: 'The Colorado Trail', status: 'resolved', callNumber: 'GV854.5.C6 F68 2024', sortKey: 'x', confidence: 'approximate' });
|
||||
const near = db.insertPending({ isbn13: '9781037052897', title: '9781037052897' }).book; // 2 digits away
|
||||
const far = db.insertPending({ isbn13: '9781234567897', title: '9781234567897' }).book;
|
||||
jobs.enqueue(near.id); jobs.enqueue(far.id);
|
||||
await jobs.idle();
|
||||
assert.equal(db.getBook(near.id)!.attentionReason, 'No catalogue has this ISBN. It may be a misread of The Colorado Trail (9781937052898), which is already here.');
|
||||
assert.equal(db.getBook(far.id)!.attentionReason, 'Not found in Open Library, Google Books or the Library of Congress');
|
||||
assert.equal(db.getBook(near.id)!.status, 'needs_attention'); // nothing is deleted
|
||||
});
|
||||
|
||||
test('the misread hint is only for an ISBN nobody knows: a book with a title but no number keeps its plain reason', async () => {
|
||||
const { db, jobs } = setupAt(async () => ({ ...noNumber, meta: { title: 'Real Book', authors: [], subjects: [] } }));
|
||||
db.insertPending({ isbn13: '9781937052898', title: 'The Colorado Trail', status: 'resolved', callNumber: 'GV854.5.C6 F68 2024', sortKey: 'x', confidence: 'approximate' });
|
||||
const b = db.insertPending({ isbn13: '9781037052897', title: '9781037052897' }).book;
|
||||
jobs.enqueue(b.id); await jobs.idle();
|
||||
assert.equal(db.getBook(b.id)!.attentionReason, 'No Library of Congress number found');
|
||||
});
|
||||
+49
-8
@@ -12,6 +12,12 @@ export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
|
||||
*/
|
||||
export const SETTLE_AFTER_ATTEMPTS = 6;
|
||||
|
||||
/** A book with no number, or only an approximate one, is asked about again at the next start once this old. */
|
||||
export const RECHECK_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** The most digits of an ISBN that may differ for a book already here to be named as the likely original of a misread. */
|
||||
export const MISREAD_MAX_DIFF = 3;
|
||||
|
||||
export const BACKOFF_FIRST_MS = 2_000;
|
||||
export const BACKOFF_CAP_MS = 300_000;
|
||||
|
||||
@@ -35,10 +41,14 @@ export type ResolverLike = Resolver;
|
||||
|
||||
export interface Jobs {
|
||||
/** `fresh`: the lookup ignores every cached source answer ("Look up again"), through its retries too. */
|
||||
enqueue(id: number, opts?: { fresh?: boolean }): void;
|
||||
enqueue(id: number, opts?: { fresh?: boolean; recheck?: boolean }): void;
|
||||
/** The book was removed: its waiting retry, queue place and remembered answers all go. */
|
||||
cancel(id: number): void;
|
||||
/** At start: pending books (and books an older version gave up on only because a source was unreachable) go on. */
|
||||
/**
|
||||
* At start: pending books (and books an older version gave up on only because a source was unreachable) go on, and
|
||||
* books with no number or an approximate one that were last looked up over 7 days ago are asked about again.
|
||||
* A hand-entered number is never touched; a recheck never takes a number away or swaps one guess for another.
|
||||
*/
|
||||
resume(): void;
|
||||
/**
|
||||
* Backfill, for books made before the hierarchy tail existed: look up only the tail (nothing else about the book
|
||||
@@ -72,6 +82,14 @@ function failingSource(e: unknown, message: string): string {
|
||||
: /openlibrary|Open Library/i.test(message) ? 'Open Library' : 'A lookup service';
|
||||
}
|
||||
|
||||
/** How many of the 13 digits differ; null when either is not 13 digits. */
|
||||
function isbnDistance(a: string, b: string): number | null {
|
||||
if (a.length !== 13 || b.length !== 13) return null;
|
||||
let n = 0;
|
||||
for (let i = 0; i < 13; i++) if (a[i] !== b[i]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
export function createJobs(deps: {
|
||||
db: Db; resolver: ResolverLike; onChange: (book: Book) => void;
|
||||
/** The tail and edition backfills' schedule (they give up until the next start). */
|
||||
@@ -92,6 +110,8 @@ export function createJobs(deps: {
|
||||
const queued = new Set<number>();
|
||||
const attempts = new Map<number, number>();
|
||||
const fresh = new Set<number>();
|
||||
// Books asked about again at start although they are not pending: their lookup must not disturb what they have.
|
||||
const rechecks = new Set<number>();
|
||||
// What each pending lookup has been definitively told so far (see jobMemo): a retry asks only for the rest.
|
||||
const memos = new Map<number, Map<string, string>>();
|
||||
// The lookup being attempted now, and the books asked for again meanwhile (true: "fresh"): they run once more after.
|
||||
@@ -131,7 +151,7 @@ export function createJobs(deps: {
|
||||
|
||||
/** Everything remembered about a lookup that has ended (or been dropped). */
|
||||
function forget(id: number): void {
|
||||
attempts.delete(id); fresh.delete(id); memos.delete(id); db.setRetry(id, null);
|
||||
attempts.delete(id); fresh.delete(id); rechecks.delete(id); memos.delete(id); db.setRetry(id, null);
|
||||
}
|
||||
|
||||
function schedule(id: number, delayMs: number): void {
|
||||
@@ -149,7 +169,8 @@ export function createJobs(deps: {
|
||||
|
||||
async function attempt(id: number): Promise<void> {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.status !== 'pending') { forget(id); return; }
|
||||
if (!book || (book.status !== 'pending' && !rechecks.has(id))) { forget(id); return; }
|
||||
const recheck = rechecks.has(id);
|
||||
const n = attempts.get(id) ?? 0;
|
||||
const input: ResolveInput = {};
|
||||
if (book.isbn13) input.isbn13 = book.isbn13;
|
||||
@@ -184,19 +205,35 @@ export function createJobs(deps: {
|
||||
if (cur.edition === null) tail.edition = res.edition;
|
||||
else if (wasFresh && res.edition !== '') tail.edition = res.edition;
|
||||
}
|
||||
const lookedUpAt = new Date(now()).toISOString();
|
||||
// A recheck of a book that has an approximate number takes nothing away and swaps one guess for another never:
|
||||
// it only changes the book when the catalogues now give an exact number (or the book had none).
|
||||
const keepsOwn = recheck && !!cur.callNumber && (!res.callNumber || res.confidence !== 'exact');
|
||||
if (cur.manualOverride) {
|
||||
emit(id, { dewey, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}), ...(tail.edition !== undefined ? { edition: tail.edition } : {}) });
|
||||
emit(id, { dewey, lookedUpAt, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}), ...(tail.edition !== undefined ? { edition: tail.edition } : {}) });
|
||||
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
|
||||
} else if (keepsOwn) {
|
||||
emit(id, { lookedUpAt });
|
||||
log(`[lookup] ${label}: looked up again, nothing better than ${cur.callNumber} (${took()})`);
|
||||
} else if (res.callNumber) {
|
||||
emit(id, {
|
||||
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
|
||||
source: res.source, dewey, status: 'resolved', attentionReason: null, ...tail,
|
||||
source: res.source, dewey, status: 'resolved', attentionReason: null, lookedUpAt, ...tail,
|
||||
});
|
||||
log(`[lookup] ${label}: ${res.callNumber} (${res.source === 'similar' && similar ? `similar ${similar}` : res.source}) in ${took()}`);
|
||||
} else {
|
||||
// Only here, with every source answered for real, is the person asked to look.
|
||||
const reason = res.reason ?? 'No Library of Congress number found';
|
||||
emit(id, { dewey, status: 'needs_attention', attentionReason: reason, ...tail });
|
||||
let reason = res.reason ?? 'No Library of Congress number found';
|
||||
if (!res.meta && cur.isbn13) {
|
||||
// No catalogue has this ISBN at all: a book already here with nearly the same digits is the likely original.
|
||||
let best: { book: Book; d: number } | null = null;
|
||||
for (const o of db.listBooks()) {
|
||||
const d = o.id !== id && o.isbn13 ? isbnDistance(cur.isbn13, o.isbn13) : null;
|
||||
if (d !== null && d <= MISREAD_MAX_DIFF && (!best || d < best.d)) best = { book: o, d };
|
||||
}
|
||||
if (best) reason = `No catalogue has this ISBN. It may be a misread of ${best.book.title} (${best.book.isbn13}), which is already here.`;
|
||||
}
|
||||
emit(id, { dewey, status: 'needs_attention', attentionReason: reason, lookedUpAt, ...tail });
|
||||
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -315,6 +352,7 @@ export function createJobs(deps: {
|
||||
|
||||
return {
|
||||
enqueue(id, opts) {
|
||||
if (opts?.recheck) rechecks.add(id);
|
||||
if (opts?.fresh) { fresh.add(id); memos.delete(id); }
|
||||
// A fresh request (scan, "Look up again") overrides any wait and starts the retries over.
|
||||
const t = waiting.get(id);
|
||||
@@ -338,6 +376,9 @@ export function createJobs(deps: {
|
||||
const n = db.requeueTemporaryFailures();
|
||||
if (n > 0) log(`[lookup] ${n} book(s) an earlier version gave up on because a source did not answer will be looked up again`);
|
||||
for (const id of db.listPendingIds()) this.enqueue(id);
|
||||
const stale = db.listRecheckIds(new Date(now() - RECHECK_AFTER_MS).toISOString());
|
||||
if (stale.length > 0) log(`[lookup] ${stale.length} book(s) with no number or an approximate one will be looked up again`);
|
||||
for (const id of stale) this.enqueue(id, { recheck: true });
|
||||
},
|
||||
resumeTails() {
|
||||
const n = db.recheckEmptyTails(TAIL_RULES_VERSION);
|
||||
|
||||
@@ -51,7 +51,7 @@ test('unknown ISBN', async () => {
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780999999998' });
|
||||
assert.equal(res.meta, null);
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(res.reason, 'Not found in Open Library or the Library of Congress');
|
||||
assert.equal(res.reason, 'Not found in Open Library, Google Books or the Library of Congress');
|
||||
});
|
||||
|
||||
test('LoC block page -> TemporaryError, and nothing cached for it', async () => {
|
||||
@@ -284,7 +284,7 @@ test('similar tier: not tried for a book with no title', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780999999998' });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(f.calls.some((c) => c.includes('q=')), false);
|
||||
assert.equal(f.calls.some((c) => c.includes('openlibrary.org') && c.includes('q=')), false);
|
||||
});
|
||||
|
||||
test('similar tier: searches are cached and make at most 3 Open Library and 2 LoC requests', async () => {
|
||||
@@ -368,7 +368,7 @@ test('Day hikes: the title-word search finds Pacific Crest Trail books in the hi
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.match(detail, /^GV199\.42\.P3 /);
|
||||
// The queries kept the title's own distinctive words.
|
||||
const q = f.calls.map((c) => decodeURIComponent(c)).filter((c) => c.includes('q=') || c.includes('bath.any'));
|
||||
const q = f.calls.map((c) => decodeURIComponent(c)).filter((c) => (c.includes('openlibrary.org') && c.includes('q=')) || c.includes('bath.any'));
|
||||
assert.ok(q.every((c) => /pacific/i.test(c) && /crest/i.test(c) && /trail/i.test(c)), q.join('\n'));
|
||||
});
|
||||
|
||||
@@ -605,3 +605,106 @@ test('within one job, a retry does not repeat a request that already got a real
|
||||
await bare.resolve({ isbn13: '9781593278281' });
|
||||
assert.ok([...answered.values()].some((n) => n > 1));
|
||||
});
|
||||
|
||||
// ---- Google Books, and the widened similar-books searches ----
|
||||
|
||||
const marcRec = (title: string, lcc: string, subject = ''): string => {
|
||||
const [a, ...b] = lcc.split(' ');
|
||||
return `<record xmlns="http://www.loc.gov/MARC21/slim"><leader>00000cam a2200000 a 4500</leader>`
|
||||
+ `<datafield tag="050" ind1="0" ind2="0"><subfield code="a">${a}</subfield>${b.length ? `<subfield code="b">${b.join(' ')}</subfield>` : ''}</datafield>`
|
||||
+ `<datafield tag="245" ind1="1" ind2="0"><subfield code="a">${title}</subfield></datafield>`
|
||||
+ (subject ? `<datafield tag="650" ind1=" " ind2="0"><subfield code="a">${subject}</subfield></datafield>` : '') + `</record>`;
|
||||
};
|
||||
const sru = (recs: string[]): string => `<?xml version="1.0"?><zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:numberOfRecords>${recs.length}</zs:numberOfRecords><zs:records>${recs.map((r) => `<zs:record><zs:recordData>${r}</zs:recordData></zs:record>`).join('')}</zs:records></zs:searchRetrieveResponse>`;
|
||||
|
||||
/** Nobody but Google Books knows the ISBN; the Library of Congress keyword searches answer with `loc(query)`. */
|
||||
function onlyGoogle(loc: (query: string) => string[]) {
|
||||
const f = fixtureFetch();
|
||||
const fetchStub = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const u = new URL(url);
|
||||
if (u.hostname === 'openlibrary.org') return new Response(u.pathname === '/search.json' ? '{"docs":[]}' : '{}', { status: 200 });
|
||||
if (u.hostname === 'www.google.com') return f.fetch(url, init);
|
||||
f.calls.push(url);
|
||||
const q = decodeURIComponent(u.searchParams.get('query') ?? '').replace(/\+/g, ' ');
|
||||
return new Response(sru(/^bath\.isbn=|^bath\.title="/.test(q) ? [] : loc(q)), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const similarCalls = () => f.calls.filter((c) => c.includes('bath.any') || /bath\.title=[^"]/.test(decodeURIComponent(c)));
|
||||
return { fetch: fetchStub, f, similarCalls };
|
||||
}
|
||||
|
||||
const DURANGO = '9780984221356';
|
||||
|
||||
test('Google Books gives a title for an ISBN nobody else knows, and the widened search then finds a class from the publisher\'s place word', async () => {
|
||||
const s = onlyGoogle((q) => {
|
||||
if (/colorado/.test(q) && /hik/.test(q)) return [marcRec('Hiking Colorado', 'GV199.42.C6 H554'), marcRec('Colorado hiking', 'GV199.42.C62 C645'), marcRec('Hiking Colorado\'s roadless trails', 'GV199.42.C6 P87 2007')];
|
||||
if (/durango/.test(q)) return [marcRec('Durango as it is', 'F784.D9 M2')];
|
||||
return [];
|
||||
});
|
||||
let detail = ''; const metas: string[] = [];
|
||||
const res = await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep })
|
||||
.resolve({ isbn13: DURANGO }, { onSimilar: (d) => { detail = d; }, onMeta: (m) => metas.push(m.title) });
|
||||
assert.deepEqual(metas, ['The Best Durango Hikes']);
|
||||
assert.equal(res.meta!.title, 'The Best Durango Hikes');
|
||||
assert.deepEqual(res.meta!.authors, ['The Colorado Mountain Club']);
|
||||
assert.match(res.callNumber!, /^GV199\.42\.C6/);
|
||||
assert.equal(res.source, 'similar');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.match(detail, /widened: colorado hik\w*, a place or topic from the record/);
|
||||
assert.ok(s.similarCalls().length <= 12, 'the tier makes at most 12 requests');
|
||||
});
|
||||
|
||||
test('widened search: one book in a class is never enough, however well it matches; the answer is "no number" and the requests stay bounded', async () => {
|
||||
const s = onlyGoogle(() => [marcRec('Hiking Colorado', 'GV199.42.C6 H554')]);
|
||||
const res = await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: DURANGO });
|
||||
assert.equal(res.callNumber, null);
|
||||
assert.equal(res.reason, 'No Library of Congress number found');
|
||||
assert.equal(res.meta!.title, 'The Best Durango Hikes');
|
||||
assert.ok(s.similarCalls().length <= 12 && s.similarCalls().length >= 4, String(s.similarCalls().length));
|
||||
});
|
||||
|
||||
test('widened search: stops at the first step that gives a class, so later steps make no request', async () => {
|
||||
// The first search (the title's own words) is already enough: no widened query at all.
|
||||
const s = onlyGoogle(() => [marcRec('Hiking Durango', 'GV199.42.C62 D87'), marcRec('Durango hikes', 'GV199.42.C62 D872'), marcRec('Durango trails', 'GV199.42.C6 D88')]);
|
||||
const res = await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: DURANGO }, { onSimilar: () => {} });
|
||||
assert.match(res.callNumber!, /^GV199\.42\.C6/);
|
||||
assert.equal(s.similarCalls().length, 1);
|
||||
});
|
||||
|
||||
test('Google Books fills the subtitle and publisher a book lacks, and the widened search uses the category-free subtitle phrase', async () => {
|
||||
const s = onlyGoogle((q) => (/national/.test(q) && /parks/.test(q) ? [marcRec('National parks', 'E160 .N246 2017', 'National parks and reserves'), marcRec('America\'s national parks', 'E160 .A5792 2011'), marcRec('Tanzania national parks', 'SB484.T3 T35 1975')] : []));
|
||||
let detail = '';
|
||||
const res = await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9798886472189' }, { onSimilar: (d) => { detail = d; } });
|
||||
assert.equal(res.meta!.subtitle, 'Extraordinary Experiences in USA National Parks');
|
||||
assert.equal(res.meta!.publisher, 'Moon Travel');
|
||||
assert.equal(res.meta!.year, 2026);
|
||||
assert.match(res.callNumber!, /^E160\./);
|
||||
assert.match(detail, /widened: national parks/);
|
||||
});
|
||||
|
||||
test('Google Books is not asked when a catalogue already gave the number', async () => {
|
||||
const f = fixtureFetch();
|
||||
await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' });
|
||||
assert.equal(f.calls.some((c) => c.includes('google.com')), false);
|
||||
});
|
||||
|
||||
test('an ISBN no source knows is "not found" and says so; Google Books being down is not "not found"', async () => {
|
||||
const s = onlyGoogle(() => []);
|
||||
const res = await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781037052897' });
|
||||
assert.equal(res.meta, null);
|
||||
assert.equal(res.reason, 'Not found in Open Library, Google Books or the Library of Congress');
|
||||
const down = (async (u: string | URL | Request, init?: RequestInit) => String(u).includes('google.com') ? new Response('busy', { status: 503 }) : s.fetch(u as string, init)) as typeof fetch;
|
||||
await assert.rejects(createResolver({ fetch: down, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781037052897' }),
|
||||
(e: unknown) => e instanceof TemporaryError && e.source === 'Google Books');
|
||||
// ...even when settling: with no number at all it still throws.
|
||||
await assert.rejects(createResolver({ fetch: down, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781037052897' }, { tolerateLocFailure: true }), TemporaryError);
|
||||
});
|
||||
|
||||
test('widened search: the second step is one query with the other forms of the words, and the steps run in order', async () => {
|
||||
const s = onlyGoogle(() => []);
|
||||
await createResolver({ fetch: s.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: DURANGO });
|
||||
const q = s.similarCalls().map((c) => decodeURIComponent(new URL(c).searchParams.get('query') ?? '').replace(/\+/g, ' '));
|
||||
assert.equal(q[0], 'bath.any=durango and bath.any=hikes');
|
||||
assert.equal(q[1], '(bath.any=durango or bath.any=durangos) and (bath.any=hikes or bath.any=hike or bath.any=hiking)');
|
||||
assert.deepEqual(q.slice(2), ['bath.any=colorado and bath.any=durango', 'bath.any=colorado and bath.any=hikes']);
|
||||
});
|
||||
@@ -5,9 +5,11 @@ import { bareClassResult, chooseCallNumber, findHint } from './choose.ts';
|
||||
import type { Chosen } from './choose.ts';
|
||||
import { createLoc } from '../sources/loc.ts';
|
||||
import { createOpenLibrary } from '../sources/openlibrary.ts';
|
||||
import { createGoogleBooks } from '../sources/googlebooks.ts';
|
||||
import type { GbInfo } from '../sources/googlebooks.ts';
|
||||
import type { OlInfo } from '../sources/openlibrary.ts';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, searchWords, voteSimilar } from './similar.ts';
|
||||
import type { SimilarCandidate } from './similar.ts';
|
||||
import { classified, cuesOf, finishSimilar, keywordsOf, mergeCandidates, placeQueries, placeWords, searchWords, shortQueries, variants, voteSimilar } from './similar.ts';
|
||||
import type { Keywords, SimilarCandidate, VoteOpts } from './similar.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
import { TemporaryError } from '../sources/http.ts';
|
||||
import { recordMatches } from './match.ts';
|
||||
@@ -82,6 +84,9 @@ function mergeMeta(parts: Partials): BookMeta | null {
|
||||
/** A work-level or title-match record belongs to some edition, not necessarily this one: its LCCN is not this book's. */
|
||||
const withoutLccn = (m: Partial<BookMeta>): Partial<BookMeta> => { const { lccn: _l, ...rest } = m; return rest; };
|
||||
|
||||
/** The fewest books that must agree on a class when the search had to be widened. */
|
||||
export const MIN_AGREE = 2;
|
||||
|
||||
const lccOf = (recs: MarcFields[]): Candidate[] => recs.flatMap((r) => r.lcc);
|
||||
|
||||
export function createResolver(deps: {
|
||||
@@ -93,6 +98,7 @@ export function createResolver(deps: {
|
||||
let bypass = 0;
|
||||
const cache: SourceCache = { get: (k) => (bypass > 0 ? null : deps.cache.get(k)), set: (k, v) => deps.cache.set(k, v) };
|
||||
const ol = createOpenLibrary({ fetch: deps.fetch, cache });
|
||||
const gb = createGoogleBooks({ fetch: deps.fetch, cache });
|
||||
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const loc = createLoc({
|
||||
fetch: deps.fetch, cache,
|
||||
@@ -187,8 +193,11 @@ export function createResolver(deps: {
|
||||
} else if (edit === null && !isbn && !locError) edit = '';
|
||||
|
||||
const olEditionCands: Candidate[] = edition?.lcc ?? [];
|
||||
// Google Books (asked below, only while there is no number): the last source for a title, and a filler of gaps.
|
||||
let google: GbInfo | null = null;
|
||||
let googleError: unknown = null;
|
||||
const metaOf = (extra: Partials = []): BookMeta | null =>
|
||||
mergeMeta([edition?.meta, locRecs[0]?.meta, ...extra, input.title ? { title: input.title } : null]);
|
||||
mergeMeta([edition?.meta, locRecs[0]?.meta, ...extra, google?.meta, input.title ? { title: input.title } : null]);
|
||||
const forChoose = (m: BookMeta | null) => ({
|
||||
authors: m?.authors.length ? m.authors : input.author ? [input.author] : [],
|
||||
title: m?.title ?? input.title ?? '',
|
||||
@@ -201,6 +210,16 @@ export function createResolver(deps: {
|
||||
let chosen: Chosen | null = chooseCallNumber({ ...own, locTitle: [], olWork: [] }, forChoose(metaOf()), exactSource);
|
||||
const hint = chosen ? null : findHint(own, exactSource);
|
||||
|
||||
// Google Books: a title and authors for an ISBN neither Open Library nor the Library of Congress knows, and the
|
||||
// subtitle, publisher and categories they left out. It never gives a number, so it is asked only when there is none.
|
||||
if (!chosen && isbn) {
|
||||
try { google = await gb.byIsbn(isbn); } catch (e) {
|
||||
if (!(e instanceof TemporaryError)) throw e;
|
||||
googleError = e; // a number found below still stands; with none, the lookup is tried again
|
||||
}
|
||||
if (google) notify(metaOf());
|
||||
}
|
||||
|
||||
// Tier 3: LoC by title and author.
|
||||
let locTitleRecs: MarcFields[] = [];
|
||||
let titleSearched = false;
|
||||
@@ -277,12 +296,55 @@ export function createResolver(deps: {
|
||||
subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw),
|
||||
})));
|
||||
}
|
||||
const vote = voteSimilar(kw, mergeCandidates(groups), hint ? { hint: hint.cls } : {});
|
||||
// The searches so far found no class: widen them, one step at a time, voting after each request and stopping at
|
||||
// the first vote that wins. At most 12 requests in all for the tier (3 Open Library + 2 Library of Congress
|
||||
// above, 1 more with a class hint, then 1 for word forms, up to 3 with place words, up to 2 shorter ones).
|
||||
const hintOpt = hint ? { hint: hint.cls } : {};
|
||||
const cues = cuesOf([meta.title, meta.subtitle, meta.publisher, ...(google?.categories ?? []), ...meta.subjects]);
|
||||
const strict: VoteOpts = hintOpt;
|
||||
// A widened vote: two books must agree (never one), they hold half the weight, and lead the rival by half again.
|
||||
const relaxed: VoteOpts = { ...hintOpt, minAgree: MIN_AGREE, minShare: 0.2, margin: 1.5, cues };
|
||||
const asGroup = (recs: MarcFields[]): SimilarCandidate[] => recs.map((r) => ({
|
||||
title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}),
|
||||
subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw),
|
||||
}));
|
||||
let vote = voteSimilar(kw, mergeCandidates(groups), strict);
|
||||
let how = '';
|
||||
const widen = async (label: string, q: () => Promise<MarcFields[]>, kws: Keywords, o: VoteOpts): Promise<void> => {
|
||||
if (vote || locError) return;
|
||||
const recs = await locCall(q);
|
||||
similarRecs.push(...recs);
|
||||
groups.push(asGroup(recs));
|
||||
vote = voteSimilar(kws, mergeCandidates(groups), o);
|
||||
if (vote) how = label;
|
||||
};
|
||||
if (!vote && kw.own.length >= 2) {
|
||||
// b: other forms of the words (hike, hikes, hiking) in one query.
|
||||
await widen('other forms of the title words', () => loc.byWordForms(kw.own.slice(0, 3).map(variants)), kw, strict);
|
||||
}
|
||||
const ctx = { title: meta.title, subtitle: meta.subtitle, publisher: meta.publisher, authors: meta.authors, subjects: meta.subjects, categories: google?.categories ?? [] };
|
||||
const places = placeWords(ctx);
|
||||
// c: place and topic words from the subtitle, publisher, author and categories; they also add weight to a book that has them.
|
||||
const kwPlaces: Keywords = { ...kw, extra: [...new Set([...places, ...kw.extra])].slice(0, 6) };
|
||||
if (!vote) {
|
||||
for (const q of placeQueries(kw, ctx, places)) {
|
||||
await widen(`${q.join(' ')}, a place or topic from the record`, () => loc.byKeywords(q), kwPlaces, relaxed);
|
||||
}
|
||||
}
|
||||
// d: shorter searches from the title's most distinctive words.
|
||||
if (!vote) {
|
||||
for (const q of shortQueries(kw)) await widen(`${q.join(' ')}, a shorter search`, () => loc.byKeywords(q), kwPlaces, relaxed);
|
||||
}
|
||||
// e: what has been found, judged once more with the match threshold lowered to one title word. Still two books must agree.
|
||||
if (!vote) {
|
||||
vote = voteSimilar(kwPlaces, mergeCandidates(groups), { ...relaxed, minMatched: 1, minShare: 0.3, margin: 1.25 });
|
||||
if (vote) how = 'a lower match threshold';
|
||||
}
|
||||
if (vote) {
|
||||
const done = finishSimilar(vote.key, forChoose(meta));
|
||||
if (done) {
|
||||
chosen = { callNumber: done.callNumber, sortKey: done.sortKey, confidence: 'approximate', source: 'similar' };
|
||||
opts?.onSimilar?.(`${vote.key} (${vote.support} of ${vote.counted} candidates)`);
|
||||
opts?.onSimilar?.(`${vote.key} (${vote.support} of ${vote.counted} candidates${how ? `; widened: ${how}` : ''})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -327,9 +389,10 @@ export function createResolver(deps: {
|
||||
// Open Library had nothing and the LoC could not be asked: report that, not "no number found".
|
||||
if (locError) throw locError;
|
||||
if (olError) throw olError;
|
||||
if (googleError) throw googleError;
|
||||
return {
|
||||
meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey, tail, edition: edit,
|
||||
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress',
|
||||
reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library, Google Books or the Library of Congress',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -200,3 +200,90 @@ test('a title with fewer than two usable words borrows the subtitle, then the su
|
||||
assert.deepEqual(searchWords(bare), [['dune', 'imaginary', 'science']]);
|
||||
assert.deepEqual(searchWords(keywordsOf('The Complete Guide')), []);
|
||||
});
|
||||
|
||||
// ---- widened searches ----
|
||||
import { cuesOf, placeQueries, placeWords, shortQueries, titlePlaces, variants } from './similar.ts';
|
||||
|
||||
test('variants: singular, plural and -ing forms of a word', () => {
|
||||
assert.deepEqual(variants('hikes'), ['hikes', 'hike', 'hiking']);
|
||||
assert.deepEqual(variants('trail'), ['trail', 'trails']);
|
||||
assert.deepEqual(variants('parks'), ['parks', 'park']);
|
||||
assert.ok(variants('stories').includes('story'));
|
||||
assert.deepEqual(variants('glass'), ['glass']);
|
||||
});
|
||||
|
||||
test('place words: Colorado from the publisher and the corporate author, never the organisation words or the title\'s own', () => {
|
||||
const w = placeWords({
|
||||
title: 'The Best Durango Hikes', publisher: 'Colorado Mountain Club Press', authors: ['San Juan Group of the Colorado Mountain'],
|
||||
subjects: ['Travel'], categories: ['Sports & Recreation'],
|
||||
});
|
||||
assert.equal(w[0], 'colorado');
|
||||
assert.ok(!w.some((x) => ['club', 'press', 'group', 'travel', 'recreation', 'sports', 'durango'].includes(x)), w.join());
|
||||
});
|
||||
|
||||
test('place words: a person\'s name is not a place, and USA becomes the words a record uses', () => {
|
||||
const w = placeWords({ title: 'Adventures of a Lifetime', subtitle: 'Extraordinary Experiences in USA National Parks', publisher: 'Moon Travel', authors: ['Becky Lomax'], subjects: [], categories: ['Photography'] });
|
||||
assert.deepEqual(w.slice(0, 2), ['united', 'states']);
|
||||
assert.ok(!w.includes('becky') && !w.includes('lomax'));
|
||||
});
|
||||
|
||||
test('place queries: the subtitle\'s last two words, then each place with the title\'s first and most distinctive words; never one word', () => {
|
||||
const i = { title: 'Backroads of Utah\'s San Rafael Swell', authors: [], subjects: [], categories: [] };
|
||||
const kw = keywordsOf(i.title);
|
||||
assert.deepEqual(titlePlaces(i.title), ['utah']);
|
||||
assert.deepEqual(placeQueries(kw, i, []), [['utah', 'backroads'], ['utah', 'rafael']]);
|
||||
const m = { title: 'Adventures of a Lifetime', subtitle: 'Extraordinary Experiences in USA National Parks', authors: [], subjects: [], categories: [] };
|
||||
assert.deepEqual(placeQueries(keywordsOf(m.title, m.subtitle), m, placeWords(m))[0], ['national', 'parks']);
|
||||
assert.deepEqual(placeQueries(keywordsOf('Durango'), { title: 'Durango', authors: [], subjects: [], categories: [] }, []), []);
|
||||
assert.ok(placeQueries(kw, i, ['x', 'y', 'z']).length <= 3);
|
||||
});
|
||||
|
||||
test('short queries: two of the most distinctive words, other than the top pair; none for a short title', () => {
|
||||
assert.deepEqual(shortQueries(keywordsOf('Backroads of Utah\'s San Rafael Swell')), [['rafael', 'utah'], ['swell', 'utah']]);
|
||||
assert.deepEqual(shortQueries(keywordsOf('Durango Hikes')), []);
|
||||
});
|
||||
|
||||
test('cues: the words that mark a guidebook, found in the book\'s own text', () => {
|
||||
assert.deepEqual(cuesOf(['The Best Durango Hikes', undefined]), ['hik']);
|
||||
assert.deepEqual(cuesOf(['Geology of Utah']), []);
|
||||
});
|
||||
|
||||
const GEO = (t: string, lcc: string): SimilarCandidate => ({ title: t, subjects: [], lcc: [lcc] });
|
||||
|
||||
test('vote: with a minimum agreement of two, one book never wins, however well it matches', () => {
|
||||
const kw = keywordsOf('Durango Hikes');
|
||||
const one = [c('Durango hikes', ['GV199.42.C6 D87'])];
|
||||
assert.ok(voteSimilar(kw, one, {}), 'the strict vote accepts one book that matches every word');
|
||||
assert.equal(voteSimilar(kw, one, { minAgree: 2 }), null);
|
||||
const two = [c('Durango hikes', ['GV199.42.C6 D87']), c('Hiking Durango', ['GV199.42.C62 D87'])];
|
||||
assert.equal(voteSimilar(kw, two, { minAgree: 2 })?.key, 'GV199.42.C6');
|
||||
});
|
||||
|
||||
test('vote: a guidebook\'s class beats a geology report that shares its place names, when the title says guidebook', () => {
|
||||
const kw = keywordsOf('Backroads of Utah\'s San Rafael Swell');
|
||||
const cands: SimilarCandidate[] = [
|
||||
{ title: 'Hiking Utah\'s San Rafael Swell', subjects: ['Hiking'], lcc: ['GV199.42.U82 S265 1986'] },
|
||||
{ title: 'Hiking and exploring Utah\'s San Rafael Swell', subjects: ['Hiking'], lcc: ['GV199.42.U82 S2648 1999'] },
|
||||
GEO('Sedimentation in small reservoirs on the San Rafael Swell, Utah', 'QE75 .C5 no. 256'),
|
||||
GEO('Geology of the San Rafael Swell, Utah', 'QE170 .S3 G5'),
|
||||
GEO('Mineral resources of the San Rafael Swell, Utah', 'QE75 .B9 no. 1752'),
|
||||
GEO('Bedrock aquifers of the San Rafael Swell, Utah', 'TA7 .U77 no. 78'),
|
||||
];
|
||||
assert.equal(voteSimilar(kw, cands, { minAgree: 2, minShare: 0.2, margin: 1.5 }), null, 'without the cue the geology reports crowd it out');
|
||||
assert.equal(voteSimilar(kw, cands, { minAgree: 2, minShare: 0.2, margin: 1.5, cues: cuesOf(['Backroads of Utah\'s San Rafael Swell']) })?.key, 'GV199.42.U82');
|
||||
});
|
||||
|
||||
test('vote: two books that disagree give nothing, even in the lowered last step', () => {
|
||||
const kw = keywordsOf('Durango Hikes');
|
||||
const split = [c('Durango hikes', ['GV199.42.C6 D87']), c('Durango hiking', ['F784.D9 M2'])];
|
||||
assert.equal(voteSimilar(kw, split, { minAgree: 2, minMatched: 1, minShare: 0.3, margin: 1.25 }), null);
|
||||
});
|
||||
|
||||
test('vote: the last step counts books that match a single title word, but still needs two of them to agree', () => {
|
||||
const kw = keywordsOf('Backroads of Utah\'s San Rafael Swell');
|
||||
const cands = [c('Canyons of Utah', ['F826 .C36']), c('Utah byways', ['F826 .B93 2001']), c('Utah history', ['F826 .H5'])];
|
||||
const o = { minAgree: 2, minShare: 0.3, margin: 1.25 };
|
||||
assert.equal(voteSimilar(kw, cands, o), null, 'one matching word is not enough at the normal threshold');
|
||||
assert.equal(voteSimilar(kw, cands, { ...o, minMatched: 1 })?.key, 'F826');
|
||||
assert.equal(voteSimilar(kw, cands.slice(0, 1), { ...o, minMatched: 1 }), null);
|
||||
});
|
||||
@@ -183,7 +183,7 @@ function candidateKeys(c: SimilarCandidate): Keys | null {
|
||||
|
||||
interface Scored { keys: Keys; score: number; matched: number }
|
||||
|
||||
function scoreCandidate(kw: Keywords, c: SimilarCandidate): { score: number; matched: number } {
|
||||
function scoreCandidate(kw: Keywords, c: SimilarCandidate, cues: Set<string> = new Set()): { score: number; matched: number } {
|
||||
const inTitle = new Set(words(`${c.title} ${c.subtitle ?? ''}`).map(stem));
|
||||
const inSubjects = new Set(c.subjects.flatMap(words).map(stem));
|
||||
let score = 0;
|
||||
@@ -198,6 +198,7 @@ function scoreCandidate(kw: Keywords, c: SimilarCandidate): { score: number; mat
|
||||
const s = stem(k);
|
||||
if (inTitle.has(s) || inSubjects.has(s)) score += 0.5;
|
||||
}
|
||||
if (cues.size > 0) score *= [...inTitle, ...inSubjects].some((w) => CUE_STEMS.has(w)) ? 1.5 : 0.6;
|
||||
return { score, matched };
|
||||
}
|
||||
|
||||
@@ -220,6 +221,19 @@ export interface VoteOpts {
|
||||
* needs two, or one matching 60%), while the share and lead tests are unchanged.
|
||||
*/
|
||||
hint?: string;
|
||||
/**
|
||||
* The fewest books that must agree on a class. When set (the widened searches), one book never wins, however well
|
||||
* its title matches. Unset: two books, or one that matches 60 % of the keywords (the first, strict search).
|
||||
*/
|
||||
minAgree?: number;
|
||||
/** How many of the title's keywords a book must match to be counted (default 2 for three or more keywords, else 1). */
|
||||
minMatched?: number;
|
||||
/**
|
||||
* Stems of words that say what kind of book this is (hik, trail, travel...), taken from the book's own text. When
|
||||
* there are any, a candidate whose own title or subjects carry such a word counts one and a half times and one that
|
||||
* does not counts 0.6 times: a guidebook is shelved with guidebooks, not with a geology report that shares its place names.
|
||||
*/
|
||||
cues?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -230,14 +244,15 @@ export interface VoteOpts {
|
||||
export function voteSimilar(kw: Keywords, cands: SimilarCandidate[], opts: VoteOpts = {}): Vote | null {
|
||||
const n = kw.title.length;
|
||||
if (n === 0) return null;
|
||||
const minMatched = n >= 3 ? 2 : 1;
|
||||
const cues = new Set(opts.cues ?? []);
|
||||
const minMatched = opts.minMatched ?? (n >= 3 ? 2 : 1);
|
||||
const minShare = opts.minShare ?? 0.25;
|
||||
const margin = opts.margin ?? 1.3;
|
||||
const counted: Scored[] = [];
|
||||
for (const c of cands) {
|
||||
const keys = candidateKeys(c);
|
||||
if (!keys) continue;
|
||||
const { score, matched } = scoreCandidate(kw, c);
|
||||
const { score, matched } = scoreCandidate(kw, c, cues);
|
||||
if (matched < minMatched) continue;
|
||||
if (opts.hint && (keys.base !== opts.hint || keys.cutters === 0)) continue;
|
||||
counted.push({ keys, score, matched });
|
||||
@@ -260,7 +275,9 @@ export function voteSimilar(kw: Keywords, cands: SimilarCandidate[], opts: VoteO
|
||||
const near = opts.hint ? [] : sums.slice(1).filter((x) => neighbours(win.key, x.key));
|
||||
const rival = opts.hint ? sums[1] : sums.slice(1).find((x) => !neighbours(win.key, x.key));
|
||||
const family = win.sum + near.reduce((a, x) => a + x.sum, 0);
|
||||
const strong = win.g.length >= 2 || win.g.some((c) => c.matched / n >= (opts.hint ? 0.5 : 0.6));
|
||||
const strong = opts.minAgree !== undefined
|
||||
? win.g.length >= opts.minAgree
|
||||
: win.g.length >= 2 || win.g.some((c) => c.matched / n >= (opts.hint ? 0.5 : 0.6));
|
||||
if (!strong) continue;
|
||||
if (family < minShare * total) continue;
|
||||
if (rival && win.sum < margin * rival.sum) continue;
|
||||
@@ -285,3 +302,128 @@ export function finishSimilar(
|
||||
export function classified(cands: SimilarCandidate[]): number {
|
||||
return cands.filter((c) => c.lcc.some((l) => parseCallNumber(l) !== null)).length;
|
||||
}
|
||||
|
||||
|
||||
/** Stems of the words that mark a travel or recreation guide, on a book's side and a candidate's. */
|
||||
const CUE_STEMS = new Set(`hiking hike trail backroad byway drive camp climb paddl bike biking cycl ski snowshoe walk guidebook guide travel trip
|
||||
recreation outdoor adventure tour park road`.split(/\s+/).map((w) => stem(w)));
|
||||
|
||||
/** The cue stems found in a book's own text (title, subtitle, publisher, categories, subjects). */
|
||||
export function cuesOf(texts: (string | undefined)[]): string[] {
|
||||
return [...new Set(texts.flatMap((t) => words(t ?? '')).map(stem).filter((w) => CUE_STEMS.has(w)))];
|
||||
}
|
||||
|
||||
// ---- Widened searches: used only when the plain keyword searches found no class (see resolver.ts) ----
|
||||
|
||||
/**
|
||||
* The forms of a word a search might need: as given, singular, plural and -ing (hikes: hike, hikes, hiking). The Library
|
||||
* of Congress keyword index stems by itself (checked: hikes and hiking find the same 248 records), so this only matters
|
||||
* for indexes that do not, and for the title index.
|
||||
*/
|
||||
export function variants(w: string): string[] {
|
||||
const base = w.length > 4 && w.endsWith('ies') ? w.slice(0, -3) + 'y'
|
||||
: w.length > 4 && /(ss|x|ch|sh)es$/.test(w) ? w.slice(0, -2)
|
||||
: w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us') ? w.slice(0, -1) : w;
|
||||
const out = [w, base, base.endsWith('s') ? base : base + 's'];
|
||||
if (base.length >= 4 && base.endsWith('e')) out.push(base.slice(0, -1) + 'ing');
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
const PLACES = new Set(`alabama alaska arizona arkansas california colorado connecticut delaware florida georgia hawaii idaho illinois
|
||||
indiana iowa kansas kentucky louisiana maine maryland massachusetts michigan minnesota mississippi missouri montana nebraska
|
||||
nevada ohio oklahoma oregon pennsylvania tennessee texas utah vermont virginia wisconsin wyoming carolina dakota hampshire
|
||||
jersey york usa mexico canada alberta ontario quebec england scotland ireland wales france italy spain germany japan china india
|
||||
africa europe asia australia alps rockies appalachian yosemite yellowstone sierra cascades`.split(/\s+/));
|
||||
|
||||
// Words of a publisher or a corporate author that name the kind of organisation, not a place or a topic.
|
||||
const ORG_NOISE = new Set(`press books book publishing publishers publisher publications publication inc llc ltd co company club society
|
||||
association council department foundation institute group committee commission service survey museum university college
|
||||
league library libraries editions edition house media international national american united states travel guide guides
|
||||
sports recreation general reference nonfiction juvenile`.split(/\s+/));
|
||||
const CORPORATE = /\b(club|society|association|council|department|foundation|institute|group|committee|commission|service|survey|museum|press|university|college|company|league|agency|office)\b/i;
|
||||
|
||||
export interface PlaceInput {
|
||||
title: string; subtitle?: string | undefined; publisher?: string | undefined; authors: string[]; subjects: string[]; categories: string[];
|
||||
}
|
||||
|
||||
/** Capitalised (or all) words of a text, lower-cased, usable as search words. */
|
||||
function rawWords(s: string): string[] {
|
||||
return plain(s).replace(/['’]s\b/g, '').split(/[^a-z0-9]+/).filter((w) => usable(w));
|
||||
}
|
||||
|
||||
/**
|
||||
* Words that say where or what a book is about, beyond its title: places first (Colorado, from "Colorado Mountain Club"),
|
||||
* then the subtitle's words, then the subjects, then the words of a corporate author and the publisher, then the source's
|
||||
* broad categories. Words already in the title, noise words and organisation words are left out. At most 4.
|
||||
*/
|
||||
export function placeWords(i: PlaceInput): string[] {
|
||||
const inTitle = new Set(rawWords(i.title).map(stem));
|
||||
const orgText = [i.publisher ?? '', ...i.authors.filter((a) => CORPORATE.test(a))].join(' ');
|
||||
const pools: string[][] = [
|
||||
// 0: a place named anywhere
|
||||
rawWords([i.subtitle ?? '', orgText, ...i.subjects, ...i.categories].join(' ')).filter((w) => PLACES.has(w)),
|
||||
// 1: the subtitle
|
||||
rawWords(i.subtitle ?? ''),
|
||||
// 2: subjects
|
||||
i.subjects.flatMap((s) => rawWords(s).filter((w) => !SUBJECT_NOISE.has(w))),
|
||||
// 3: corporate author and publisher
|
||||
rawWords(orgText),
|
||||
// 4: categories
|
||||
i.categories.flatMap(rawWords),
|
||||
];
|
||||
const out: string[] = [];
|
||||
const seen = new Set(inTitle);
|
||||
for (const pool of pools) {
|
||||
for (const w of pool) {
|
||||
if (ORG_NOISE.has(w) || SUBJECT_NOISE.has(w) || seen.has(stem(w))) continue;
|
||||
seen.add(stem(w));
|
||||
out.push(w);
|
||||
}
|
||||
}
|
||||
// "USA" is not what catalogue records say; they say United States.
|
||||
const named = out.slice(0, 4);
|
||||
return named.flatMap((w) => (w === 'usa' ? ['united', 'states'] : [w]));
|
||||
}
|
||||
|
||||
/** The title's usable words that name a place (Utah). */
|
||||
export function titlePlaces(title: string): string[] {
|
||||
return rawWords(title).filter((w) => PLACES.has(w));
|
||||
}
|
||||
|
||||
/** The last two usable words of a phrase, in order ("Extraordinary Experiences in USA National Parks" -> national parks). */
|
||||
function lastPair(s: string | undefined): string[] {
|
||||
const w = rawWords(s ?? '');
|
||||
return w.length >= 2 ? w.slice(-2) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage c: pairs of words to search, at most `max`. First the tail of the subtitle (its noun phrase), then each place
|
||||
* with the title's most distinctive words. Never one word alone.
|
||||
*/
|
||||
export function placeQueries(kw: Keywords, i: PlaceInput, extras: string[], max = 3): string[][] {
|
||||
const out: string[][] = [];
|
||||
const add = (q: string[]) => {
|
||||
if (q.length < 2 || new Set(q.map(stem)).size < q.length) return;
|
||||
if (!out.some((o) => keywordKey(o) === keywordKey(q))) out.push(q);
|
||||
};
|
||||
add(lastPair(i.subtitle));
|
||||
const places = [...titlePlaces(i.title), ...extras.filter((w) => PLACES.has(w))];
|
||||
// With no place at all, the first other word the record gave stands in.
|
||||
const anchors = (places.length > 0 ? places : extras.slice(0, 1)).slice(0, 2);
|
||||
for (const a of anchors) {
|
||||
// The title's first word (often the kind of book: Backroads) and its most distinctive one.
|
||||
const first = rawWords(i.title)[0];
|
||||
const topics = [...new Set([first, ...kw.own].filter((w): w is string => !!w && stem(w) !== stem(a)))].slice(0, 2);
|
||||
for (const t of topics) add([a, t]);
|
||||
}
|
||||
return out.slice(0, max);
|
||||
}
|
||||
|
||||
/** Stage d: shorter searches from the title's most distinctive words other than the pair already tried (top two). */
|
||||
export function shortQueries(kw: Keywords, max = 2): string[][] {
|
||||
const w = kw.own;
|
||||
if (w.length < 3) return [];
|
||||
const out = [[w[0]!, w[2]!]];
|
||||
if (w.length >= 4) out.push([w[1]!, w[2]!]);
|
||||
return out.slice(0, max);
|
||||
}
|
||||
@@ -25,12 +25,13 @@ function pick(u: URL, locOverride: string | null): string | null {
|
||||
if (isbn) return `ol-search-${isbn}.json`;
|
||||
return 'ol-title-search.json';
|
||||
}
|
||||
if (u.hostname === 'www.google.com') return `gb-isbn-${(u.searchParams.get('q') ?? '').replace('isbn:', '')}.xml`;
|
||||
if (locOverride) return locOverride;
|
||||
if (u.hostname === 'lccn.loc.gov') return `loc-lccn-${u.pathname.split('/')[1]}.xml`;
|
||||
const q = u.searchParams.get('query') ?? '';
|
||||
const m = /^bath\.isbn=(\d+)$/.exec(q);
|
||||
if (m) return `loc-isbn-${m[1]}.xml`;
|
||||
if (q.startsWith('bath.any=')) {
|
||||
if (q.startsWith('bath.any=') || q.startsWith('(bath.any=')) {
|
||||
const name = `loc-similar-${slug(q.replace(/bath\.any=/g, '').replace(/ and /g, ' '))}.xml`;
|
||||
return existsSync(join(DIR, name)) ? name : 'loc-isbn-9780999999998.xml'; // unknown keywords: zero records
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:dc='http://purl.org/dc/terms'><id>http://www.google.com/books/feeds/volumes</id><updated>2026-11-22T18:40:53.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Search results for isbn:9780692215005</title><link rel='alternate' type='text/html' href='http://www.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes?q=isbn%3A9780692215005'/><author><name>Google Books Search</name><uri>http://www.google.com</uri></author><generator version='beta'>Google Book Search data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>1</openSearch:itemsPerPage><entry><id>http://www.google.com/books/feeds/volumes/fWl0xAEACAAJ</id><updated>2026-11-22T18:40:53.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Backroads of Utah's San Rafael Swell</title><link rel='http://schemas.google.com/books/2008/info' type='text/html' href='http://books.google.com/books?id=fWl0xAEACAAJ&dq=isbn:9780692215005&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/preview' type='text/html' href='http://books.google.com/books?id=fWl0xAEACAAJ&dq=isbn:9780692215005&cd=1&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/annotation' type='application/atom+xml' href='http://www.google.com/books/feeds/users/me/volumes'/><link rel='alternate' type='text/html' href='http://books.google.com/books?id=fWl0xAEACAAJ&dq=isbn:9780692215005'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes/fWl0xAEACAAJ'/><gbs:contentVersion>preview-1.0.0</gbs:contentVersion><gbs:embeddability value='http://schemas.google.com/books/2008#not_embeddable'/><gbs:openAccess value='http://schemas.google.com/books/2008#disabled'/><gbs:viewability value='http://schemas.google.com/books/2008#view_no_pages'/><dc:creator>Christian Probasco</dc:creator><dc:date>2019-03</dc:date><dc:description>Guidebook to Utah&#39;s scenic San Rafael Swell</dc:description><dc:format>255 pages</dc:format><dc:format>book</dc:format><dc:identifier>fWl0xAEACAAJ</dc:identifier><dc:identifier>ISBN:069221500X</dc:identifier><dc:identifier>ISBN:9780692215005</dc:identifier><dc:language>en</dc:language><dc:title>Backroads of Utah's San Rafael Swell</dc:title></entry></feed>
|
||||
@@ -0,0 +1 @@
|
||||
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:dc='http://purl.org/dc/terms'><id>http://www.google.com/books/feeds/volumes</id><updated>2026-11-22T18:42:30.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Search results for isbn:9780984221356</title><link rel='alternate' type='text/html' href='http://www.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes?q=isbn%3A9780984221356'/><author><name>Google Books Search</name><uri>http://www.google.com</uri></author><generator version='beta'>Google Book Search data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>1</openSearch:itemsPerPage><entry><id>http://www.google.com/books/feeds/volumes/3VcVkgAACAAJ</id><updated>2026-11-22T18:42:30.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>The Best Durango Hikes</title><link rel='http://schemas.google.com/books/2008/thumbnail' type='image/x-unknown' href='http://books.google.com/books/content?id=3VcVkgAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/info' type='text/html' href='http://books.google.com/books?id=3VcVkgAACAAJ&dq=isbn:9780984221356&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/preview' type='text/html' href='http://books.google.com/books?id=3VcVkgAACAAJ&dq=isbn:9780984221356&cd=1&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/annotation' type='application/atom+xml' href='http://www.google.com/books/feeds/users/me/volumes'/><link rel='alternate' type='text/html' href='http://books.google.com/books?id=3VcVkgAACAAJ&dq=isbn:9780984221356'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes/3VcVkgAACAAJ'/><gbs:contentVersion>preview-1.0.0</gbs:contentVersion><gbs:embeddability value='http://schemas.google.com/books/2008#not_embeddable'/><gbs:openAccess value='http://schemas.google.com/books/2008#disabled'/><gbs:viewability value='http://schemas.google.com/books/2008#view_no_pages'/><dc:creator>The Colorado Mountain Club</dc:creator><dc:date>2011-04-18</dc:date><dc:description>The only guidebook you&#39;ll need to hike Durango, one of Colorado&#39;s great mountain towns</dc:description><dc:format>0 pages</dc:format><dc:format>book</dc:format><dc:identifier>3VcVkgAACAAJ</dc:identifier><dc:identifier>ISBN:0984221352</dc:identifier><dc:identifier>ISBN:9780984221356</dc:identifier><dc:language>en</dc:language><dc:publisher>Best Hikes</dc:publisher><dc:subject>Sports & Recreation</dc:subject><dc:title>The Best Durango Hikes</dc:title></entry></feed>
|
||||
@@ -0,0 +1 @@
|
||||
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:dc='http://purl.org/dc/terms'><id>http://www.google.com/books/feeds/volumes</id><updated>2026-11-22T18:41:20.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Search results for isbn:9781037052897</title><link rel='alternate' type='text/html' href='http://www.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes?q=isbn%3A9781037052897'/><author><name>Google Books Search</name><uri>http://www.google.com</uri></author><generator version='beta'>Google Book Search data API</generator><openSearch:totalResults>0</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>0</openSearch:itemsPerPage></feed>
|
||||
@@ -0,0 +1 @@
|
||||
<?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gbs='http://schemas.google.com/books/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:dc='http://purl.org/dc/terms'><id>http://www.google.com/books/feeds/volumes</id><updated>2026-11-22T18:40:26.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Search results for isbn:9798886472189</title><link rel='alternate' type='text/html' href='http://www.google.com'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes?q=isbn%3A9798886472189'/><author><name>Google Books Search</name><uri>http://www.google.com</uri></author><generator version='beta'>Google Book Search data API</generator><openSearch:totalResults>1</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>1</openSearch:itemsPerPage><entry><id>http://www.google.com/books/feeds/volumes/_JbW0QEACAAJ</id><updated>2026-11-22T18:40:26.000Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/books/2008#volume'/><title type='text'>Adventures of a Lifetime</title><link rel='http://schemas.google.com/books/2008/thumbnail' type='image/x-unknown' href='http://books.google.com/books/content?id=_JbW0QEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/info' type='text/html' href='http://books.google.com/books?id=_JbW0QEACAAJ&dq=isbn:9798886472189&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/preview' type='text/html' href='http://books.google.com/books?id=_JbW0QEACAAJ&dq=isbn:9798886472189&cd=1&source=gbs_gdata'/><link rel='http://schemas.google.com/books/2008/annotation' type='application/atom+xml' href='http://www.google.com/books/feeds/users/me/volumes'/><link rel='alternate' type='text/html' href='http://books.google.com/books?id=_JbW0QEACAAJ&dq=isbn:9798886472189'/><link rel='self' type='application/atom+xml' href='https://www.google.com/books/feeds/volumes/_JbW0QEACAAJ'/><gbs:contentVersion>preview-1.0.0</gbs:contentVersion><gbs:embeddability value='http://schemas.google.com/books/2008#not_embeddable'/><gbs:openAccess value='http://schemas.google.com/books/2008#disabled'/><gbs:viewability value='http://schemas.google.com/books/2008#view_no_pages'/><dc:creator>Becky Lomax</dc:creator><dc:creator>Moon Travel Guides</dc:creator><dc:date>2026-09-22</dc:date><dc:description>From rafting the Rio Grande at Big Bend, to looking out at Grand Prismatic Spring in Yellowstone, to driving Newfound Gap Road in Great Smoky Mountain National Park, to wildlife-watching for elk and bighorn sheep at Rocky Mountain National ...</dc:description><dc:format>0 pages</dc:format><dc:format>book</dc:format><dc:identifier>_JbW0QEACAAJ</dc:identifier><dc:identifier>ISBN:9798886472189</dc:identifier><dc:language>en</dc:language><dc:publisher>Moon Travel</dc:publisher><dc:subject>Photography</dc:subject><dc:title>Adventures of a Lifetime</dc:title><dc:title>Extraordinary Experiences in USA National Parks</dc:title></entry></feed>
|
||||
@@ -0,0 +1,56 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createGoogleBooks, parseGoogleBooks } from './googlebooks.ts';
|
||||
import { fixtureFetch } from './fixture-fetch.ts';
|
||||
import { TemporaryError, jobMemo } from './http.ts';
|
||||
|
||||
const fx = (isbn: string) => readFileSync(join(import.meta.dirname, 'fixtures', `gb-isbn-${isbn}.xml`), 'utf8');
|
||||
|
||||
test('Google Books feed: title, subtitle, authors, publisher, year and category', () => {
|
||||
const g = parseGoogleBooks(fx('9798886472189'), '9798886472189')!;
|
||||
assert.equal(g.meta.title, 'Adventures of a Lifetime');
|
||||
assert.equal(g.meta.subtitle, 'Extraordinary Experiences in USA National Parks');
|
||||
assert.deepEqual(g.meta.authors, ['Becky Lomax', 'Moon Travel Guides']);
|
||||
assert.equal(g.meta.publisher, 'Moon Travel');
|
||||
assert.equal(g.meta.year, 2026);
|
||||
assert.deepEqual(g.categories, ['Photography']);
|
||||
});
|
||||
|
||||
test('Google Books feed: a book with no subtitle, and an & in a category', () => {
|
||||
const g = parseGoogleBooks(fx('9780984221356'), '9780984221356')!;
|
||||
assert.equal(g.meta.title, 'The Best Durango Hikes');
|
||||
assert.equal(g.meta.subtitle, undefined);
|
||||
assert.deepEqual(g.meta.authors, ['The Colorado Mountain Club']);
|
||||
assert.ok(g.categories.includes('Sports & Recreation'));
|
||||
});
|
||||
|
||||
test('Google Books feed: no entries is null; a page that is not the feed is a temporary failure', () => {
|
||||
assert.equal(parseGoogleBooks(fx('9781037052897'), '9781037052897'), null);
|
||||
assert.throws(() => parseGoogleBooks('<html>blocked</html>', '1'), TemporaryError);
|
||||
});
|
||||
|
||||
test('Google Books client: asks the Atom feed with the generic agent, caches a hit, not a miss', async () => {
|
||||
const f = fixtureFetch();
|
||||
const map = new Map<string, string>();
|
||||
const gb = createGoogleBooks({ fetch: f.fetch, cache: { get: (k) => map.get(k) ?? null, set: (k, v) => { map.set(k, v); } } });
|
||||
assert.equal((await gb.byIsbn('9780692215005'))?.meta.title, "Backroads of Utah's San Rafael Swell");
|
||||
assert.match(f.calls[0]!, /^https:\/\/www\.google\.com\/books\/feeds\/volumes\?q=isbn%3A9780692215005$/);
|
||||
await gb.byIsbn('9780692215005');
|
||||
assert.equal(f.calls.length, 1);
|
||||
assert.equal(await gb.byIsbn('9781037052897'), null);
|
||||
assert.ok(!map.has('gb-isbn:9781037052897'));
|
||||
});
|
||||
|
||||
test('Google Books client: 5xx and 429 are temporary; a 404 is "no entry"; a retry inside one job does not ask twice', async () => {
|
||||
const status = (n: number) => (async () => new Response('x', { status: n })) as unknown as typeof fetch;
|
||||
const cache = { get: () => null, set: () => {} };
|
||||
await assert.rejects(createGoogleBooks({ fetch: status(503), cache }).byIsbn('1'), (e: unknown) => e instanceof TemporaryError && e.source === 'Google Books');
|
||||
await assert.rejects(createGoogleBooks({ fetch: status(429), cache }).byIsbn('1'), TemporaryError);
|
||||
assert.equal(await createGoogleBooks({ fetch: status(404), cache }).byIsbn('1'), null);
|
||||
const f = fixtureFetch();
|
||||
const gb = createGoogleBooks({ fetch: f.fetch, cache });
|
||||
await jobMemo.run(new Map(), async () => { await gb.byIsbn('9781037052897'); await gb.byIsbn('9781037052897'); });
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
import type { BookMeta } from '../../shared/types.ts';
|
||||
import { getText, trimPunct, TemporaryError, CONNECT_RETRY_DELAYS_MS, jobMemo } from './http.ts';
|
||||
import type { SourceCache } from './http.ts';
|
||||
|
||||
/** What Google Books knows about an ISBN: a title and who made it, never a call number. `categories` are its broad subject labels. */
|
||||
export interface GbInfo { meta: Partial<BookMeta>; categories: string[] }
|
||||
|
||||
/** The old Atom feed: needs no key (the JSON API answers 429 without one). One entry per volume. */
|
||||
const FEED = 'https://www.google.com/books/feeds/volumes';
|
||||
|
||||
// Namespace prefixes are kept: the entry's own <title> and <dc:title> must stay apart.
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: true, parseTagValue: false, trimValues: true,
|
||||
isArray: (name) => ['entry', 'dc:title', 'dc:creator', 'dc:subject', 'dc:publisher', 'dc:date'].includes(name),
|
||||
});
|
||||
|
||||
function strs(v: unknown): string[] {
|
||||
return (Array.isArray(v) ? v : []).filter((x): x is string => typeof x === 'string' && x.trim() !== '').map((s) => s.trim());
|
||||
}
|
||||
|
||||
const bare = (s: string): string => s.toLowerCase().replace(/^the\s+/, '').replace(/[^a-z0-9]+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* Parse the feed for one ISBN; null when it has no entry for it. The first dc:title is the title and the second the
|
||||
* subtitle. Entries are read in order and the first one that lists this ISBN wins (a search can return near misses).
|
||||
*/
|
||||
export function parseGoogleBooks(body: string, isbn: string): GbInfo | null {
|
||||
let root: Record<string, any>;
|
||||
try { root = parser.parse(body)?.feed; } catch { throw new TemporaryError('Google Books returned an unreadable page', { source: 'Google Books' }); }
|
||||
if (!root || typeof root !== 'object') throw new TemporaryError('Google Books returned an unexpected page', { source: 'Google Books' });
|
||||
const entries: Record<string, unknown>[] = Array.isArray(root['entry']) ? root['entry'] : [];
|
||||
for (const e of entries) {
|
||||
const ids = strs(e['dc:identifier']).concat(typeof e['dc:identifier'] === 'string' ? [e['dc:identifier']] : []);
|
||||
const listed = ids.some((i) => i.replace(/^ISBN:/i, '').replace(/-/g, '') === isbn) || ids.length === 0;
|
||||
const [title, subtitle] = strs(e['dc:title']);
|
||||
if (!title || !listed) continue;
|
||||
const meta: Partial<BookMeta> = { title: trimPunct(title), authors: [], subjects: [] };
|
||||
if (subtitle) meta.subtitle = trimPunct(subtitle);
|
||||
const seen = new Set<string>();
|
||||
for (const a of strs(e['dc:creator'])) { if (!seen.has(bare(a))) { seen.add(bare(a)); meta.authors!.push(a); } }
|
||||
const pub = strs(e['dc:publisher'])[0];
|
||||
if (pub) meta.publisher = trimPunct(pub);
|
||||
const y = /\b(1[0-9]\d\d|20\d\d)\b/.exec(strs(e['dc:date'])[0] ?? '');
|
||||
if (y) meta.year = Number(y[1]);
|
||||
return { meta, categories: [...new Set(strs(e['dc:subject']))] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface GoogleBooks {
|
||||
/** null when Google Books has no entry for this ISBN. Throws TemporaryError when it cannot be asked. */
|
||||
byIsbn(isbn: string): Promise<GbInfo | null>;
|
||||
}
|
||||
|
||||
export function createGoogleBooks(deps: { fetch: typeof fetch; cache: SourceCache }): GoogleBooks {
|
||||
return {
|
||||
async byIsbn(isbn) {
|
||||
const key = `gb-isbn:${isbn}`;
|
||||
const hit = deps.cache.get(key);
|
||||
if (hit !== null) return parseGoogleBooks(hit, isbn);
|
||||
const url = `${FEED}?${new URLSearchParams({ q: `isbn:${isbn}` })}`;
|
||||
// A definitive answer already given in this job is not asked for again after another request failed.
|
||||
const memo = jobMemo.getStore();
|
||||
const remembered = memo?.get(url);
|
||||
let text = remembered;
|
||||
if (text === undefined) {
|
||||
const res = await getText(deps.fetch, url, undefined, CONNECT_RETRY_DELAYS_MS);
|
||||
// Other 4xx: treat as "no entry" rather than an error.
|
||||
text = res.status >= 400 ? '' : res.body;
|
||||
if (text !== '' && !text.includes('<feed')) throw new TemporaryError('Google Books returned an unexpected page', { source: 'Google Books' });
|
||||
memo?.set(url, text);
|
||||
}
|
||||
if (text === '') return null;
|
||||
const info = parseGoogleBooks(text, isbn);
|
||||
if (info) deps.cache.set(key, text); // only a real record is cached, so a miss is asked again
|
||||
return info;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export function sourceName(url: string): string {
|
||||
let host = '';
|
||||
try { host = new URL(url).hostname; } catch { /* not a URL */ }
|
||||
if (host === 'openlibrary.org' || host.endsWith('.openlibrary.org')) return 'Open Library';
|
||||
if (host === 'www.google.com' || host === 'google.com' || host.endsWith('.googleapis.com')) return 'Google Books';
|
||||
if (host === 'loc.gov' || host.endsWith('.loc.gov')) return 'Library of Congress';
|
||||
return host || 'A lookup service';
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ export interface Loc {
|
||||
byKeywords(keywords: string[]): Promise<MarcFields[]>;
|
||||
/** Records whose title alone has every word (the `bath.title` index, unquoted so the words may be apart). */
|
||||
byTitleWords(words: string[]): Promise<MarcFields[]>;
|
||||
/** Records with every group of words: in a group, any one of its forms will do (hike or hikes or hiking). */
|
||||
byWordForms(groups: string[][]): Promise<MarcFields[]>;
|
||||
}
|
||||
|
||||
export function createLoc(deps: {
|
||||
@@ -111,6 +113,12 @@ export function createLoc(deps: {
|
||||
if (ws.length === 0) return Promise.resolve([]);
|
||||
return sru(`similar-loc-title:${ws.join(' ')}`, ws.map((w) => `bath.title=${w}`).join(' and '), 20);
|
||||
},
|
||||
byWordForms(groups) {
|
||||
const gs = groups.map((g) => [...new Set(g.map((k) => k.replace(/[^\p{L}\p{N}]/gu, '')).filter(Boolean))]).filter((g) => g.length > 0);
|
||||
if (gs.length === 0) return Promise.resolve([]);
|
||||
const query = gs.map((g) => (g.length > 1 ? `(${g.map((w) => `bath.any=${w}`).join(' or ')})` : `bath.any=${g[0]}`)).join(' and ');
|
||||
return sru(`similar-loc-forms:${gs.map((g) => g.join('|')).join(' ')}`, query, 20);
|
||||
},
|
||||
byKeywords(keywords) {
|
||||
const words = keywords.map((k) => k.replace(/[^\p{L}\p{N}]/gu, '')).filter(Boolean);
|
||||
if (words.length === 0) return Promise.resolve([]);
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface Book {
|
||||
hierarchyTail: string[] | null;
|
||||
/** The edition statement ("Third edition") from a record for this exact edition. null: not looked up yet; '': looked, none. */
|
||||
edition: string | null;
|
||||
/** When the catalogues were last asked about this book (ISO time); null for a book never looked up. */
|
||||
lookedUpAt: string | null;
|
||||
/** Only while a pending lookup is backing off after a temporary failure; kept in memory, not saved. */
|
||||
retry?: LookupRetry | null;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'pending', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
|
||||
printedAt: null, hierarchyTail: null, edition: null, lookedUpAt: null, createdAt: `2026-01-01T00:00:0${id}Z`, updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const ready = (id: number, over: Partial<Book> = {}) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id, ...over });
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, over: Partial<Book>): Book {
|
||||
id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null,
|
||||
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: false,
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: '', updatedAt: '', ...over,
|
||||
printedAt: null, hierarchyTail: null, edition: null, lookedUpAt: null, createdAt: '', updatedAt: '', ...over,
|
||||
};
|
||||
}
|
||||
const qa = (id: number, key: string) => book(id, { callNumber: 'QA76.73 .R87', sortKey: key });
|
||||
|
||||
@@ -8,7 +8,7 @@ function book(id: number, title: string, sortKey: string | null): Book {
|
||||
id, isbn13: null, lccn: null, title, subtitle: null, authors: [], publisher: null, year: null,
|
||||
subjects: [], callNumber: null, sortKey, confidence: null, source: null, dewey: null,
|
||||
status: 'resolved', attentionReason: null, manualOverride: false, inQueue: true,
|
||||
printedAt: null, hierarchyTail: null, edition: null, createdAt: '', updatedAt: '',
|
||||
printedAt: null, hierarchyTail: null, edition: null, lookedUpAt: null, createdAt: '', updatedAt: '',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user