Add QR codes to cards, stop inventing call number parts
Cards now carry a QR code holding the book's own record (call number, title, authors, ISBN, year), and the scanner reads it back to find or add that book. Call number selection no longer pads catalogue numbers with generated cutters. A number is "exact" only when it comes verbatim from a record for this edition; a bare class is a hint that steers the other-edition and similar-books lookups; a record fetched by LCCN must list the book's ISBN to count as this edition. "Look up again" bypasses every cached result, and shelf order breaks ties by author then title. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6cec404e21
commit
ad2956e868
56 files changed
+4020
-156
No files matched your search
+68
-1
@@ -10,7 +10,11 @@ const found: Resolution = {
|
||||
callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null,
|
||||
};
|
||||
|
||||
function setup(resolve = async () => found, port?: number) {
|
||||
function setupRecording(fresh: (boolean | undefined)[]) {
|
||||
return setup(async (_i?: unknown, o?: { fresh?: boolean }) => { fresh.push(o?.fresh ?? false); return found; });
|
||||
}
|
||||
|
||||
function setup(resolve: (i?: any, o?: any) => Promise<Resolution> = async () => found, port?: number) {
|
||||
const db = openDb(':memory:');
|
||||
const events = createEventBus();
|
||||
const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] };
|
||||
@@ -249,3 +253,66 @@ test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', as
|
||||
assert.equal(readdirSync(join(dir, 'captures')).length, 30);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('from-card: parses, adds a resolved book that is not queued, then finds it again', async () => {
|
||||
const { req, db } = setup();
|
||||
assert.equal((await req('POST', '/api/books/from-card', { text: 'https://example.com' })).status, 400);
|
||||
assert.equal((await req('POST', '/api/books/from-card', {})).status, 400);
|
||||
const text = 'PQ2230.A1 H8 1987 ~\nLes Misérables\nVictor Hugo\nbooksorter 1';
|
||||
const first = await (await req('POST', '/api/books/from-card', { text })).json() as any;
|
||||
assert.equal(first.existed, false);
|
||||
assert.equal(first.book.status, 'resolved');
|
||||
assert.equal(first.book.source, 'card');
|
||||
assert.equal(first.book.confidence, 'approximate');
|
||||
assert.equal(first.book.inQueue, false);
|
||||
assert.equal(first.book.callNumber, 'PQ2230.A1 H8 1987');
|
||||
assert.deepEqual(first.book.authors, ['Victor Hugo']);
|
||||
// same title (any case, padded) with the same call number is the same book; a different call number is not
|
||||
const again = await (await req('POST', '/api/books/from-card', { text: text.replace('Les Misérables', 'LES MISÉRABLES ') })).json() as any;
|
||||
assert.equal(again.existed, true);
|
||||
assert.equal(again.book.id, first.book.id);
|
||||
const other = await (await req('POST', '/api/books/from-card', { text: text.replace('H8', 'H9') })).json() as any;
|
||||
assert.equal(other.existed, false);
|
||||
assert.equal(db.listBooks().length, 2);
|
||||
});
|
||||
|
||||
test('from-card: a card with an ISBN matches by ISBN; cross-origin is refused', async () => {
|
||||
const { req, db } = setup(undefined, 4321);
|
||||
const text = 'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik\nISBN 9781593278281\n2018\nbooksorter 1';
|
||||
const made = await (await req('POST', '/api/books/from-card', { text }, { origin: 'http://localhost:4321' })).json() as any;
|
||||
assert.equal(made.book.isbn13, '9781593278281');
|
||||
assert.equal(made.book.year, 2018);
|
||||
const found = await (await req('POST', '/api/books/from-card', { text: text.replace('The Rust Programming Language', 'Other') }, { origin: 'http://localhost:4321' })).json() as any;
|
||||
assert.equal(found.existed, true);
|
||||
assert.equal(found.book.id, made.book.id);
|
||||
assert.equal((await req('POST', '/api/books/from-card', { text }, { origin: 'http://evil.example' })).status, 403);
|
||||
assert.equal(db.listBooks().length, 1);
|
||||
});
|
||||
|
||||
test('retry asks the lookup to ignore its caches', async () => {
|
||||
const fresh: (boolean | undefined)[] = [];
|
||||
const { req, jobs } = setupRecording(fresh);
|
||||
const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any;
|
||||
await jobs.idle();
|
||||
assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200);
|
||||
await jobs.idle();
|
||||
assert.deepEqual(fresh, [false, true]);
|
||||
});
|
||||
|
||||
test('print order and the book list break identical sort keys by author surname, then title', async () => {
|
||||
const { req, db, pdfCalls } = setup();
|
||||
const add = (title: string, authors: string[]) => db.insertPending({
|
||||
title, authors, callNumber: 'GV199.42 2020', sortKey: 'GV 0199.42 2020', confidence: 'approximate', source: 'ol-edition',
|
||||
status: 'resolved', manualOverride: false, inQueue: true,
|
||||
}).book;
|
||||
add('Zebra trails', ['Pat Young']); add('Sierra South', ['Kathy Morey']); add('Alpine', ['Pat Young']); add('Day hikes', ['Marlise Kast-Myers']);
|
||||
assert.deepEqual(db.listBooks().map((b) => b.title), ['Day hikes', 'Sierra South', 'Alpine', 'Zebra trails']);
|
||||
assert.equal((await req('GET', '/api/print.pdf')).status, 200);
|
||||
assert.deepEqual(pdfCalls[0]!.cards.map((c) => c.title), ['Day hikes', 'Sierra South', 'Alpine', 'Zebra trails']);
|
||||
});
|
||||
|
||||
test('a search result\'s LCCN (work-level) is not saved onto the book', async () => {
|
||||
const { req } = setup();
|
||||
const f = await (await req('POST', '/api/books/from-search', { result: { title: 'Hit', authors: ['X'], lccn: '96067014', lcc: [] } })).json() as any;
|
||||
assert.equal(f.book.lccn, null);
|
||||
});
|
||||
+28
-3
@@ -1,9 +1,11 @@
|
||||
import { mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { compareShelf } from '../shared/shelf.ts';
|
||||
import { join } from 'node:path';
|
||||
import { Hono } from 'hono';
|
||||
import type { Context } from 'hono';
|
||||
import type { Book, CardData, SearchResult, Settings } from '../shared/types.ts';
|
||||
import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
import { parseCardCode } from '../shared/cardcode.ts';
|
||||
import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts';
|
||||
import type { Db, Filter, NewBook } from './db.ts';
|
||||
import type { Jobs, ResolverLike } from './jobs.ts';
|
||||
@@ -153,6 +155,26 @@ export function createApp(deps: AppDeps): Hono {
|
||||
return c.json({ book: addPending({ lccn, title: lccn }).book });
|
||||
});
|
||||
|
||||
// A card's QR code carries the whole record, so the book is made straight from it, with no lookup. It is not
|
||||
// queued for printing: it already has its card.
|
||||
app.post('/api/books/from-card', async (c) => {
|
||||
const text = (await body(c)).text;
|
||||
const card = typeof text === 'string' ? parseCardCode(text) : null;
|
||||
if (!card) throw new HttpError(400, 'Not a Booksorter card');
|
||||
const sortKey = sortKeyOfRaw(card.callNumber);
|
||||
const title = card.title.trim();
|
||||
const same = (b: Book) => b.title.trim().toLowerCase() === title.toLowerCase() && b.sortKey === sortKey;
|
||||
const existing = card.isbn13 ? db.findByIsbn(card.isbn13) : db.listBooks().find(same) ?? null;
|
||||
if (existing) return c.json({ book: existing, existed: true });
|
||||
const { book, created } = db.insertPending({
|
||||
isbn13: card.isbn13, title: title || card.callNumber, authors: card.authors, year: card.year,
|
||||
callNumber: card.callNumber, sortKey, confidence: card.approximate ? 'approximate' : 'exact', source: 'card',
|
||||
status: 'resolved', manualOverride: false, inQueue: false,
|
||||
});
|
||||
if (created) events.emitBook(book);
|
||||
return c.json({ book, existed: !created });
|
||||
});
|
||||
|
||||
app.get('/api/search', async (c) => {
|
||||
const title = c.req.query('title')?.trim() ?? '';
|
||||
const author = c.req.query('author')?.trim() ?? '';
|
||||
@@ -166,7 +188,8 @@ export function createApp(deps: AppDeps): Hono {
|
||||
const title = r && str(r.title);
|
||||
if (!r || !title) throw new HttpError(400, 'A search result is required');
|
||||
const { book } = addPending({
|
||||
title, authors: strList(r.authors) ?? [], year: yearOf(r.year), publisher: str(r.publisher), lccn: str(r.lccn),
|
||||
title, authors: strList(r.authors) ?? [], year: yearOf(r.year), publisher: str(r.publisher),
|
||||
// (The result's LCCN is a work-level one: it may belong to another edition, so it is not saved.)
|
||||
});
|
||||
return c.json({ book });
|
||||
});
|
||||
@@ -238,9 +261,11 @@ export function createApp(deps: AppDeps): Hono {
|
||||
// "Look up again" must really ask again, so forget what the sources told us for this book.
|
||||
for (const key of cacheKeys(book)) db.cache.delete(key);
|
||||
if (book.title) db.cache.deletePrefix(`loc-title:${book.title}|`);
|
||||
// The title search and the similar-books searches are keyed by words as the lookup saw them (not necessarily
|
||||
// as stored now), so the lookup itself is told to ignore its cache and write fresh answers.
|
||||
const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!;
|
||||
events.emitBook(updated);
|
||||
jobs.enqueue(book.id);
|
||||
jobs.enqueue(book.id, { fresh: true });
|
||||
return c.json({ book: updated });
|
||||
});
|
||||
|
||||
@@ -249,7 +274,7 @@ export function createApp(deps: AppDeps): Hono {
|
||||
const startPosition = (s === 2 || s === 3 ? s : 1) as 1 | 2 | 3;
|
||||
const books = db.listBooks({ filter: 'queue' })
|
||||
.filter((b) => b.status === 'resolved' && b.callNumber)
|
||||
.sort((a, b) => ((a.sortKey ?? '~') < (b.sortKey ?? '~') ? -1 : (a.sortKey ?? '~') > (b.sortKey ?? '~') ? 1 : 0));
|
||||
.sort(compareShelf);
|
||||
if (!books.length) throw new HttpError(400, 'Nothing to print');
|
||||
const cards: CardData[] = books.map((b) => {
|
||||
const cn = parseCallNumber(b.callNumber!);
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { compareShelf } from '../shared/shelf.ts';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts';
|
||||
@@ -134,8 +135,8 @@ export function openDb(path: string): Db {
|
||||
params.push(needle, needle, needle, needle);
|
||||
}
|
||||
const sql = `SELECT * FROM books ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
|
||||
ORDER BY sort_key IS NULL, sort_key, title COLLATE NOCASE, id`;
|
||||
return (db.prepare(sql).all(...params) as Row[]).map(toBook);
|
||||
ORDER BY sort_key IS NULL, sort_key, id`;
|
||||
return (db.prepare(sql).all(...params) as Row[]).map(toBook).sort(compareShelf);
|
||||
},
|
||||
updateBook(id, patch) {
|
||||
const keys = Object.keys(patch).filter((k) => k in COLUMNS && (patch as Row)[k] !== undefined) as (keyof BookPatch)[];
|
||||
|
||||
+13
-6
@@ -6,7 +6,12 @@ export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
|
||||
|
||||
export type ResolverLike = Resolver;
|
||||
|
||||
export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise<void> }
|
||||
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;
|
||||
resume(): void;
|
||||
idle(): Promise<void>;
|
||||
}
|
||||
|
||||
// TemporaryError lives in resolve/resolver.ts; match by class name unless the caller injects a test.
|
||||
function defaultIsTemporary(e: unknown): boolean {
|
||||
@@ -35,6 +40,7 @@ export function createJobs(deps: {
|
||||
const queue: number[] = [];
|
||||
const queued = new Set<number>();
|
||||
const attempts = new Map<number, number>();
|
||||
const fresh = new Set<number>();
|
||||
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
|
||||
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
let running: Promise<void> | null = null;
|
||||
@@ -77,7 +83,7 @@ export function createJobs(deps: {
|
||||
|
||||
async function attempt(id: number): Promise<void> {
|
||||
const book = db.getBook(id);
|
||||
if (!book || book.status !== 'pending') { attempts.delete(id); return; }
|
||||
if (!book || book.status !== 'pending') { attempts.delete(id); fresh.delete(id); return; }
|
||||
const n = attempts.get(id) ?? 0;
|
||||
const final = n >= delays.length;
|
||||
const input: ResolveInput = {};
|
||||
@@ -93,8 +99,8 @@ export function createJobs(deps: {
|
||||
let similar = '';
|
||||
const took = () => `${Date.now() - started} ms`;
|
||||
try {
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, onSimilar: (d) => { similar = d; } });
|
||||
attempts.delete(id);
|
||||
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, fresh: fresh.has(id), onSimilar: (d) => { similar = d; } });
|
||||
attempts.delete(id); fresh.delete(id);
|
||||
const cur = db.getBook(id);
|
||||
if (!cur) return;
|
||||
if (res.meta) applyMeta(id, res.meta);
|
||||
@@ -123,7 +129,7 @@ export function createJobs(deps: {
|
||||
schedule(id, delay);
|
||||
return;
|
||||
}
|
||||
attempts.delete(id);
|
||||
attempts.delete(id); fresh.delete(id);
|
||||
log(`[lookup] ${label}: failed, ${message} in ${took()}`);
|
||||
const cur = db.getBook(id);
|
||||
if (cur && !cur.manualOverride) {
|
||||
@@ -146,7 +152,8 @@ export function createJobs(deps: {
|
||||
}
|
||||
|
||||
return {
|
||||
enqueue(id) {
|
||||
enqueue(id, opts) {
|
||||
if (opts?.fresh) fresh.add(id);
|
||||
// A fresh request (scan, "Look up again") overrides any wait and starts the retries over.
|
||||
const t = waiting.get(id);
|
||||
if (t) { clearTimeout(t); waiting.delete(id); attempts.delete(id); }
|
||||
|
||||
@@ -74,3 +74,13 @@ test('omitted pieces: no subclass duplicate, no isbn, no tilde', () => {
|
||||
assert.equal(runs.filter((r) => r.text === 'Science').length, 1);
|
||||
assert.ok(!runs.some((r) => r.text.startsWith('ISBN') || r.text === '~'));
|
||||
});
|
||||
|
||||
test('no text block goes below y 132 (room for the QR code)', () => {
|
||||
const many: CardData = {
|
||||
...base, title: 'A long title '.repeat(12), authors: ['One Author', 'Two Author', 'Three Author'],
|
||||
subjects: ['A long first subject heading '.repeat(4), 'A long second subject heading '.repeat(4)],
|
||||
};
|
||||
const runs = layoutCard(many, measure);
|
||||
assert.ok(runs.filter((r) => r.y > 20).every((r) => r.y > 132));
|
||||
assert.ok(runs.some((r) => r.text.startsWith('ISBN') && r.y === 16));
|
||||
});
|
||||
@@ -10,7 +10,8 @@ export const RULE_Y = 286;
|
||||
const GRAY = 0.35;
|
||||
const BLOCK_START = 268;
|
||||
const BLOCK_GAP = 8;
|
||||
const BLOCK_FLOOR = 30;
|
||||
/** Text stays above the QR code: its top edge is y 122 plus 9 pt of clear space, rounded up. */
|
||||
const BLOCK_FLOOR = 132;
|
||||
const ELLIPSIS = '…';
|
||||
|
||||
/** Largest size (1 pt steps, down to min) at which text fits; text is truncated if min still overflows. */
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { test, before } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
|
||||
import { qrMatrix, qrRects, QR_BOTTOM, QR_SIZE, QR_TOP, QR_X } from './qr.ts';
|
||||
import { encodeCardCode, parseCardCode } from '../../shared/cardcode.ts';
|
||||
import type { CardCode } from '../../shared/cardcode.ts';
|
||||
|
||||
const short = 'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik; Carol Nichols\nISBN 9781718500440\n2018\nbooksorter 1';
|
||||
|
||||
test('the symbol is 90 pt square, flush left, from y 32 to 122, for any version', () => {
|
||||
const longest = encodeCardCode({
|
||||
callNumber: 'QA76.73.C153 S77 K47 2013', approximate: true, title: 'x'.repeat(200), authors: ['a'.repeat(60)], isbn13: '9781718500440', year: 2018,
|
||||
});
|
||||
for (const payload of [short, longest, 'booksorter 1']) {
|
||||
const { rects, version } = qrRects(payload);
|
||||
assert.ok(version >= 1 && version <= 6, `version ${version}`);
|
||||
const x0 = Math.min(...rects.map(r => r.x)), x1 = Math.max(...rects.map(r => r.x + r.width));
|
||||
const y0 = Math.min(...rects.map(r => r.y)), y1 = Math.max(...rects.map(r => r.y + r.height));
|
||||
// finder patterns sit in every corner except bottom-right, so all four edges are touched
|
||||
assert.ok(Math.abs(x0 - QR_X) < 1e-9 && Math.abs(x1 - (QR_X + QR_SIZE)) < 1e-9);
|
||||
assert.ok(Math.abs(y0 - QR_BOTTOM) < 1e-9 && Math.abs(y1 - QR_TOP) < 1e-9);
|
||||
assert.equal(QR_X, 14);
|
||||
}
|
||||
});
|
||||
|
||||
test('horizontal runs are merged: rectangles cover exactly the dark modules', () => {
|
||||
const m = qrMatrix(short), n = m.length, mod = QR_SIZE / n;
|
||||
const { rects } = qrRects(short);
|
||||
let dark = 0;
|
||||
for (const row of m) for (const v of row) if (v) dark++;
|
||||
const area = rects.reduce((a, r) => a + r.width * r.height, 0);
|
||||
assert.ok(Math.abs(area - dark * mod * mod) < 1e-6);
|
||||
assert.ok(rects.length < dark);
|
||||
for (const r of rects) assert.ok(Math.abs(r.height - mod) < 1e-9);
|
||||
});
|
||||
|
||||
// ---- round trip: draw the symbol into pixels and read it back with zxing-wasm ----------------------
|
||||
before(async () => {
|
||||
const wasm = readFileSync(createRequire(import.meta.url).resolve('zxing-wasm/reader').replace(/dist[\\/].*$/, 'dist/reader/zxing_reader.wasm'));
|
||||
await prepareZXingModule({ overrides: { wasmBinary: wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength) as ArrayBuffer }, fireImmediately: true });
|
||||
});
|
||||
|
||||
function raster(matrix: boolean[][], px = 6, quiet = 4): { data: Uint8ClampedArray; width: number; height: number } {
|
||||
const n = matrix.length, size = (n + 2 * quiet) * px, data = new Uint8ClampedArray(size * size * 4).fill(255);
|
||||
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
|
||||
if (!matrix[r]![c]) continue;
|
||||
for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {
|
||||
const i = (((r + quiet) * px + y) * size + (c + quiet) * px + x) * 4;
|
||||
data[i] = data[i + 1] = data[i + 2] = 0;
|
||||
}
|
||||
}
|
||||
return { data, width: size, height: size };
|
||||
}
|
||||
|
||||
test('a printed symbol with a non-ASCII title reads back to the same payload', async () => {
|
||||
const card: CardCode = {
|
||||
callNumber: 'PQ2230.A1 H8 1987', approximate: false, title: 'Les Misérables',
|
||||
authors: ['Victor Hugo'], isbn13: '9780140444308', year: 1987,
|
||||
};
|
||||
const payload = encodeCardCode(card);
|
||||
const [hit] = await readBarcodes(raster(qrMatrix(payload)) as ImageData, { formats: ['QRCode'], tryHarder: true });
|
||||
assert.ok(hit, 'zxing found no QR code');
|
||||
assert.equal(hit.format, 'QRCode');
|
||||
assert.equal(hit.text, payload);
|
||||
assert.deepEqual(parseCardCode(hit.text), card);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import qrcode from 'qrcode-generator';
|
||||
|
||||
/** Card-local geometry of the QR symbol (dark-module area, not counting the quiet zone). */
|
||||
export const QR_SIZE = 90;
|
||||
export const QR_X = 14; // flush with the text margin (MARGIN_X in card.ts)
|
||||
export const QR_BOTTOM = 32;
|
||||
export const QR_TOP = QR_BOTTOM + QR_SIZE;
|
||||
/** Nothing else is drawn within this distance of the symbol. */
|
||||
export const QR_CLEAR = 9;
|
||||
|
||||
// The payload is UTF-8; the library's default byte encoder is not.
|
||||
qrcode.stringToBytes = (s: string) => Array.from(new TextEncoder().encode(s));
|
||||
|
||||
/** Dark modules of the smallest error-level-L byte-mode symbol that holds the payload: matrix[row][col]. */
|
||||
export function qrMatrix(payload: string): boolean[][] {
|
||||
const qr = qrcode(0, 'L');
|
||||
qr.addData(payload, 'Byte');
|
||||
qr.make();
|
||||
const n = qr.getModuleCount();
|
||||
return Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => qr.isDark(r, c)));
|
||||
}
|
||||
|
||||
export interface Rect { x: number; y: number; width: number; height: number }
|
||||
|
||||
/**
|
||||
* Filled rectangles (card-local points) for the dark modules, scaled so the symbol is QR_SIZE square.
|
||||
* Each horizontal run of dark modules is one rectangle, so there are no hairline gaps between neighbours.
|
||||
*/
|
||||
export function qrRects(payload: string): { version: number; rects: Rect[] } {
|
||||
const m = qrMatrix(payload), n = m.length, module = QR_SIZE / n;
|
||||
const rects: Rect[] = [];
|
||||
for (let r = 0; r < n; r++) {
|
||||
let c = 0;
|
||||
while (c < n) {
|
||||
if (!m[r]![c]) { c++; continue; }
|
||||
let end = c;
|
||||
while (end < n && m[r]![end]) end++;
|
||||
rects.push({ x: QR_X + c * module, y: QR_TOP - (r + 1) * module, width: (end - c) * module, height: module });
|
||||
c = end;
|
||||
}
|
||||
}
|
||||
return { version: (n - 17) / 4, rects };
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import fontkit from '@pdf-lib/fontkit';
|
||||
import type { CardData, Settings } from '../../shared/types.ts';
|
||||
import { layoutCard, MARGIN_X, TEXT_WIDTH, RULE_Y } from './card.ts';
|
||||
import { SHEET, CARD, cardMatrix } from './layout.ts';
|
||||
import { qrRects } from './qr.ts';
|
||||
import { encodeCardCode } from '../../shared/cardcode.ts';
|
||||
|
||||
interface Fonts { regular: PDFFont; bold: PDFFont; has: (cp: number) => boolean }
|
||||
|
||||
@@ -64,6 +66,12 @@ function drawCard(page: PDFPage, card: CardData, fonts: Fonts) {
|
||||
x: r.x, y: r.y, size: r.size, font: r.bold ? fonts.bold : fonts.regular, color: rgb(r.gray, r.gray, r.gray),
|
||||
});
|
||||
}
|
||||
// The payload carries the real text, not the font-safe copy the card text is drawn from.
|
||||
const payload = encodeCardCode({
|
||||
callNumber: card.callNumber, approximate: card.approximate, title: card.title,
|
||||
authors: card.authors, isbn13: card.isbn13, year: card.year,
|
||||
});
|
||||
for (const r of qrRects(payload).rects) page.drawRectangle({ ...r, color: rgb(0, 0, 0), borderWidth: 0 });
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: RULE_Y }, end: { x: MARGIN_X + TEXT_WIDTH, y: RULE_Y },
|
||||
thickness: 0.75, color: rgb(0, 0, 0),
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chooseCallNumber } from './choose.ts';
|
||||
import { bareClassResult, chooseCallNumber, findHint } from './choose.ts';
|
||||
import type { Tiers } from './choose.ts';
|
||||
|
||||
const none: Tiers = { locExact: [], olEdition: [], locTitle: [], olWork: [] };
|
||||
const raws = (...r: string[]) => r.map((raw) => ({ raw }));
|
||||
const m = { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language' };
|
||||
const m = {};
|
||||
|
||||
test('LoC exact complete', () => {
|
||||
test('LoC exact complete is used verbatim', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
|
||||
assert.equal(r?.confidence, 'exact');
|
||||
@@ -19,13 +19,38 @@ test('exact source is passed through', () => {
|
||||
assert.equal(r?.source, 'loc-lccn');
|
||||
});
|
||||
|
||||
test('an edition number with one cutter is used verbatim: no cutter and no year added', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, { year: 2018 });
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87');
|
||||
assert.equal(r?.confidence, 'exact');
|
||||
const loc = chooseCallNumber({ ...none, locExact: [{ raw: 'PS3552.R89' }] }, { year: 2010 });
|
||||
assert.equal(loc?.callNumber, 'PS3552.R89');
|
||||
assert.equal(loc?.confidence, 'exact');
|
||||
});
|
||||
|
||||
test('LoC is preferred over Open Library when both have a number', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: raws('QA76.73.R87 K53 2018'), olEdition: raws('QA76.73.C15 K47 1988') }, m);
|
||||
assert.equal(r?.source, 'loc-isbn');
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
|
||||
});
|
||||
|
||||
test('a bare LoC class does not stop an Open Library edition number', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: raws('QA76.73'), olEdition: raws('QA76.73.R87 K53 2018') }, m);
|
||||
assert.equal(r?.source, 'ol-edition');
|
||||
assert.equal(r?.confidence, 'exact');
|
||||
});
|
||||
|
||||
test('OL edition most frequent after normalizing', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.C15 K47 1988', 'QA76.73.C15 .K4718 1991', 'QA76.73.C15K47 1988') }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.73.C15 K47 1988');
|
||||
assert.equal(r?.confidence, 'exact');
|
||||
assert.equal(r?.source, 'ol-edition');
|
||||
});
|
||||
|
||||
test('a record with a 050 $b outranks a more frequent one without evidence', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: [{ raw: 'QA76.A1', complete: false }, { raw: 'QA76.A1', complete: false }, { raw: 'QA76.B2 C3', complete: true }] }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.B2 C3');
|
||||
});
|
||||
|
||||
test('legacy PZ3 dropped when literature class present', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('PZ3.H4186 Du', 'PS3558.E63 D8 2005') }, m);
|
||||
assert.equal(r?.callNumber, 'PS3558.E63 D8 2005');
|
||||
@@ -37,27 +62,22 @@ test('PZ kept when it is the only class', () => {
|
||||
});
|
||||
|
||||
test('LoC title: approximate, year replaced', () => {
|
||||
const r = chooseCallNumber({ ...none, locTitle: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, { ...m, year: 2023 });
|
||||
const r = chooseCallNumber({ ...none, locTitle: [{ raw: 'QA76.73.R87 K53 2018', complete: true }] }, { year: 2023 });
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2023');
|
||||
assert.equal(r?.confidence, 'approximate');
|
||||
assert.equal(r?.source, 'loc-title');
|
||||
});
|
||||
|
||||
test('OL work: padded class gets cutter and year', () => {
|
||||
const r = chooseCallNumber({ ...none, olWork: raws('QA-0076.76000000.A65') }, { ...m, year: 2018 });
|
||||
test('other editions: a bare class is not a number, even with a year to add', () => {
|
||||
assert.equal(chooseCallNumber({ ...none, olWork: raws('QA-0076.76000000') }, { year: 2018 }), null);
|
||||
const r = chooseCallNumber({ ...none, olWork: raws('QA-0076.76000000', 'QA-0076.76000000.A65 K53 2001') }, { year: 2018 });
|
||||
assert.equal(r?.callNumber, 'QA76.76.A65 K53 2018');
|
||||
assert.equal(r?.confidence, 'approximate');
|
||||
assert.equal(r?.source, 'ol-work');
|
||||
});
|
||||
|
||||
test('incomplete exact candidate with unknown year gets cutter only', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53');
|
||||
});
|
||||
|
||||
test('tie goes to the longest first line', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.A1 2000', 'QA76.73.R87 K53 2018') }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
|
||||
test('an incomplete bare class gets nothing generated', () => {
|
||||
assert.equal(chooseCallNumber({ ...none, olEdition: raws('QA76.73') }, { year: 2018 }), null);
|
||||
});
|
||||
|
||||
test('earlier tier wins over later tiers', () => {
|
||||
@@ -69,14 +89,53 @@ test('unparseable only -> null', () => {
|
||||
assert.equal(chooseCallNumber({ ...none, olEdition: raws('[E]', 'Fic') }, m), null);
|
||||
});
|
||||
|
||||
test('literature class-only number with the author cutter gets a title cutter', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'Dune', year: 2010 });
|
||||
assert.equal(r?.callNumber, 'PS3552.R89 D86 2010');
|
||||
const the = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'The Dune' });
|
||||
assert.equal(the?.callNumber, 'PS3552.R89 D86');
|
||||
test('hint: found from a bare class, LoC before Open Library', () => {
|
||||
assert.deepEqual(findHint({ locExact: raws('GV199.42'), olEdition: raws('GV199.62') }, 'loc-lccn'), { cls: 'GV199.42', source: 'loc-lccn' });
|
||||
assert.deepEqual(findHint({ locExact: [], olEdition: raws('', 'GV199.42') }), { cls: 'GV199.42', source: 'ol-edition' });
|
||||
assert.equal(findHint({ locExact: raws('GV199.42.S55'), olEdition: [] }), null);
|
||||
});
|
||||
|
||||
test('non-literature class-only numbers still get the author cutter', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language', year: 2018 });
|
||||
test('hint: other editions are used only inside the hinted class', () => {
|
||||
const hint = { cls: 'GV199.42', source: 'ol-edition' as const };
|
||||
const t = { ...none, locTitle: raws('GV199.62.C57 2011'), olWork: raws('GV-0199.42000000.S55 M663 2006') };
|
||||
const r = chooseCallNumber(t, { year: 2020 }, 'loc-isbn', hint);
|
||||
assert.equal(r?.callNumber, 'GV199.42.S55 M663 2020');
|
||||
assert.equal(r?.source, 'ol-work');
|
||||
// Without a hint the first tier wins as before.
|
||||
assert.equal(chooseCallNumber(t, { year: 2020 })?.callNumber, 'GV199.62.C57 2020');
|
||||
// Hint present but no edition in that class: nothing.
|
||||
assert.equal(chooseCallNumber({ ...none, locTitle: raws('QA76.73.R87 K53 2018') }, { year: 2020 }, 'loc-isbn', hint), null);
|
||||
});
|
||||
|
||||
test('bare class fallback: class and year only, source of the hint, approximate', () => {
|
||||
const r = bareClassResult({ cls: 'GV199.42', source: 'ol-edition' }, 2020);
|
||||
assert.equal(r?.callNumber, 'GV199.42 2020');
|
||||
assert.equal(r?.confidence, 'approximate');
|
||||
assert.equal(r?.source, 'ol-edition');
|
||||
assert.equal(bareClassResult({ cls: 'GV199.42', source: 'loc-isbn' })?.callNumber, 'GV199.42');
|
||||
});
|
||||
|
||||
test('a LoC 050 with only $a yields to an Open Library number that says the same and more', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: [{ raw: 'GV199.42.S55', complete: false }], olEdition: raws('GV199.42.S55 S54 2020') }, m);
|
||||
assert.equal(r?.callNumber, 'GV199.42.S55 S54 2020');
|
||||
assert.equal(r?.source, 'ol-edition');
|
||||
// A different class or different cutters is not an extension: LoC stays.
|
||||
const other = chooseCallNumber({ ...none, locExact: [{ raw: 'GV199.42.S55', complete: false }], olEdition: raws('GV199.42.C2 S54 2020') }, m);
|
||||
assert.equal(other?.callNumber, 'GV199.42.S55');
|
||||
// With a $b, LoC is complete and stays.
|
||||
const full = chooseCallNumber({ ...none, locExact: [{ raw: 'GV199.42.S55 A1', complete: true }], olEdition: raws('GV199.42.S55 A1 2020') }, m);
|
||||
assert.equal(full?.source, 'loc-isbn');
|
||||
});
|
||||
|
||||
test('a candidate carries its own LoC source (by ISBN or by LCCN)', () => {
|
||||
const r = chooseCallNumber({ ...none, locExact: [
|
||||
{ raw: 'GV199.42.C2', complete: false, source: 'loc-lccn' }, { raw: 'GV199.42.C2 S73 2019', complete: true, source: 'loc-isbn' },
|
||||
] }, m, 'loc-lccn');
|
||||
assert.equal(r?.callNumber, 'GV199.42.C2 S73 2019');
|
||||
assert.equal(r?.source, 'loc-isbn');
|
||||
});
|
||||
|
||||
test('tie goes to the longest first line', () => {
|
||||
const r = chooseCallNumber({ ...none, olEdition: raws('QA76.A1 2000', 'QA76.73.R87 K53 2018') }, m);
|
||||
assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018');
|
||||
});
|
||||
@@ -1,17 +1,21 @@
|
||||
import type { Candidate, Source } from '../../shared/types.ts';
|
||||
import type { CallNumber } from '../../shared/callnumber.ts';
|
||||
import { cardLines, formatCallNumber, hasYear, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts';
|
||||
import { cutterFor, mainEntry } from '../../shared/cutter.ts';
|
||||
import { cardLines, classKey, formatCallNumber, hasYear, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts';
|
||||
|
||||
export interface Tiers { locExact: Candidate[]; olEdition: Candidate[]; locTitle: Candidate[]; olWork: Candidate[] }
|
||||
|
||||
interface Parsed { cn: CallNumber; complete: boolean | undefined; formatted: string }
|
||||
export interface Chosen { callNumber: string; sortKey: string; confidence: 'exact' | 'approximate'; source: Source }
|
||||
|
||||
/** A bare class (no cutters) from this edition's own record: where the book belongs, but not a full number. */
|
||||
export interface Hint { cls: string; source: Source }
|
||||
|
||||
interface Parsed { cn: CallNumber; complete: boolean | undefined; formatted: string; source: Source | undefined }
|
||||
|
||||
function parseAll(cands: Candidate[]): Parsed[] {
|
||||
const out: Parsed[] = [];
|
||||
for (const c of cands) {
|
||||
const cn = parseCallNumber(c.raw);
|
||||
if (cn) out.push({ cn, complete: c.complete, formatted: formatCallNumber(cn) });
|
||||
if (cn) out.push({ cn, complete: c.complete, formatted: formatCallNumber(cn), source: c.source });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -22,13 +26,18 @@ function dropLegacyFiction(ps: Parsed[]): Parsed[] {
|
||||
return ps.some(legacy) && ps.some(literature) ? ps.filter((p) => !legacy(p)) : ps;
|
||||
}
|
||||
|
||||
function pickMostFrequent(ps: Parsed[]): { cn: CallNumber; complete: boolean } {
|
||||
/** Among numbers with at least one cutter: records with real evidence of completeness (an LoC 050 $b) first, then the most frequent. */
|
||||
function pickBest(ps: Parsed[]): { cn: CallNumber; complete: boolean; source?: Source } | null {
|
||||
const groups = new Map<string, Parsed[]>();
|
||||
for (const p of ps) {
|
||||
if (p.cn.cutters.length === 0) continue;
|
||||
const g = groups.get(p.formatted);
|
||||
if (g) g.push(p); else groups.set(p.formatted, [p]);
|
||||
}
|
||||
if (groups.size === 0) return null;
|
||||
const ranked = [...groups.values()].sort((a, b) => {
|
||||
const ca = a.some((p) => p.complete === true), cb = b.some((p) => p.complete === true);
|
||||
if (ca !== cb) return ca ? -1 : 1;
|
||||
if (a.length !== b.length) return b.length - a.length;
|
||||
const la = cardLines(a[0]!.cn)[0].length;
|
||||
const lb = cardLines(b[0]!.cn)[0].length;
|
||||
@@ -38,40 +47,80 @@ function pickMostFrequent(ps: Parsed[]): { cn: CallNumber; complete: boolean } {
|
||||
return ka < kb ? -1 : ka > kb ? 1 : 0;
|
||||
});
|
||||
const g = ranked[0]!;
|
||||
const cn = g[0]!.cn;
|
||||
const explicit = g.find((p) => p.complete !== undefined)?.complete;
|
||||
return { cn, complete: explicit ?? (hasYear(cn) || cn.cutters.length >= 2) };
|
||||
const src = g.find((p) => p.source)?.source;
|
||||
return { cn: g[0]!.cn, complete: g.some((p) => p.complete === true), ...(src ? { source: src } : {}) };
|
||||
}
|
||||
|
||||
const TIER_SOURCE: Record<keyof Tiers, Source> = {
|
||||
locExact: 'loc-isbn', olEdition: 'ol-edition', locTitle: 'loc-title', olWork: 'ol-work',
|
||||
};
|
||||
|
||||
export function chooseCallNumber(
|
||||
tiers: Tiers,
|
||||
meta: { authors: string[]; title: string; year?: number },
|
||||
exactSource?: 'loc-isbn' | 'loc-lccn',
|
||||
): { callNumber: string; sortKey: string; confidence: 'exact' | 'approximate'; source: Source } | null {
|
||||
const order: (keyof Tiers)[] = ['locExact', 'olEdition', 'locTitle', 'olWork'];
|
||||
for (const tier of order) {
|
||||
const ps = dropLegacyFiction(parseAll(tiers[tier]));
|
||||
/**
|
||||
* The bare class this edition's own records give, if they give one: it steers the later tiers.
|
||||
* LoC first. Only meaningful when no own record has a full number.
|
||||
*/
|
||||
export function findHint(
|
||||
tiers: Pick<Tiers, 'locExact' | 'olEdition'>, exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn',
|
||||
): Hint | null {
|
||||
for (const tier of ['locExact', 'olEdition'] as const) {
|
||||
const ps = dropLegacyFiction(parseAll(tiers[tier])).filter((p) => p.cn.cutters.length === 0);
|
||||
if (ps.length === 0) continue;
|
||||
const approximate = tier === 'locTitle' || tier === 'olWork';
|
||||
let { cn, complete } = pickMostFrequent(ps);
|
||||
if (!complete && cn.cutters.length < 3) {
|
||||
// Literature (P plus one letter) already carries the author as its first cutter; the next one is the title.
|
||||
const literature = /^P[A-Z]$/.test(cn.letters) && cn.cutters.length >= 1;
|
||||
const c = cutterFor(literature ? meta.title.trim().replace(/^(a|an|the)\s+/i, '') : mainEntry(meta.authors, meta.title));
|
||||
cn = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }] };
|
||||
if (meta.year) cn = withYear(cn, meta.year);
|
||||
}
|
||||
if (approximate && meta.year) cn = withYear(cn, meta.year);
|
||||
return {
|
||||
callNumber: formatCallNumber(cn),
|
||||
sortKey: sortKey(cn),
|
||||
confidence: approximate ? 'approximate' : 'exact',
|
||||
source: tier === 'locExact' ? (exactSource ?? 'loc-isbn') : TIER_SOURCE[tier],
|
||||
};
|
||||
// Most frequent class; ties go to the more specific (longer) class.
|
||||
const count = new Map<string, number>();
|
||||
for (const p of ps) count.set(classKey(p.cn), (count.get(classKey(p.cn)) ?? 0) + 1);
|
||||
const cls = [...count].sort((a, b) => b[1] - a[1] || b[0].length - a[0].length || (a[0] < b[0] ? -1 : 1))[0]![0];
|
||||
return { cls, source: tier === 'locExact' ? exactSource : TIER_SOURCE[tier] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick a number from the tiers that have one with at least one cutter; nothing is invented.
|
||||
* This edition's own records (locExact, then olEdition) are used verbatim and are `exact`.
|
||||
* Other editions (locTitle, olWork) are `approximate`, with this edition's year in place of theirs;
|
||||
* when a class hint exists, only numbers in the hinted class qualify.
|
||||
*/
|
||||
export function chooseCallNumber(
|
||||
tiers: Tiers,
|
||||
meta: { year?: number },
|
||||
exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn',
|
||||
hint?: Hint | null,
|
||||
): Chosen | null {
|
||||
// This edition's own records. LoC wins, unless its number has no evidence of being complete (a 050 with only $a)
|
||||
// and Open Library's number for the same edition says the same thing and more.
|
||||
const pickOwn = (tier: 'locExact' | 'olEdition') => pickBest(dropLegacyFiction(parseAll(tiers[tier])));
|
||||
const loc = pickOwn('locExact');
|
||||
const ol = pickOwn('olEdition');
|
||||
const useOl = ol && (!loc || (!loc.complete && extendsNumber(ol.cn, loc.cn)));
|
||||
const own = useOl ? { ...ol, tier: 'olEdition' as const } : loc ? { ...loc, tier: 'locExact' as const } : null;
|
||||
if (own) {
|
||||
return {
|
||||
callNumber: formatCallNumber(own.cn), sortKey: sortKey(own.cn), confidence: 'exact',
|
||||
source: own.tier === 'locExact' ? (own.source ?? exactSource) : TIER_SOURCE.olEdition,
|
||||
};
|
||||
}
|
||||
for (const tier of ['locTitle', 'olWork'] as const) {
|
||||
let ps = dropLegacyFiction(parseAll(tiers[tier]));
|
||||
if (hint) ps = ps.filter((p) => classKey(p.cn) === hint.cls);
|
||||
const best = pickBest(ps);
|
||||
if (!best) continue;
|
||||
const cn = meta.year ? withYear(best.cn, meta.year) : best.cn;
|
||||
return { callNumber: formatCallNumber(cn), sortKey: sortKey(cn), confidence: 'approximate', source: TIER_SOURCE[tier] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Does `longer` say the same as `shorter` (same class, same leading cutters) and more (further cutters or a year)? */
|
||||
function extendsNumber(longer: CallNumber, shorter: CallNumber): boolean {
|
||||
if (classKey(longer) !== classKey(shorter)) return false;
|
||||
if (shorter.cutters.some((c, i) => longer.cutters[i]?.letter !== c.letter || longer.cutters[i]?.digits !== c.digits)) return false;
|
||||
return longer.cutters.length > shorter.cutters.length || (hasYear(longer) && !hasYear(shorter));
|
||||
}
|
||||
|
||||
/** Last resort for a bare class: the class and this edition's year, nothing generated. */
|
||||
export function bareClassResult(hint: Hint, year?: number): Chosen | null {
|
||||
const cn = parseCallNumber(hint.cls);
|
||||
if (!cn) return null;
|
||||
const out = year ? withYear(cn, year) : cn;
|
||||
return { callNumber: formatCallNumber(out), sortKey: sortKey(out), confidence: 'approximate', source: hint.source };
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
||||
import { normalizeTitle, recordMatches, titlesMatch } from './match.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [] });
|
||||
const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names, topics: [], isbns: [] });
|
||||
|
||||
test('normalizeTitle', () => {
|
||||
assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month');
|
||||
|
||||
@@ -5,6 +5,8 @@ import type { SourceCache } from './resolver.ts';
|
||||
import { createLoc } from '../sources/loc.ts';
|
||||
import { createOpenLibrary } from '../sources/openlibrary.ts';
|
||||
import { fixtureFetch } from '../sources/fixture-fetch.ts';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
function memCache(): SourceCache & { map: Map<string, string> } {
|
||||
const map = new Map<string, string>();
|
||||
@@ -321,3 +323,116 @@ test('similar tier: a LoC failure is still an error when not tolerated and nothi
|
||||
const failLoc = ((u: string | URL | Request) => String(u).includes('loc.gov') ? Promise.reject(new Error('down')) : inner(u)) as typeof fetch;
|
||||
await assert.rejects(createResolver({ fetch: failLoc, cache: memCache(), sleep: noSleep }).resolve(WIND_RIVER), TemporaryError);
|
||||
});
|
||||
|
||||
// The two books that used to get a generated author cutter after the place-based class GV199.42.
|
||||
const SIERRA_SOUTH = '9780899978840';
|
||||
const DAY_HIKES = '9781581572025';
|
||||
const noLocTitle = (f: ReturnType<typeof fixtureFetch>): typeof fetch =>
|
||||
(async (input: string | URL | Request, init?: RequestInit) =>
|
||||
decodeURIComponent(String(input)).includes('bath.title') ? new Response('<searchRetrieveResponse></searchRetrieveResponse>') : f.fetch(input as string, init)) as typeof fetch;
|
||||
|
||||
test('Sierra South: a bare GV199.42 is a hint; another edition in that class supplies the place cutter', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: SIERRA_SOUTH });
|
||||
assert.equal(res.callNumber, 'GV199.42.S55 W564 2020'); // LoC 1990 edition (Winnett), year replaced
|
||||
assert.equal(res.source, 'loc-title');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.doesNotMatch(res.callNumber!, /^GV199\.42\.M67/);
|
||||
});
|
||||
|
||||
test('Sierra South: with no LoC title match, the Open Library work\'s 2006 edition number is used', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: noLocTitle(f), cache: memCache(), sleep: noSleep }).resolve({ isbn13: SIERRA_SOUTH });
|
||||
assert.equal(res.callNumber, 'GV199.42.S55 M663 2020');
|
||||
assert.equal(res.source, 'ol-work');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
});
|
||||
|
||||
const emptySimilar = (f: ReturnType<typeof fixtureFetch>, loc?: string): typeof fetch =>
|
||||
(async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const q = decodeURIComponent(url);
|
||||
if (url.includes('openlibrary.org/search.json?q=')) return new Response('{"docs":[]}');
|
||||
if (q.includes('bath.title=') && !q.includes('bath.title="') && loc) return new Response(readFileSync(join(import.meta.dirname, '..', 'sources', 'fixtures', loc), 'utf8'));
|
||||
if (q.includes('bath.any=') || (q.includes('bath.title=') && !q.includes('bath.title="'))) return new Response('<searchRetrieveResponse></searchRetrieveResponse>');
|
||||
return f.fetch(input as string, init);
|
||||
}) as typeof fetch;
|
||||
|
||||
test('Day hikes: the title-word search finds Pacific Crest Trail books in the hinted class, and the vote borrows their place cutter', async () => {
|
||||
const f = fixtureFetch();
|
||||
let detail = '';
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: DAY_HIKES }, { onSimilar: (d) => { detail = d; } });
|
||||
assert.equal(res.callNumber, 'GV199.42.P3 K37 2014'); // GV199.42.P3 from LoC and Open Library records, then this book's own cutter and year
|
||||
assert.equal(res.source, 'similar');
|
||||
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'));
|
||||
assert.ok(q.every((c) => /pacific/i.test(c) && /crest/i.test(c) && /trail/i.test(c)), q.join('\n'));
|
||||
});
|
||||
|
||||
test('Day hikes: a bare GV199.42 and nothing better gives the class and year, approximate, no author cutter', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: emptySimilar(f), cache: memCache(), sleep: noSleep }).resolve({ isbn13: DAY_HIKES });
|
||||
assert.equal(res.callNumber, 'GV199.42 2014');
|
||||
assert.equal(res.source, 'ol-edition');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.doesNotMatch(res.callNumber!, /K37/);
|
||||
});
|
||||
|
||||
test('with a class hint and nobody in that class found, one extra LoC title-index search is made', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: emptySimilar(f, 'loc-similar-pacific-crest-trail.xml'), cache: memCache(), sleep: noSleep }).resolve({ isbn13: DAY_HIKES });
|
||||
assert.equal(res.callNumber, 'GV199.42.P3 K37 2014');
|
||||
assert.equal(res.source, 'similar');
|
||||
});
|
||||
|
||||
test('without a class hint there is no extra title-index search', async () => {
|
||||
const f = fixtureFetch();
|
||||
await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve(WIND_RIVER);
|
||||
assert.equal(f.calls.some((c) => /bath\.title=[^"]/.test(decodeURIComponent(c))), false);
|
||||
});
|
||||
|
||||
// An LCCN counts as this edition's only when the record lists this ISBN (or the book has no ISBN).
|
||||
const UTAH_BYWAYS = '9780899974248'; // LCCN 96067014 is the 1996 edition, whose 020 is 9780963656087
|
||||
|
||||
test('an LCCN record that does not list the book\'s ISBN is another edition: approximate, this year, never exact', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: UTAH_BYWAYS, lccn: '96067014' });
|
||||
assert.equal(res.callNumber, 'F824.3.H84 2007');
|
||||
assert.equal(res.confidence, 'approximate');
|
||||
assert.equal(res.source, 'loc-title');
|
||||
});
|
||||
|
||||
test('an LCCN record that lists the book\'s ISBN (ISBN-10 or 13) is this edition: exact, by LCCN', async () => {
|
||||
const f = fixtureFetch();
|
||||
const isbnMiss = (async (input: string | URL | Request, init?: RequestInit) =>
|
||||
decodeURIComponent(String(input)).includes('bath.isbn') ? new Response('<searchRetrieveResponse></searchRetrieveResponse>') : f.fetch(input as string, init)) as typeof fetch;
|
||||
const res = await createResolver({ fetch: isbnMiss, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9780201835953', lccn: '94036653' });
|
||||
assert.equal(res.callNumber, 'QA76.758.B75 1995');
|
||||
assert.equal(res.confidence, 'exact');
|
||||
assert.equal(res.source, 'loc-lccn');
|
||||
});
|
||||
|
||||
test('with an ISBN, the ISBN record is asked first; a complete number there means the LCCN is not asked at all', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281', lccn: '2018012345' });
|
||||
assert.equal(res.source, 'loc-isbn');
|
||||
assert.equal(f.calls.some((c) => c.includes('lccn.loc.gov')), false);
|
||||
});
|
||||
|
||||
test('an LCCN from the work-level Open Library record is not reported as the book\'s', async () => {
|
||||
const f = fixtureFetch();
|
||||
const metas: (string | undefined)[] = [];
|
||||
await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: UTAH_BYWAYS }, { onMeta: (m) => metas.push(m.lccn) });
|
||||
assert.ok(metas.length > 0);
|
||||
assert.deepEqual(metas.filter(Boolean), []);
|
||||
// The work record does list one:
|
||||
assert.match(readFileSync(join(import.meta.dirname, '..', 'sources', 'fixtures', 'ol-search-9780899974248.json'), 'utf8'), /96067014/);
|
||||
});
|
||||
|
||||
test('an LCCN from the LoC ISBN record\'s own 010 is reported', async () => {
|
||||
const f = fixtureFetch();
|
||||
const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ isbn13: SIERRA_SOUTH });
|
||||
assert.equal(res.meta?.lccn, '2020947927');
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { BookMeta, Candidate, ResolveInput, Resolution, SearchResult } from '../../shared/types.ts';
|
||||
import { normalizeIsbn } from '../../shared/isbn.ts';
|
||||
import { chooseCallNumber } from './choose.ts';
|
||||
import { classKey, parseCallNumber } from '../../shared/callnumber.ts';
|
||||
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 type { OlInfo } from '../sources/openlibrary.ts';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, queryPlan, voteSimilar } from './similar.ts';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, searchWords, voteSimilar } from './similar.ts';
|
||||
import type { SimilarCandidate } from './similar.ts';
|
||||
import type { MarcFields } from '../sources/marc.ts';
|
||||
import { TemporaryError } from '../sources/http.ts';
|
||||
@@ -20,6 +22,8 @@ export interface ResolveOpts {
|
||||
tolerateLocFailure?: boolean;
|
||||
/** Called when the similar-books tier chose the number, for example "GV199.42.W8 (4 of 9 candidates)". */
|
||||
onSimilar?: (detail: string) => void;
|
||||
/** Ignore every cached source answer (and write fresh ones), so "Look up again" really asks again. */
|
||||
fresh?: boolean;
|
||||
}
|
||||
|
||||
export interface Resolver {
|
||||
@@ -47,6 +51,9 @@ function mergeMeta(parts: Partials): BookMeta | null {
|
||||
return meta;
|
||||
}
|
||||
|
||||
/** 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; };
|
||||
|
||||
const lccOf = (recs: MarcFields[]): Candidate[] => recs.flatMap((r) => r.lcc);
|
||||
|
||||
export function createResolver(deps: {
|
||||
@@ -54,16 +61,25 @@ export function createResolver(deps: {
|
||||
locIntervalMs?: number;
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}): Resolver {
|
||||
const ol = createOpenLibrary({ fetch: deps.fetch, cache: deps.cache });
|
||||
// While a fresh lookup runs, reads miss; writes still go through, so the new answers replace the old ones.
|
||||
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 sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const loc = createLoc({
|
||||
fetch: deps.fetch, cache: deps.cache,
|
||||
fetch: deps.fetch, cache,
|
||||
intervalMs: deps.locIntervalMs ?? 6000,
|
||||
sleep,
|
||||
});
|
||||
const OL_GAP_MS = 1000;
|
||||
|
||||
async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
||||
if (!opts?.fresh) return lookup(input, opts);
|
||||
bypass++;
|
||||
try { return await lookup(input, opts); } finally { bypass--; }
|
||||
}
|
||||
|
||||
async function lookup(input: ResolveInput, opts?: ResolveOpts): Promise<Resolution> {
|
||||
// In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup.
|
||||
let locError: unknown = null;
|
||||
const locCall = async (fn: () => Promise<MarcFields[]>): Promise<MarcFields[]> => {
|
||||
@@ -90,7 +106,7 @@ export function createResolver(deps: {
|
||||
if (required) throw r.e;
|
||||
return null;
|
||||
}
|
||||
return r.v;
|
||||
return r.v ? { ...r.v, meta: withoutLccn(r.v.meta) } : null;
|
||||
};
|
||||
if (isbn) {
|
||||
workP = ol.work(isbn).then((v) => ({ v }), (e: unknown) => ({ e }));
|
||||
@@ -102,14 +118,28 @@ export function createResolver(deps: {
|
||||
// Library of Congress: by LCCN when known, else by ISBN.
|
||||
const lccn = input.lccn ?? edition?.meta.lccn;
|
||||
let locRecs: MarcFields[] = [];
|
||||
let exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn';
|
||||
if (lccn) {
|
||||
locRecs = await locCall(() => loc.byLccn(lccn));
|
||||
if (locRecs.length > 0) exactSource = 'loc-lccn';
|
||||
let locCands: Candidate[] = [];
|
||||
// Numbers from an LCCN record that is not verifiably this edition: they are another edition's, like a title match.
|
||||
let lccnOtherCands: Candidate[] = [];
|
||||
let exactSource: 'loc-isbn' | 'loc-lccn' = isbn ? 'loc-isbn' : 'loc-lccn';
|
||||
const tagged = (recs: MarcFields[], source: 'loc-isbn' | 'loc-lccn'): Candidate[] =>
|
||||
lccOf(recs).map((c) => ({ ...c, source }));
|
||||
// The ISBN comes first: its record is for this edition by construction. The LCCN is the second route, asked
|
||||
// only when the ISBN gave no number, or none with evidence of being complete (a 050 with only $a).
|
||||
if (isbn) {
|
||||
locRecs = await locCall(() => loc.byIsbn(isbn));
|
||||
locCands = tagged(locRecs, 'loc-isbn');
|
||||
}
|
||||
if (isbn && lccOf(locRecs).length === 0) {
|
||||
const recs = await locCall(() => loc.byIsbn(isbn));
|
||||
if (recs.length > 0) { locRecs = recs; exactSource = 'loc-isbn'; }
|
||||
if (lccn && !locCands.some((c) => c.complete === true)) {
|
||||
const recs = await locCall(() => loc.byLccn(lccn));
|
||||
// Same edition only if the book has no ISBN (the LCCN is then its own identifier) or the record lists this ISBN.
|
||||
const mine = recs.filter((r) => !isbn || r.isbns.includes(isbn));
|
||||
const others = recs.filter((r) => !mine.includes(r));
|
||||
if (mine.length > 0) {
|
||||
if (locRecs.length === 0) locRecs = mine;
|
||||
locCands = [...locCands, ...tagged(mine, 'loc-lccn')];
|
||||
}
|
||||
lccnOtherCands = lccOf(others);
|
||||
}
|
||||
|
||||
const olEditionCands: Candidate[] = edition?.lcc ?? [];
|
||||
@@ -122,11 +152,10 @@ export function createResolver(deps: {
|
||||
});
|
||||
notify(metaOf());
|
||||
|
||||
// Tiers 1 and 2.
|
||||
let chosen = chooseCallNumber(
|
||||
{ locExact: lccOf(locRecs), olEdition: olEditionCands, locTitle: [], olWork: [] },
|
||||
forChoose(metaOf()), exactSource,
|
||||
);
|
||||
// Tiers 1 and 2: this edition's own records, used verbatim. A bare class there is only a hint.
|
||||
const own = { locExact: locCands, olEdition: olEditionCands };
|
||||
let chosen: Chosen | null = chooseCallNumber({ ...own, locTitle: [], olWork: [] }, forChoose(metaOf()), exactSource);
|
||||
const hint = chosen ? null : findHint(own, exactSource);
|
||||
|
||||
// Tier 3: LoC by title and author.
|
||||
let locTitleRecs: MarcFields[] = [];
|
||||
@@ -135,26 +164,26 @@ export function createResolver(deps: {
|
||||
const m = metaOf([work?.meta]);
|
||||
const title = m?.title ?? input.title;
|
||||
const author = m?.authors[0] ?? input.author ?? '';
|
||||
// Without an author a title search cannot be verified, so the tier is skipped.
|
||||
// Without an author a title search cannot be verified, so that search is skipped.
|
||||
if (title && author) {
|
||||
const found = await locCall(() => loc.byTitle(title, author));
|
||||
locTitleRecs = found.filter((r) => recordMatches(r, title, author));
|
||||
chosen = chooseCallNumber(
|
||||
{ locExact: [], olEdition: [], locTitle: lccOf(locTitleRecs), olWork: [] },
|
||||
forChoose(m), exactSource,
|
||||
);
|
||||
}
|
||||
chosen = chooseCallNumber(
|
||||
{ locExact: [], olEdition: [], locTitle: [...lccnOtherCands, ...lccOf(locTitleRecs)], olWork: [] },
|
||||
forChoose(m), exactSource, hint,
|
||||
);
|
||||
}
|
||||
|
||||
// Tier 4, and the work-level part of the metadata merge.
|
||||
work ??= await getWork(!chosen);
|
||||
// Without an ISBN or LCCN, the best title hit also supplies metadata.
|
||||
const hitMeta = !isbn && !input.lccn ? locTitleRecs[0]?.meta : undefined;
|
||||
const hitMeta = !isbn && !input.lccn && locTitleRecs[0] ? withoutLccn(locTitleRecs[0].meta) : undefined;
|
||||
const meta = metaOf([hitMeta, work?.meta]);
|
||||
notify(meta);
|
||||
chosen ??= chooseCallNumber(
|
||||
{ locExact: [], olEdition: [], locTitle: [], olWork: work?.lcc ?? [] },
|
||||
forChoose(meta), exactSource,
|
||||
forChoose(meta), exactSource, hint,
|
||||
);
|
||||
|
||||
// Tier 5: borrow the class from similar books. Last resort, and only for a book with a title.
|
||||
@@ -163,7 +192,7 @@ export function createResolver(deps: {
|
||||
const kw = keywordsOf(meta.title, meta.subtitle, meta.subjects);
|
||||
const groups: SimilarCandidate[][] = [];
|
||||
let found = 0;
|
||||
const plan = kw.title.length >= 2 ? queryPlan(kw.title) : queryPlan([...kw.title, ...kw.extra].slice(0, 3), 1);
|
||||
const plan = searchWords(kw);
|
||||
for (const [i, words] of plan.entries()) {
|
||||
if (i > 0) await sleep(OL_GAP_MS);
|
||||
try {
|
||||
@@ -176,7 +205,7 @@ export function createResolver(deps: {
|
||||
found = classified(groups.flat());
|
||||
if (found >= 5) break;
|
||||
}
|
||||
const locWords = kw.title.slice(0, 3);
|
||||
const locWords = (plan[0] ?? []).slice(0, 3);
|
||||
if (locWords.length > 0) {
|
||||
for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) {
|
||||
const recs = await locCall(() => loc.byKeywords(words));
|
||||
@@ -187,7 +216,18 @@ export function createResolver(deps: {
|
||||
if (classified(groups.at(-1)!) >= 5 || locError) break;
|
||||
}
|
||||
}
|
||||
const vote = voteSimilar(kw, mergeCandidates(groups));
|
||||
// With a class hint and nobody in that class found so far, one more LoC search on the title index alone.
|
||||
if (hint && !locError && locWords.length >= 2 && !groups.flat().some((c) => c.lcc.some((l) => {
|
||||
const cn = parseCallNumber(l);
|
||||
return cn !== null && cn.cutters.length > 0 && classKey(cn) === hint.cls;
|
||||
}))) {
|
||||
const recs = await locCall(() => loc.byTitleWords(locWords));
|
||||
groups.push(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),
|
||||
})));
|
||||
}
|
||||
const vote = voteSimilar(kw, mergeCandidates(groups), hint ? { hint: hint.cls } : {});
|
||||
if (vote) {
|
||||
const done = finishSimilar(vote.key, forChoose(meta));
|
||||
if (done) {
|
||||
@@ -197,6 +237,13 @@ export function createResolver(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
// A bare class and nothing better: the class and this edition's year, with no generated cutter.
|
||||
// Unless Open Library just failed and another attempt is coming: then ask again rather than settle for it.
|
||||
if (!chosen && hint) {
|
||||
if (olError && !opts?.tolerateLocFailure) throw olError;
|
||||
chosen = bareClassResult(hint, forChoose(meta).year);
|
||||
}
|
||||
|
||||
const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey
|
||||
?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, queryPlan, stem, voteSimilar } from './similar.ts';
|
||||
import { classified, finishSimilar, keywordsOf, mergeCandidates, queryPlan, searchWords, stem, voteSimilar } from './similar.ts';
|
||||
import type { SimilarCandidate } from './similar.ts';
|
||||
import { parseMarcXml } from '../sources/marc.ts';
|
||||
import { parseSimilar } from '../sources/openlibrary.ts';
|
||||
@@ -141,3 +141,62 @@ test('real responses: bread books vote for TX769', () => {
|
||||
const v = voteSimilar(keywordsOf('Artisan Flour Water Bread'), cands);
|
||||
assert.equal(v?.key, 'TX769');
|
||||
});
|
||||
|
||||
test('hinted vote: only candidates in the hinted class count, and one good match is enough', () => {
|
||||
const kw = keywordsOf('Sierra Nevada Backpacking Guide');
|
||||
const cands = [
|
||||
c('Sierra Nevada backpacking', ['GV199.42.S55 S54 2020']),
|
||||
c('Sierra backpacking trips', ['GV199.62.C57 2011']),
|
||||
c('Sierra Nevada backpacking', ['GV199.62.C57 2012']),
|
||||
c('Backpacking the Sierra', ['GV199.62.C57 2013']),
|
||||
];
|
||||
// Unhinted, the three GV199.62 books win; hinted to GV199.42, only the one book in that class is heard.
|
||||
assert.equal(voteSimilar(kw, cands)?.key, 'GV199.62');
|
||||
const v = voteSimilar(kw, cands, { hint: 'GV199.42' });
|
||||
assert.equal(v?.key, 'GV199.42.S55');
|
||||
assert.equal(v?.support, 1);
|
||||
});
|
||||
|
||||
test('hinted vote: a weak lone match, a bare-class candidate, or scattered places give nothing', () => {
|
||||
const kw = keywordsOf('Sierra Nevada Backpacking Guide');
|
||||
assert.equal(voteSimilar(kw, [c('Sierra history', ['GV199.42.S55 A1'])], { hint: 'GV199.42' }), null);
|
||||
assert.equal(voteSimilar(kw, [c('Sierra Nevada backpacking', ['GV199.42'])], { hint: 'GV199.42' }), null);
|
||||
const scattered = [
|
||||
c('Sierra Nevada backpacking', ['GV199.42.S55 A1']), c('Sierra Nevada backpacking', ['GV199.42.C2 B1']),
|
||||
c('Sierra Nevada backpacking', ['GV199.42.W3 C1']), c('Sierra Nevada backpacking', ['GV199.42.N4 D1']),
|
||||
];
|
||||
assert.equal(voteSimilar(kw, scattered, { hint: 'GV199.42' }), null);
|
||||
});
|
||||
|
||||
test('hinted vote: a winning key may equal the hint when real records have a single cutter', () => {
|
||||
const kw = keywordsOf('Trail Runners Handbook Colorado');
|
||||
const v = voteSimilar(kw, [
|
||||
c('Colorado trail runners', ['GV199.62.C57 2011']), c('Trail running Colorado', ['GV199.62.C57 2012']),
|
||||
], { hint: 'GV199.62' });
|
||||
assert.equal(v?.key, 'GV199.62');
|
||||
});
|
||||
|
||||
test('queries come from the title: capitalised mid-title words first, then longer, and subtitle words stay out', () => {
|
||||
const k = keywordsOf('Day hikes & overnights on the Pacific Crest Trail', 'Southern California : from the Mexican Border to Los Angeles County', ['Guidebooks', 'Hiking']);
|
||||
assert.deepEqual(k.own, ['pacific', 'crest', 'trail', 'overnights', 'hikes']);
|
||||
assert.deepEqual(k.sub.slice(0, 3), ['california', 'mexican', 'angeles']);
|
||||
assert.deepEqual(k.title.slice(0, 5), k.own); // scoring still sees the subtitle after the title's words
|
||||
assert.deepEqual(searchWords(k), [
|
||||
['pacific', 'crest', 'trail', 'overnights', 'hikes'], ['pacific', 'crest', 'trail', 'overnights'], ['pacific', 'crest', 'trail'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('a Title Case title carries no signal from capitals: longest words first, as before', () => {
|
||||
const k = keywordsOf('Beyond Trails in the Wind River Mountains of Wyoming');
|
||||
assert.deepEqual(k.own, ['mountains', 'wyoming', 'trails', 'river', 'wind']);
|
||||
assert.deepEqual(searchWords(k)[2], ['mountains', 'wyoming', 'trails']);
|
||||
});
|
||||
|
||||
test('a title with fewer than two usable words borrows the subtitle, then the subjects, in one query of three', () => {
|
||||
const k = keywordsOf('Dune', 'Messiah of the desert planet', ['Science fiction', 'Arrakis (Imaginary place)']);
|
||||
assert.deepEqual(k.own, ['dune']);
|
||||
assert.deepEqual(searchWords(k), [['dune', 'messiah', 'desert']]);
|
||||
const bare = keywordsOf('Dune', undefined, ['Science fiction', 'Arrakis (Imaginary place)']);
|
||||
assert.deepEqual(searchWords(bare), [['dune', 'imaginary', 'science']]);
|
||||
assert.deepEqual(searchWords(keywordsOf('The Complete Guide')), []);
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CallNumber } from '../../shared/callnumber.ts';
|
||||
import { cardLines, formatCallNumber, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts';
|
||||
import { cardLines, classKey, formatCallNumber, parseCallNumber, sortKey, withYear } from '../../shared/callnumber.ts';
|
||||
import { cutterFor, mainEntry } from '../../shared/cutter.ts';
|
||||
|
||||
// The fifth tier: when no catalogue has the book, shelve it where books on the same subject are shelved.
|
||||
@@ -9,10 +9,14 @@ import { cutterFor, mainEntry } from '../../shared/cutter.ts';
|
||||
export interface SimilarCandidate { title: string; subtitle?: string; subjects: string[]; lcc: string[] }
|
||||
|
||||
export interface Keywords {
|
||||
/** From the title and subtitle, most distinctive first. These drive the queries and the support rules. */
|
||||
/** The title's words, then the subtitle's, each most distinctive first. These drive the support rules. */
|
||||
title: string[];
|
||||
/** From the book's own subjects; they only add a little to a candidate's score. */
|
||||
extra: string[];
|
||||
/** The title's own words alone, most distinctive first (a subset of `title`). Searches are built from these. */
|
||||
own: string[];
|
||||
/** The subtitle's words not already in the title, most distinctive first. */
|
||||
sub: string[];
|
||||
}
|
||||
|
||||
export interface Vote {
|
||||
@@ -58,30 +62,58 @@ function usable(w: string): boolean {
|
||||
return w.length >= 3 && !/^\d+$/.test(w) && !STOP.has(w);
|
||||
}
|
||||
|
||||
/** Distinct words, longer (so rarer, on the whole) first; ties keep their order in the title. */
|
||||
function ranked(ws: string[]): string[] {
|
||||
/** A usable title word with what ranks it: whether it is capitalised away from the start (proper-noun-like), its length, its place. */
|
||||
interface Tok { w: string; proper: boolean; i: number }
|
||||
|
||||
function toks(s: string): Tok[] {
|
||||
const raw = s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/['’]s\b/g, '').split(/[^A-Za-z0-9]+/).filter(Boolean);
|
||||
const seen = new Set<string>();
|
||||
const out: { w: string; i: number }[] = [];
|
||||
ws.forEach((w, i) => {
|
||||
const s = stem(w);
|
||||
if (seen.has(s)) return;
|
||||
seen.add(s);
|
||||
out.push({ w, i });
|
||||
const out: Tok[] = [];
|
||||
raw.forEach((r, i) => {
|
||||
const w = r.toLowerCase();
|
||||
if (!usable(w)) return;
|
||||
const st = stem(w);
|
||||
if (seen.has(st)) return;
|
||||
seen.add(st);
|
||||
out.push({ w, proper: i > 0 && /^[A-Z]/.test(r), i });
|
||||
});
|
||||
return out.sort((a, b) => b.w.length - a.w.length || a.i - b.i).map((x) => x.w);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Words in the order a search should keep them: capitalised mid-title words first (Pacific Crest Trail), then the
|
||||
* rest; within each group the longer (so rarer, on the whole) first, then title order. When every word is
|
||||
* capitalised, as in a Title Case title, the capitals say nothing and it is simply longest first.
|
||||
*/
|
||||
function byDistinction(ts: Tok[]): string[] {
|
||||
const informative = ts.some((t) => t.proper) && ts.some((t) => !t.proper);
|
||||
return [...ts].sort((a, b) =>
|
||||
(informative ? Number(b.proper) - Number(a.proper) : 0) || b.w.length - a.w.length || a.i - b.i).map((t) => t.w);
|
||||
}
|
||||
|
||||
export function keywordsOf(title: string, subtitle?: string, subjects: string[] = []): Keywords {
|
||||
const t = ranked(words(`${title} ${subtitle ?? ''}`).filter(usable));
|
||||
const have = new Set(t.map(stem));
|
||||
const own = byDistinction(toks(title));
|
||||
const have = new Set(own.map(stem));
|
||||
const sub = byDistinction(toks(subtitle ?? '').filter((t) => !have.has(stem(t.w))));
|
||||
const all = [...own, ...sub];
|
||||
const haveAll = new Set(all.map(stem));
|
||||
const counts = new Map<string, number>();
|
||||
for (const s of subjects) {
|
||||
for (const w of new Set(words(s).filter((x) => usable(x) && !SUBJECT_NOISE.has(x)))) {
|
||||
if (!have.has(stem(w))) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
if (!haveAll.has(stem(w))) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
const extra = [...counts].sort((a, b) => b[1] - a[1] || b[0].length - a[0].length).slice(0, 4).map((x) => x[0]);
|
||||
return { title: t.slice(0, 8), extra };
|
||||
return { title: all.slice(0, 8), extra, own: own.slice(0, 8), sub };
|
||||
}
|
||||
|
||||
/**
|
||||
* The searches to run. The title's own words come first, and are enough when there are two or more; the subtitle's
|
||||
* words and then the book's subjects only fill in for a title with too few usable words (a single query of three).
|
||||
*/
|
||||
export function searchWords(kw: Keywords): string[][] {
|
||||
if (kw.own.length >= 2) return queryPlan(kw.own);
|
||||
return queryPlan([...kw.own, ...kw.sub, ...kw.extra].slice(0, 3), 1);
|
||||
}
|
||||
|
||||
/** Normalised form of the keywords; the cache key for a search. */
|
||||
@@ -126,7 +158,7 @@ export function mergeCandidates(groups: SimilarCandidate[][]): SimilarCandidate[
|
||||
// Literature classes number each author, so a neighbour's number says nothing about this book.
|
||||
const AUTHOR_CLASSES = new Set(['PQ', 'PR', 'PS', 'PT', 'PZ']);
|
||||
|
||||
interface Keys { fine: string; cutter: string; cls: string }
|
||||
interface Keys { fine: string; cutter: string; cls: string; base: string; cutters: number }
|
||||
|
||||
/** The three granularities of one call number: with its topical cutter, with that cutter cut short, and the bare class. */
|
||||
function keysOf(cn: CallNumber): Keys | null {
|
||||
@@ -134,7 +166,7 @@ function keysOf(cn: CallNumber): Keys | null {
|
||||
const fine = cardLines(cn)[0];
|
||||
const c0 = cn.cutters[0];
|
||||
const cutter = cn.cutters.length >= 2 && c0 ? `${cn.letters}${cn.number}${cn.decimal ? '.' + cn.decimal : ''}.${c0.letter}${c0.digits.slice(0, 1)}` : fine;
|
||||
return { fine, cutter, cls: cn.letters + cn.number };
|
||||
return { fine, cutter, cls: cn.letters + cn.number, base: classKey(cn), cutters: cn.cutters.length };
|
||||
}
|
||||
|
||||
/** A candidate's own keys: the ones its (possibly several) call numbers agree on most. */
|
||||
@@ -180,6 +212,14 @@ export interface VoteOpts {
|
||||
minShare?: number;
|
||||
/** The winner must beat the runner-up by this factor. */
|
||||
margin?: number;
|
||||
/**
|
||||
* A bare class from this edition's own catalogue record, for example GV199.42. Only candidates in exactly that
|
||||
* class (letters, number and decimal) and with at least one cutter are counted, and the class level (which would
|
||||
* just be the hint itself) is not tried. The hint is strong evidence, so the support needed is lower: one
|
||||
* candidate matching at least half of the title keywords is enough (two candidates otherwise; an unhinted vote
|
||||
* needs two, or one matching 60%), while the share and lead tests are unchanged.
|
||||
*/
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,11 +239,12 @@ export function voteSimilar(kw: Keywords, cands: SimilarCandidate[], opts: VoteO
|
||||
if (!keys) continue;
|
||||
const { score, matched } = scoreCandidate(kw, c);
|
||||
if (matched < minMatched) continue;
|
||||
if (opts.hint && (keys.base !== opts.hint || keys.cutters === 0)) continue;
|
||||
counted.push({ keys, score, matched });
|
||||
}
|
||||
if (counted.length === 0) return null;
|
||||
const total = counted.reduce((a, c) => a + c.score, 0);
|
||||
for (const level of ['fine', 'cutter', 'class'] as const) {
|
||||
for (const level of (opts.hint ? ['fine', 'cutter'] : ['fine', 'cutter', 'class']) as ('fine' | 'cutter' | 'class')[]) {
|
||||
const groups = new Map<string, Scored[]>();
|
||||
for (const c of counted) {
|
||||
const key = c.keys[level === 'class' ? 'cls' : level];
|
||||
@@ -215,10 +256,11 @@ export function voteSimilar(kw: Keywords, cands: SimilarCandidate[], opts: VoteO
|
||||
const win = sums[0]!;
|
||||
// Keys a few class numbers away (QL681 and QL683) are neighbours on the shelf: they do not count as rivals,
|
||||
// and their score counts towards the winner's share.
|
||||
const near = sums.slice(1).filter((x) => neighbours(win.key, x.key));
|
||||
const rival = sums.slice(1).find((x) => !neighbours(win.key, x.key));
|
||||
// (In a hinted vote every key is in one class, so neighbours would hide all rivals: the places compete.)
|
||||
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 >= 0.6);
|
||||
const strong = 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;
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface FixtureFetch {
|
||||
locOverride: string | null;
|
||||
}
|
||||
|
||||
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
export const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
function pick(u: URL, locOverride: string | null): string | null {
|
||||
if (u.hostname === 'openlibrary.org') {
|
||||
@@ -32,7 +32,14 @@ function pick(u: URL, locOverride: string | null): string | null {
|
||||
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
|
||||
}
|
||||
if (/^bath\.title=[^"]/.test(q)) {
|
||||
const name = `loc-titlewords-${slug(q.replace(/bath\.title=/g, '').replace(/ and /g, ' '))}.xml`;
|
||||
return existsSync(join(DIR, name)) ? name : 'loc-isbn-9780999999998.xml';
|
||||
}
|
||||
if (q.startsWith('bath.title=')) {
|
||||
const t = /^bath\.title="([^"]*)"/.exec(q)?.[1];
|
||||
const named = t ? `loc-title-${slug(t)}.xml` : null;
|
||||
if (named && existsSync(join(DIR, named))) return named;
|
||||
return /mythical/i.test(q) ? 'loc-title-mythical-brooks.xml' : 'loc-isbn-9780999999998.xml'; // zero records
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9780899974248</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,96 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>1</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01493cam a22003015i 4500</leader>
|
||||
<controlfield tag="001">21750637</controlfield>
|
||||
<controlfield tag="005">20250607103417.9</controlfield>
|
||||
<controlfield tag="008">201014s2020 alu 000 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">21750637</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">0</subfield>
|
||||
<subfield code="b">ibc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">epcn</subfield>
|
||||
<subfield code="f">20</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="925" ind1="0" ind2=" ">
|
||||
<subfield code="a">acquire</subfield>
|
||||
<subfield code="b">1 shelf copy</subfield>
|
||||
<subfield code="x">policy default</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="b">xd15 2020-10-14</subfield>
|
||||
<subfield code="a">xn11 2021-09-22 1 copy rec'd., to USASH</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 2020947927</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9780899978840</subfield>
|
||||
<subfield code="q">(paperback)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="z">9780899978857</subfield>
|
||||
<subfield code="q">(ebook)</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="b">eng</subfield>
|
||||
<subfield code="e">rda</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="042" ind1=" " ind2=" ">
|
||||
<subfield code="a">pcc</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Wenk, Elizabeth,</subfield>
|
||||
<subfield code="d">1974-</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Sierra South :</subfield>
|
||||
<subfield code="b">backcountry trips in California's Sierra Nevada /</subfield>
|
||||
<subfield code="c">Elizabeth Wenk, Mike White.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">9.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="263" ind1=" " ind2=" ">
|
||||
<subfield code="a">1111</subfield>
|
||||
</datafield>
|
||||
<datafield tag="264" ind1=" " ind2="1">
|
||||
<subfield code="a">Birmingham :</subfield>
|
||||
<subfield code="b">Wilderness Press,</subfield>
|
||||
<subfield code="c">2020.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">pages cm</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="520" ind1=" " ind2=" ">
|
||||
<subfield code="a">"Find the Best Hikes and Backpacking Trips in California's Sierra Nevada. The rush of trekking through nature, the thrill of experiencing new places, the reward of discovering beautiful sights-all of this awaits in the Sierra Nevada. For more than 40 years, this definitive guidebook has led readers along the top trails between Tehachapi Pass and the southern border of Yosemite National Park. Now, with the revised and updated edition, let hiking experts Elizabeth Wenk and Mike White show you the way"--</subfield>
|
||||
<subfield code="c">Provided by publisher.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">White, Mike,</subfield>
|
||||
<subfield code="d">1952-</subfield>
|
||||
<subfield code="e">author.</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9780899978840</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.isbn=9781581572025</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,138 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><record xmlns="http://www.loc.gov/MARC21/slim" xmlns:zs="http://docs.oasis-open.org/ns/search-ws/sruResponse">
|
||||
<leader>01774cam a2200457 a 4500</leader>
|
||||
<controlfield tag="001">1637833</controlfield>
|
||||
<controlfield tag="005">20250607040025.1</controlfield>
|
||||
<controlfield tag="008">960422s1996 iduab b 001 0 eng d</controlfield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="a">1637833</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="906">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">copycat</subfield>
|
||||
<subfield code="d">2</subfield>
|
||||
<subfield code="e">opcn</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">pb22 09-20-96 to hlcd; lk17 10-12-96; lk29 11-08-96; lk18 11-12-96</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">pn08 04-22-96; OCLC import pb22 09-20-96</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="955">
|
||||
<subfield code="a">LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="010">
|
||||
<subfield code="a"> 96067014 </subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">0963656082</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="020">
|
||||
<subfield code="a">9780963656087</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="9">(DLC) 96067014</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="035">
|
||||
<subfield code="a">(OCoLC)35454757</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="040">
|
||||
<subfield code="a">UM</subfield>
|
||||
<subfield code="c">UM</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="042">
|
||||
<subfield code="a">lccopycat</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="043">
|
||||
<subfield code="a">n-us-ut</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="050">
|
||||
<subfield code="a">F824.3</subfield>
|
||||
<subfield code="b">.H84 1996</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="0" ind2="0" tag="082">
|
||||
<subfield code="a">917.9204/33</subfield>
|
||||
<subfield code="2">21</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2=" " tag="100">
|
||||
<subfield code="a">Huegel, Tony.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2="0" tag="245">
|
||||
<subfield code="a">Utah byways :</subfield>
|
||||
<subfield code="b">backcountry drives for the whole family /</subfield>
|
||||
<subfield code="c">by Tony Huegel ; cover design, maps, art and production by Jerry Painter ; photography by Tony Huegel.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1="1" ind2=" " tag="246">
|
||||
<subfield code="i">At head of title on cover:</subfield>
|
||||
<subfield code="a">Backcountry drives for the whole family</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="250">
|
||||
<subfield code="a">1st ed.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="260">
|
||||
<subfield code="a">Idaho Falls, Idaho :</subfield>
|
||||
<subfield code="b">Post Co.,</subfield>
|
||||
<subfield code="c">c1996.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="300">
|
||||
<subfield code="a">174 p. :</subfield>
|
||||
<subfield code="b">ill., maps ;</subfield>
|
||||
<subfield code="c">23 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="336">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="337">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="338">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="500">
|
||||
<subfield code="a">"A Post Co. guidebook."</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="500">
|
||||
<subfield code="a">"60 roads to adventure statewide, including Canyonlands, Arches, and Capitol Reef national parks"--Cover.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="504">
|
||||
<subfield code="a">Includes bibliographical references (p. 168) and index.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2="0" tag="650">
|
||||
<subfield code="a">Automobile travel</subfield>
|
||||
<subfield code="z">Utah</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2="0" tag="650">
|
||||
<subfield code="a">All terrain vehicle driving</subfield>
|
||||
<subfield code="z">Utah</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2="0" tag="651">
|
||||
<subfield code="a">Utah</subfield>
|
||||
<subfield code="x">Tours.</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="920">
|
||||
<subfield code="a">**LC HAS REQ'D # OF SHELF COPIES**</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="922">
|
||||
<subfield code="a">co</subfield>
|
||||
</datafield>
|
||||
<datafield ind1=" " ind2=" " tag="991">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">F824.3</subfield>
|
||||
<subfield code="i">.H84 1996</subfield>
|
||||
<subfield code="p">0003357390A</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record>
|
||||
File diff suppressed because it is too large.
Load diff
+2
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>0</zs:numberOfRecords><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.title="Day hikes & overnights on the Pacific Crest Trail" and bath.author="Kast-Myers"</zs:query><zs:maximumRecords>5</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0"?>
|
||||
<zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"><zs:version>1.1</zs:version><zs:numberOfRecords>1</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema>marcxml</zs:recordSchema><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns="http://www.loc.gov/MARC21/slim">
|
||||
<leader>01502cam a2200421 a 4500</leader>
|
||||
<controlfield tag="001">1052150</controlfield>
|
||||
<controlfield tag="005">20250606162656.9</controlfield>
|
||||
<controlfield tag="008">900402s1990 cauab 001 0 eng </controlfield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="a">1052150</subfield>
|
||||
</datafield>
|
||||
<datafield tag="906" ind1=" " ind2=" ">
|
||||
<subfield code="a">7</subfield>
|
||||
<subfield code="b">cbc</subfield>
|
||||
<subfield code="c">orignew</subfield>
|
||||
<subfield code="d">1</subfield>
|
||||
<subfield code="e">ocip</subfield>
|
||||
<subfield code="f">19</subfield>
|
||||
<subfield code="g">y-gencatlg</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">CIP ver. he06 08-13-90</subfield>
|
||||
</datafield>
|
||||
<datafield tag="955" ind1=" " ind2=" ">
|
||||
<subfield code="a">LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150</subfield>
|
||||
</datafield>
|
||||
<datafield tag="010" ind1=" " ind2=" ">
|
||||
<subfield code="a"> 90012325 </subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">0899971156</subfield>
|
||||
</datafield>
|
||||
<datafield tag="020" ind1=" " ind2=" ">
|
||||
<subfield code="a">9780899971155</subfield>
|
||||
</datafield>
|
||||
<datafield tag="035" ind1=" " ind2=" ">
|
||||
<subfield code="9">(DLC) 90012325</subfield>
|
||||
</datafield>
|
||||
<datafield tag="040" ind1=" " ind2=" ">
|
||||
<subfield code="a">DLC</subfield>
|
||||
<subfield code="c">DLC</subfield>
|
||||
<subfield code="d">DLC</subfield>
|
||||
</datafield>
|
||||
<datafield tag="043" ind1=" " ind2=" ">
|
||||
<subfield code="a">n-us-ca</subfield>
|
||||
<subfield code="a">n-us-nv</subfield>
|
||||
</datafield>
|
||||
<datafield tag="050" ind1="0" ind2="0">
|
||||
<subfield code="a">GV199.42.S55</subfield>
|
||||
<subfield code="b">W564 1990</subfield>
|
||||
</datafield>
|
||||
<datafield tag="082" ind1="0" ind2="0">
|
||||
<subfield code="a">917.94/80453</subfield>
|
||||
<subfield code="2">20</subfield>
|
||||
</datafield>
|
||||
<datafield tag="100" ind1="1" ind2=" ">
|
||||
<subfield code="a">Winnett, Thomas.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="245" ind1="1" ind2="0">
|
||||
<subfield code="a">Sierra south :</subfield>
|
||||
<subfield code="b">100 back-country trips in California's Sierra /</subfield>
|
||||
<subfield code="c">Thomas Winnett, Jason Winnett, and Kathy Morey.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="250" ind1=" " ind2=" ">
|
||||
<subfield code="a">5th ed.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="260" ind1=" " ind2=" ">
|
||||
<subfield code="a">Berkeley :</subfield>
|
||||
<subfield code="b">Wilderness Press,</subfield>
|
||||
<subfield code="c">1990.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="300" ind1=" " ind2=" ">
|
||||
<subfield code="a">296 p. :</subfield>
|
||||
<subfield code="b">ill., map ;</subfield>
|
||||
<subfield code="c">20 cm.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="336" ind1=" " ind2=" ">
|
||||
<subfield code="a">text</subfield>
|
||||
<subfield code="b">txt</subfield>
|
||||
<subfield code="2">rdacontent</subfield>
|
||||
</datafield>
|
||||
<datafield tag="337" ind1=" " ind2=" ">
|
||||
<subfield code="a">unmediated</subfield>
|
||||
<subfield code="b">n</subfield>
|
||||
<subfield code="2">rdamedia</subfield>
|
||||
</datafield>
|
||||
<datafield tag="338" ind1=" " ind2=" ">
|
||||
<subfield code="a">volume</subfield>
|
||||
<subfield code="b">nc</subfield>
|
||||
<subfield code="2">rdacarrier</subfield>
|
||||
</datafield>
|
||||
<datafield tag="500" ind1=" " ind2=" ">
|
||||
<subfield code="a">Folded map in pocket.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Backpacking</subfield>
|
||||
<subfield code="z">Sierra Nevada (Calif. and Nev.)</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Hiking</subfield>
|
||||
<subfield code="z">Sierra Nevada (Calif. and Nev.)</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Backpacking</subfield>
|
||||
<subfield code="z">California</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="650" ind1=" " ind2="0">
|
||||
<subfield code="a">Hiking</subfield>
|
||||
<subfield code="z">California</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="651" ind1=" " ind2="0">
|
||||
<subfield code="a">Sierra Nevada (Calif. and Nev.)</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="651" ind1=" " ind2="0">
|
||||
<subfield code="a">California</subfield>
|
||||
<subfield code="x">Guidebooks.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">Winnett, Jason.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="700" ind1="1" ind2=" ">
|
||||
<subfield code="a">Morey, Kathy.</subfield>
|
||||
</datafield>
|
||||
<datafield tag="991" ind1=" " ind2=" ">
|
||||
<subfield code="b">c-GenColl</subfield>
|
||||
<subfield code="h">GV199.42.S55</subfield>
|
||||
<subfield code="i">W564 1990</subfield>
|
||||
<subfield code="p">00056351747</subfield>
|
||||
<subfield code="t">Copy 1</subfield>
|
||||
<subfield code="w">BOOKS</subfield>
|
||||
</datafield>
|
||||
</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.title="Sierra South" and bath.author="Morey"</zs:query><zs:maximumRecords>5</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking><zs:recordSchema>marcxml</zs:recordSchema></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>
|
||||
@@ -0,0 +1 @@
|
||||
{"ISBN:9780899974248": {"url": "http://openlibrary.org/books/OL8277272M/Utah_Byways", "key": "/books/OL8277272M", "title": "Utah Byways", "subtitle": "65 of Utah's Best Backcountry Drives", "authors": [{"url": "http://openlibrary.org/authors/OL36924A/Tony_Huegel", "name": "Tony Huegel"}], "number_of_pages": 216, "weight": "12 ounces", "identifiers": {"librarything": ["6501236"], "goodreads": ["5086610"], "isbn_10": ["0899974244"], "isbn_13": ["9780899974248"], "oclc": ["79297105"], "openlibrary": ["OL8277272M"]}, "classifications": {"lc_classifications": [""]}, "publishers": [{"name": "Wilderness Press"}], "publish_date": "January 15, 2007", "subjects": [{"name": "All terrain vehicle driving", "url": "https://openlibrary.org/subjects/all_terrain_vehicle_driving"}, {"name": "Automobile travel", "url": "https://openlibrary.org/subjects/automobile_travel"}, {"name": "Guidebooks", "url": "https://openlibrary.org/subjects/guidebooks"}, {"name": "Rural roads", "url": "https://openlibrary.org/subjects/rural_roads"}, {"name": "Tours", "url": "https://openlibrary.org/subjects/tours"}, {"name": "Automobile travel, guidebooks", "url": "https://openlibrary.org/subjects/automobile_travel,_guidebooks"}, {"name": "Utah, guidebooks", "url": "https://openlibrary.org/subjects/utah,_guidebooks"}], "subject_places": [{"name": "Utah", "url": "https://openlibrary.org/subjects/place:utah"}], "cover": {"small": "https://covers.openlibrary.org/b/id/1662210-S.jpg", "medium": "https://covers.openlibrary.org/b/id/1662210-M.jpg", "large": "https://covers.openlibrary.org/b/id/1662210-L.jpg"}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"ISBN:9780899978840": {"url": "http://openlibrary.org/books/OL29826202M/Sierra_South", "key": "/books/OL29826202M", "title": "Sierra South", "subtitle": "Backcountry Trips in California's Sierra Nevada", "authors": [{"url": "http://openlibrary.org/authors/OL24211A/Kathy_Morey", "name": "Kathy Morey"}, {"url": "http://openlibrary.org/authors/OL790724A/Mike_White", "name": "Mike White"}, {"url": "http://openlibrary.org/authors/OL2914572A/Stacy_Corless", "name": "Stacy Corless"}, {"url": "http://openlibrary.org/authors/OL2914560A/Analise_Elliot", "name": "Analise Elliot"}, {"url": "http://openlibrary.org/authors/OL2914576A/Chris_Tirrell", "name": "Chris Tirrell"}, {"url": "http://openlibrary.org/authors/OL223317A/Thomas_Winnett", "name": "Thomas Winnett"}], "number_of_pages": 344, "identifiers": {"isbn_13": ["9780899978840"], "openlibrary": ["OL29826202M"]}, "classifications": {"lc_classifications": ["", "GV199.42"]}, "publishers": [{"name": "AdventureKEEN"}], "publish_date": "2020", "subjects": [{"name": "Guidebooks", "url": "https://openlibrary.org/subjects/guidebooks"}, {"name": "Backpacking", "url": "https://openlibrary.org/subjects/backpacking"}, {"name": "Hiking", "url": "https://openlibrary.org/subjects/hiking"}, {"name": "Sierra nevada (calif. and nev.)", "url": "https://openlibrary.org/subjects/sierra_nevada_(calif._and_nev.)"}, {"name": "California, description and travel", "url": "https://openlibrary.org/subjects/california,_description_and_travel"}, {"name": "Nevada, description and travel", "url": "https://openlibrary.org/subjects/nevada,_description_and_travel"}, {"name": "Recreation", "url": "https://openlibrary.org/subjects/recreation"}], "subject_places": [{"name": "Sierra Nevada (Calif. and Nev.)", "url": "https://openlibrary.org/subjects/place:sierra_nevada_(calif._and_nev.)"}, {"name": "California", "url": "https://openlibrary.org/subjects/place:california"}]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"ISBN:9781581572025": {"url": "http://openlibrary.org/books/OL26921721M/Day_hikes_overnights_on_the_Pacific_Crest_Trail", "key": "/books/OL26921721M", "title": "Day hikes & overnights on the Pacific Crest Trail", "subtitle": "Southern California : from the Mexican Border to Los Angeles County", "authors": [{"url": "http://openlibrary.org/authors/OL7520146A/Marlise_Kast-Myers", "name": "Marlise Kast-Myers"}], "number_of_pages": 186, "pagination": "xxi 186 pages", "by_statement": "Marlise Kast-Myers", "identifiers": {"isbn_10": ["1581572026"], "isbn_13": ["9781581572025"], "oclc": ["868082130"], "openlibrary": ["OL26921721M"]}, "classifications": {"lc_classifications": ["GV199.42"], "dewey_decimal_class": ["917.9490454"]}, "publish_date": "2014", "subjects": [{"name": "Guidebooks", "url": "https://openlibrary.org/subjects/guidebooks"}, {"name": "Hiking", "url": "https://openlibrary.org/subjects/hiking"}, {"name": "Pacific crest trail", "url": "https://openlibrary.org/subjects/pacific_crest_trail"}], "subject_places": [{"name": "Southern California", "url": "https://openlibrary.org/subjects/place:southern_california"}, {"name": "Pacific Crest Trail", "url": "https://openlibrary.org/subjects/place:pacific_crest_trail"}], "ebooks": [{"preview_url": "https://archive.org/details/dayhikesovernigh0000kast", "availability": "restricted", "formats": {}}], "cover": {"small": "https://covers.openlibrary.org/b/id/13113740-S.jpg", "medium": "https://covers.openlibrary.org/b/id/13113740-M.jpg", "large": "https://covers.openlibrary.org/b/id/13113740-L.jpg"}}}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Tony Huegel"],"ddc":["917.920433"],"first_publish_year":1996,"key":"/works/OL525435W","lcc":["F--0824.30000000.H84 1996","F--0824.30000000.H84 2000"],"lccn":["96067014","00024577"],"publisher":["Wilderness Press","Post Company","Post Co."],"title":"Utah Byways","subject":["All terrain vehicle driving","Automobile travel","Guidebooks","Rural roads","Tours","Automobile travel, guidebooks","Utah, guidebooks"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Kathy Morey","Mike White","Stacy Corless","Analise Elliot","Chris Tirrell","Thomas Winnett"],"first_publish_year":2006,"key":"/works/OL19977687W","lcc":["GV-0199.42000000","GV-0199.42000000.S55 M663 2006"],"publisher":["Wilderness Press","AdventureKEEN"],"title":"Sierra South","subject":["Guidebooks","Backpacking","Hiking","Sierra nevada (calif. and nev.)","California, description and travel","Nevada, description and travel","Recreation"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":1,"start":0,"numFoundExact":true,"num_found":1,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"","offset":null,"docs":[{"author_name":["Marlise Kast-Myers"],"ddc":["917.9490454"],"first_publish_year":2014,"key":"/works/OL19708557W","lcc":["GV-0199.42000000"],"title":"Day hikes & overnights on the Pacific Crest Trail","subject":["Guidebooks","Hiking","Pacific crest trail"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":4,"start":0,"numFoundExact":true,"num_found":4,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"pacific crest trail overnights hikes","offset":null,"docs":[{"author_name":["Paul Gerald"],"first_publish_year":2007,"key":"/works/OL8635457W","title":"Day & Overnight Hikes"},{"author_name":["Marlise Kast-Myers"],"first_publish_year":2014,"key":"/works/OL19708557W","lcc":["GV-0199.42000000"],"title":"Day hikes & overnights on the Pacific Crest Trail","subject":["Guidebooks","Hiking","Pacific crest trail"]},{"author_name":["Paul Gerald"],"first_publish_year":2007,"key":"/works/OL12074539W","lcc":["GV-0199.42000000.O7 G47 2007","GV-0199.42000000.O7G47 2007"],"subtitle":"on the Pacific Crest Trail in Oregon","title":"Day & overnight hikes","subject":["Guidebooks","Hiking","Oregon, guidebooks"]},{"author_name":["Marlise Kast-Myers"],"first_publish_year":2014,"key":"/works/OL21787181W","title":"Day Hikes and Overnights on the Pacific Crest Trail - Southern California","subject":["Hiking","Pacific crest trail"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":4,"start":0,"numFoundExact":true,"num_found":4,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"pacific crest trail overnights","offset":null,"docs":[{"author_name":["Paul Gerald"],"first_publish_year":2007,"key":"/works/OL8635457W","title":"Day & Overnight Hikes"},{"author_name":["Marlise Kast-Myers"],"first_publish_year":2014,"key":"/works/OL19708557W","lcc":["GV-0199.42000000"],"title":"Day hikes & overnights on the Pacific Crest Trail","subject":["Guidebooks","Hiking","Pacific crest trail"]},{"author_name":["Paul Gerald"],"first_publish_year":2007,"key":"/works/OL12074539W","lcc":["GV-0199.42000000.O7 G47 2007","GV-0199.42000000.O7G47 2007"],"subtitle":"on the Pacific Crest Trail in Oregon","title":"Day & overnight hikes","subject":["Guidebooks","Hiking","Oregon, guidebooks"]},{"author_name":["Marlise Kast-Myers"],"first_publish_year":2014,"key":"/works/OL21787181W","title":"Day Hikes and Overnights on the Pacific Crest Trail - Southern California","subject":["Hiking","Pacific crest trail"]}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":235,"start":0,"numFoundExact":true,"num_found":235,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"pacific crest trail","offset":null,"docs":[{"author_name":["Cheryl Strayed","Isabel Ferrer","Carlos Milla","Anna Turró Armengol"],"first_publish_year":1767,"key":"/works/OL16142316W","lcc":["PS-3619.00000000.T744Z46 2012","PS-3619.00000000.T744 Z46 2012eb","F--0852.30000000","PS-3619.00000000.T744 Z46 2013c","PS-3619.00000000.T744Z46 2013c","PS-3619.00000000.T744Z46 2013b","PS-3619.00000000.T744 Z46 2013","PS-3619.00000000.T744 Z4618 2013","PS-3619.00000000.T744 Z46 2013b","F--0852.30000000.S91","PS-3619.00000000.T744 Z46 2012"],"title":"Wild","subject":["Travel","American Authors","Biography","Description and travel","Self-actualization (Psychology) in women","Hiking","Biographies as Topic","Healing power of Nature","Pacific (AK, CA, HI, NV, OR, WA)","Adventure","BIOGRAPHY & AUTOBIOGRAPHY","Literary","LITERARY CRITICISM","American","General","Personal Memoirs","nyt:hardcover-nonfiction=2012-04-08","New York Times bestseller","Authors, biography","Pacific crest trail","Biography as Topic","Autores estadounidenses","Viajes","Descripciones y viajes","Biografía","Spanish language materials","nyt:paperback-nonfiction=2013-04-14","Large type books"]},{"author_name":["Jeffrey P. Schaffer","Jeffery P. Schaffer","Andy Selters"],"first_publish_year":1900,"key":"/works/OL82189W","lcc":["GV-0199.42000000.P3 S33 1990","GV-0199.42000000.P3 S33 1986"],"title":"The Pacific Crest Trail","subject":["Guidebooks","Hiking","North America","Travel - Foreign","United States - Pacific - Oregon","Travel","Travel - United States","Canada","Travel & holiday guides","USA","Walking, hiking, trekking","Western & Pacific Coast states","Pacific Crest Trail","Pacific States"]},{"author_name":["Jeffrey P. Schaffer","Ben Schifrin","Thomas Winnett","Ruby Johnson Jenkins"],"first_publish_year":1990,"key":"/works/OL18873689W","lcc":["GV-0199.42000000.P3 P3 1990","GV-0199.42000000.P3R36 2018","GV-0199.42000000.P3 S33 1990","GV-0199.42000000.P3S85 2018"],"title":"The Pacific Crest Trail","subject":["Guidebooks","Hiking","Travel & holiday guides","Walking, hiking, trekking","Travel - United States","Pacific Crest Trail","Travel","Canada","USA","Western & Pacific Coast states","General","Pacific States","Trails","California, description and travel"]},{"author_name":["Karen Berger","Daniel R. Smith"],"first_publish_year":2000,"key":"/works/OL20976979W","lcc":["GV-0199.42000000.P3B47 2000","GV-0199.42000000.P3 B47 2000"],"title":"The Pacific Crest Trail","subject":["Guidebooks","Hiking","Pacific crest trail","Northwest, pacific, guidebooks","Pacific states, guidebooks"]},{"author_name":["Bob Holtel"],"first_publish_year":1994,"key":"/works/OL3968052W","lcc":["GV-1063.00000000.H65 1994"],"title":"Soul, Sweat & Survival on the Pacific Crest Trail","subject":["Cross-country running","Travel","Journeys","Hiking","Voyages and travels","Pacific crest trail"]},{"author_name":["William R. Gray"],"first_publish_year":1975,"key":"/works/OL6805897W","lcc":["F--0851.00000000.G8"],"title":"The Pacific Crest Trail","subject":["Description and travel","Hiking"]},{"author_name":["Michael Quine"],"first_publish_year":2023,"key":"/works/OL38368064W","title":"Pacific Crest Trail"},{"author_name":["Mark Larabee","Barney Scout Mann","Cheryl Strayed"],"first_publish_year":2016,"key":"/works/OL25736741W","lcc":["GV-0199.42000000.P3L37 2016"],"title":"Pacific Crest Trail","subject":["Pacific crest trail","Nature photography"]},{"author_name":["Thomas Winnett"],"first_publish_year":1973,"key":"/works/OL16411843W","lcc":["F--0851.00000000.P174"],"title":"The Pacific Crest Trail","subject":["Hiking"]},{"author_name":["Dan White"],"first_publish_year":2008,"key":"/works/OL8556330W","lcc":["GV-0199.42000000.P3W45 2008","GV-0199.42000000.P3 W45 2008"],"title":"The Cactus Eaters","subject":["Nature","Nonfiction","Travel","Guidebooks","Hiking","Pacific crest trail","Pacific states, guidebooks"]},{"author_name":["Simon Melrose"],"first_publish_year":2016,"key":"/works/OL24614128W","title":"Trout Fishing the Pacific Crest Trail"},{"author_name":["Dana York","James M. André"],"first_publish_year":2023,"key":"/works/OL35708644W","title":"Plants of the Pacific Crest Trail","subject":["West (u.s.), guidebooks","Hiking","Plants"]},{"author_name":["Barney Scout Mann"],"first_publish_year":2020,"key":"/works/OL24348299W","lcc":["GV-0199.42000000.P3M36 2020"],"title":"Journeys North","subject":["Recreation"]},{"author_name":["Tricia Andryszewski"],"first_publish_year":1998,"key":"/works/OL452360W","lcc":["GV-0199.42000000.P3 A53 1998","GV-0199.42000000.P3A53 1998"],"title":"Step by step along the Pacific Crest Trail","subject":["Nature study","Juvenile literature","Hiking","Hiking, juvenile literature","Nature study, juvenile literature","Pacific crest trail"]},{"author_name":["Ray Echols"],"first_publish_year":2009,"key":"/works/OL15066048W","lcc":["GV-0Line truncated
|
||||
@@ -19,6 +19,8 @@ export interface Loc {
|
||||
byTitle(title: string, author: string): Promise<MarcFields[]>;
|
||||
/** Records whose title, subjects or notes mention every keyword (the `bath.any` index). */
|
||||
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[]>;
|
||||
}
|
||||
|
||||
export function createLoc(deps: {
|
||||
@@ -101,6 +103,11 @@ export function createLoc(deps: {
|
||||
const query = surname ? `bath.title="${t}" and bath.author="${surname}"` : `bath.title="${t}"`;
|
||||
return sru(`loc-title:${title}|${author}`, query, 5);
|
||||
},
|
||||
byTitleWords(words) {
|
||||
const ws = words.map((k) => k.replace(/[^\p{L}\p{N}]/gu, '')).filter(Boolean);
|
||||
if (ws.length === 0) return Promise.resolve([]);
|
||||
return sru(`similar-loc-title:${ws.join(' ')}`, ws.map((w) => `bath.title=${w}`).join(' and '), 20);
|
||||
},
|
||||
byKeywords(keywords) {
|
||||
const words = keywords.map((k) => k.replace(/[^\p{L}\p{N}]/gu, '')).filter(Boolean);
|
||||
if (words.length === 0) return Promise.resolve([]);
|
||||
|
||||
@@ -77,3 +77,9 @@ test('the Rust fixture shows a plain author name', () => {
|
||||
const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml'));
|
||||
assert.ok(r!.meta.authors!.every((a) => !a.includes(',') && !/\d/.test(a)), String(r!.meta.authors));
|
||||
});
|
||||
|
||||
test('020 ISBNs are read as ISBN-13, ISBN-10 converted, qualifiers dropped, junk ignored', () => {
|
||||
const xml = (a: string[]) => `<record><datafield tag="020" ind1=" " ind2=" ">${a.map((x) => `<subfield code="a">${x}</subfield>`).join('')}</datafield></record>`;
|
||||
assert.deepEqual(parseMarcXml(xml(['0201835959 (pbk.)', '9780201835953', 'not an isbn']))[0]!.isbns, ['9780201835953']);
|
||||
assert.deepEqual(parseMarcXml('<record><leader>x</leader></record>')[0]!.isbns, []);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
import type { BookMeta, Candidate } from '../../shared/types.ts';
|
||||
import { trimPunct } from './http.ts';
|
||||
import { normalizeIsbn } from '../../shared/isbn.ts';
|
||||
|
||||
export interface MarcFields {
|
||||
lccn: string | null;
|
||||
@@ -11,6 +12,8 @@ export interface MarcFields {
|
||||
names: string[];
|
||||
/** Subject headings with their subdivisions and place names (650, 651), for judging what a book is about. */
|
||||
topics: string[];
|
||||
/** The ISBNs the record lists (020 $a), as ISBN-13: an ISBN-10 is converted, the "(pbk.)" qualifier dropped. */
|
||||
isbns: string[];
|
||||
}
|
||||
|
||||
type Node = Record<string, unknown>;
|
||||
@@ -127,7 +130,8 @@ export function parseMarcRecord(rec: Node): MarcFields {
|
||||
if (publisher) meta.publisher = publisher;
|
||||
if (ym) meta.year = Number(ym[1]);
|
||||
if (lccn) meta.lccn = lccn;
|
||||
return { lccn, lcc, dewey, meta, names, topics };
|
||||
const isbns = uniq(all('020').flatMap((f) => f.subs.filter((x) => x.code === 'a').map((x) => normalizeIsbn(x.value.split(/\s/)[0] ?? '')).filter((x): x is string => x !== null)));
|
||||
return { lccn, lcc, dewey, meta, names, topics, isbns };
|
||||
}
|
||||
|
||||
/** Parse every MARC record in an SRU response or a bare LCCN permalink record. */
|
||||
|
||||
@@ -28,6 +28,9 @@ export function parseCallNumber(raw: string): CallNumber | null {
|
||||
};
|
||||
}
|
||||
|
||||
/** The class part without cutters or year: GV199.42 for GV199.42.S55 S54 2020. */
|
||||
export function classKey(cn: CallNumber): string { return base(cn); }
|
||||
|
||||
function base(cn: CallNumber): string {
|
||||
return cn.letters + cn.number + (cn.decimal ? '.' + cn.decimal : '');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { encodeCardCode, parseCardCode } from './cardcode.ts';
|
||||
import type { CardCode } from './cardcode.ts';
|
||||
|
||||
const rust: CardCode = {
|
||||
callNumber: 'QA76.73.R87 K53 2018', approximate: false, title: 'The Rust Programming Language',
|
||||
authors: ['Steve Klabnik', 'Carol Nichols', 'Third Person'], isbn13: '9781718500440', year: 2018,
|
||||
};
|
||||
const bytes = (s: string) => new TextEncoder().encode(s).length;
|
||||
|
||||
test('encodes the documented layout', () => {
|
||||
assert.equal(
|
||||
encodeCardCode(rust),
|
||||
'QA76.73.R87 K53 2018\nThe Rust Programming Language\nSteve Klabnik; Carol Nichols\nISBN 9781718500440\n2018\nbooksorter 1',
|
||||
);
|
||||
});
|
||||
|
||||
test('optional lines are left out, the authors line stays; approximate adds a tilde', () => {
|
||||
assert.equal(
|
||||
encodeCardCode({ ...rust, authors: [], isbn13: null, year: null, approximate: true }),
|
||||
'QA76.73.R87 K53 2018 ~\nThe Rust Programming Language\n\nbooksorter 1',
|
||||
);
|
||||
});
|
||||
|
||||
test('round trip', () => {
|
||||
assert.deepEqual(parseCardCode(encodeCardCode(rust)), { ...rust, authors: ['Steve Klabnik', 'Carol Nichols'] });
|
||||
const bare = { ...rust, authors: [], isbn13: null, year: null, approximate: true };
|
||||
assert.deepEqual(parseCardCode(encodeCardCode(bare)), bare);
|
||||
});
|
||||
|
||||
test('long text is cut to 130 bytes, authors first to 40 bytes, with an ellipsis', () => {
|
||||
const c = { ...rust, title: 'A very long title '.repeat(12), authors: ['Alexandrina Victoria Hanover-Windsor', 'Bartholomew Montgomery Fitzgerald'] };
|
||||
const text = encodeCardCode(c);
|
||||
assert.ok(bytes(text) <= 130, String(bytes(text)));
|
||||
const lines = text.split('\n');
|
||||
assert.ok(bytes(lines[2]!) <= 40 && lines[2]!.endsWith('…'));
|
||||
assert.ok(lines[1]!.endsWith('…'));
|
||||
assert.equal(lines[0], rust.callNumber);
|
||||
assert.equal(lines.at(-1), 'booksorter 1');
|
||||
assert.ok(lines.includes('ISBN 9781718500440') && lines.includes('2018'));
|
||||
});
|
||||
|
||||
test('multi-byte characters are never split', () => {
|
||||
const c = { ...rust, title: 'é'.repeat(100), authors: ['日本語の著者'.repeat(10)] };
|
||||
const text = encodeCardCode(c);
|
||||
assert.ok(bytes(text) <= 130);
|
||||
assert.ok(!text.includes('�'));
|
||||
assert.equal(parseCardCode(text)?.callNumber, rust.callNumber);
|
||||
});
|
||||
|
||||
test('parse ignores other codes and tolerates CRLF, trailing spaces and unknown lines', () => {
|
||||
assert.equal(parseCardCode('https://example.com/book'), null);
|
||||
assert.equal(parseCardCode('QA76.73.R87 K53 2018\nTitle\nA\nsomething else'), null);
|
||||
assert.equal(parseCardCode('not a call number\nTitle\nA\nbooksorter 1'), null);
|
||||
const p = parseCardCode('QA76.73.R87 K53 2018 ~ \r\nTitle \r\nA; B\r\n2018\r\nfuture: thing\r\nISBN 9781718500440\r\nbooksorter 2 \r\n');
|
||||
assert.deepEqual(p, { callNumber: 'QA76.73.R87 K53 2018', approximate: true, title: 'Title', authors: ['A', 'B'], isbn13: '9781718500440', year: 2018 });
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { parseCallNumber } from './callnumber.ts';
|
||||
|
||||
/** What the QR code on a printed card says. See README: plain text, one fact per line. */
|
||||
export interface CardCode {
|
||||
callNumber: string; approximate: boolean; title: string; authors: string[];
|
||||
isbn13: string | null; year: number | null;
|
||||
}
|
||||
|
||||
export const MARKER_NAME = 'booksorter';
|
||||
export const MARKER = `${MARKER_NAME} 1`;
|
||||
export const MAX_BYTES = 130;
|
||||
export const MAX_AUTHOR_BYTES = 40;
|
||||
const ELLIPSIS = '…';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const byteLength = (s: string): number => encoder.encode(s).length;
|
||||
const oneLine = (s: string): string => s.replace(/\s+/g, ' ').trim();
|
||||
|
||||
/** Shorten to at most `max` UTF-8 bytes, ending in an ellipsis when something was cut. Never splits a character. */
|
||||
function fit(s: string, max: number): string {
|
||||
if (byteLength(s) <= max) return s;
|
||||
const chars = Array.from(s);
|
||||
while (chars.length > 0) {
|
||||
chars.pop();
|
||||
const t = chars.join('').trimEnd() + ELLIPSIS;
|
||||
if (byteLength(t) <= max) return t;
|
||||
}
|
||||
return max >= byteLength(ELLIPSIS) ? ELLIPSIS : '';
|
||||
}
|
||||
|
||||
export function encodeCardCode(c: CardCode): string {
|
||||
const callNumber = oneLine(c.callNumber) + (c.approximate ? ' ~' : '');
|
||||
const tail: string[] = [];
|
||||
if (c.isbn13) tail.push(`ISBN ${c.isbn13}`);
|
||||
if (c.year != null) tail.push(String(c.year));
|
||||
tail.push(MARKER);
|
||||
let authors = oneLine(c.authors.slice(0, 2).join('; '));
|
||||
let title = oneLine(c.title);
|
||||
const build = () => [callNumber, title, authors, ...tail].join('\n');
|
||||
if (byteLength(build()) > MAX_BYTES) {
|
||||
authors = fit(authors, MAX_AUTHOR_BYTES);
|
||||
title = '';
|
||||
const room = MAX_BYTES - byteLength(build());
|
||||
title = fit(oneLine(c.title), Math.max(0, room));
|
||||
}
|
||||
return build();
|
||||
}
|
||||
|
||||
/** Returns null for anything that is not a Booksorter card (other QR codes on a book, for example). */
|
||||
export function parseCardCode(text: string): CardCode | null {
|
||||
const lines = text.split(/\r?\n/).map((l) => l.trimEnd());
|
||||
while (lines.length > 0 && lines[lines.length - 1]!.trim() === '') lines.pop();
|
||||
if (lines.length < 4) return null;
|
||||
if (!/^booksorter \d+$/.test(lines[lines.length - 1]!.trim())) return null;
|
||||
let callNumber = lines[0]!.trim();
|
||||
let approximate = false;
|
||||
if (callNumber.endsWith(' ~')) { approximate = true; callNumber = callNumber.slice(0, -2).trim(); }
|
||||
if (!callNumber || !parseCallNumber(callNumber)) return null;
|
||||
const authors = lines[2]!.split(';').map((a) => a.trim()).filter(Boolean);
|
||||
let isbn13: string | null = null, year: number | null = null;
|
||||
for (const line of lines.slice(3, -1)) {
|
||||
const t = line.trim();
|
||||
const isbn = /^ISBN (\d{13})$/.exec(t);
|
||||
if (isbn) { isbn13 = isbn[1]!; continue; }
|
||||
if (/^\d{4}$/.test(t)) year = Number(t);
|
||||
}
|
||||
return { callNumber, approximate, title: lines[1]!.trim(), authors, isbn13, year };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { compareShelf } from './shelf.ts';
|
||||
|
||||
const b = (id: number, title: string, authors: string[], sortKey: string | null) => ({ id, title, authors, sortKey });
|
||||
|
||||
test('identical sort keys: first author surname, then title, then id', () => {
|
||||
const key = 'GV 0199.42 2020';
|
||||
const books = [
|
||||
b(1, 'Sierra South', ['Kathy Morey'], key),
|
||||
b(2, 'Day hikes', ['Marlise Kast-Myers'], key),
|
||||
b(3, 'Sierra North', ['Kathy Morey'], key),
|
||||
b(4, 'Unknown author', [], key),
|
||||
b(5, 'Sierra North', ['Morey, Kathy'], key),
|
||||
b(6, 'Later key', ['Aaron'], 'GV 0199.42 S55 2020'),
|
||||
b(7, 'No number', ['Aaron'], null),
|
||||
];
|
||||
assert.deepEqual([...books].sort(compareShelf).map((x) => x.id), [4, 2, 3, 5, 1, 6, 7]);
|
||||
// Input order does not matter.
|
||||
assert.deepEqual([...books].reverse().sort(compareShelf).map((x) => x.id), [4, 2, 3, 5, 1, 6, 7]);
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Book } from './types.ts';
|
||||
import { mainEntry } from './cutter.ts';
|
||||
|
||||
type Shelved = Pick<Book, 'sortKey' | 'title' | 'authors' | 'id'>;
|
||||
|
||||
/**
|
||||
* Shelf order, the one rule for the Library list, the print order and the server's book list: by sortKey (books
|
||||
* without one last), then, because bare classes make identical keys possible, first author's surname, then title,
|
||||
* then id so the order is always the same.
|
||||
*/
|
||||
export function compareShelf(a: Shelved, b: Shelved): number {
|
||||
if (a.sortKey !== b.sortKey) {
|
||||
if (a.sortKey === null) return 1;
|
||||
if (b.sortKey === null) return -1;
|
||||
return a.sortKey < b.sortKey ? -1 : 1;
|
||||
}
|
||||
const sa = a.authors.length ? mainEntry(a.authors, '') : '';
|
||||
const sb = b.authors.length ? mainEntry(b.authors, '') : '';
|
||||
return sa.localeCompare(sb, 'en', { sensitivity: 'base' })
|
||||
|| a.title.localeCompare(b.title, 'en', { sensitivity: 'base' })
|
||||
|| a.id - b.id;
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
export type Confidence = 'exact' | 'approximate' | 'manual';
|
||||
export type Status = 'pending' | 'resolved' | 'needs_attention';
|
||||
export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'similar' | 'manual';
|
||||
export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'similar' | 'manual' | 'card';
|
||||
export interface Book {
|
||||
id: number; isbn13: string | null; lccn: string | null;
|
||||
title: string; subtitle: string | null; authors: string[];
|
||||
@@ -14,7 +14,7 @@ export interface BookMeta {
|
||||
title: string; subtitle?: string; authors: string[]; publisher?: string;
|
||||
year?: number; subjects: string[]; lccn?: string;
|
||||
}
|
||||
export interface Candidate { raw: string; complete?: boolean }
|
||||
export interface Candidate { raw: string; complete?: boolean; /** Which record this came from, when it matters (the Library of Congress by LCCN or by ISBN). */ source?: Source }
|
||||
export interface SearchResult {
|
||||
title: string; authors: string[]; year?: number; publisher?: string;
|
||||
lccn?: string; lcc: string[];
|
||||
|
||||
+31
-1
@@ -2,7 +2,7 @@ import type { Book, SearchResult } from '../shared/types.ts';
|
||||
import { api } from './api.ts';
|
||||
import { setLastScan, upsertBook } from './live.ts';
|
||||
import { beepLow } from './sound.ts';
|
||||
import { showError } from './toast-store.ts';
|
||||
import { showError, showToast } from './toast-store.ts';
|
||||
|
||||
/** ISBNs with a request in flight: one ISBN is never sent twice at the same time. */
|
||||
const inflight = new Map<string, Promise<void>>();
|
||||
@@ -41,3 +41,33 @@ export async function addFromResult(r: SearchResult): Promise<boolean> {
|
||||
try { added(await api.fromSearch(r)); return true; }
|
||||
catch (e) { beepLow(); showError(`Could not add "${r.title}": ${(e as Error).message}`); return false; }
|
||||
}
|
||||
|
||||
/** Card texts with a request in flight: one card is never sent twice at the same time. */
|
||||
const cardsInflight = new Map<string, Promise<void>>();
|
||||
|
||||
/**
|
||||
* A card's QR code was read: find or add the book it describes. Nothing changes on the Scan screen except a
|
||||
* toast; for a book already in the library the toast can open it in the editor.
|
||||
*/
|
||||
export function addFromCard(text: string, open: (id: number) => void): Promise<void> {
|
||||
let p = cardsInflight.get(text);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
try {
|
||||
const r = await api.fromCard(text);
|
||||
upsertBook(r.book);
|
||||
if (r.existed) {
|
||||
showToast(`Already in your library: ${r.book.title}`, { action: { label: 'Open', run: () => open(r.book.id) } });
|
||||
} else {
|
||||
showToast(`Added from its card: ${r.book.title}`);
|
||||
}
|
||||
} catch (e) {
|
||||
beepLow();
|
||||
showError(`Could not use that card: ${(e as Error).message}`);
|
||||
}
|
||||
})();
|
||||
cardsInflight.set(text, p);
|
||||
void p.finally(() => cardsInflight.delete(text));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export interface BookPatch { title?: string; authors?: string[]; publisher?: str
|
||||
|
||||
export const api = {
|
||||
scan: (isbn: string) => request<{ book: Book; duplicate: boolean }>('POST', '/api/scan', { isbn }),
|
||||
fromCard: (text: string) => request<{ book: Book; existed: boolean }>('POST', '/api/books/from-card', { text }),
|
||||
addLccn: async (lccn: string) => toBook(await request('POST', '/api/books/lccn', { lccn })),
|
||||
search: (title: string, author: string) =>
|
||||
request<SearchResult[]>('GET', `/api/search?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`),
|
||||
|
||||
@@ -2,11 +2,12 @@ import { cardLines, parseCallNumber } from '../../shared/callnumber.ts';
|
||||
|
||||
export const APPROX_TIP = 'Number borrowed from another edition';
|
||||
export const SIMILAR_TIP = 'Number borrowed from similar books';
|
||||
export const CARD_TIP = 'Number read from its card, marked approximate there';
|
||||
|
||||
/** A call number in two monospaced lines, the way it is printed on the card. `~` marks an approximate one. */
|
||||
export function CallNo({ value, approximate, source, large }: { value: string | null; approximate?: boolean; source?: string | null; large?: boolean }) {
|
||||
const similar = source === 'similar';
|
||||
const tip = similar ? SIMILAR_TIP : APPROX_TIP;
|
||||
const tip = similar ? SIMILAR_TIP : source === 'card' ? CARD_TIP : APPROX_TIP;
|
||||
const cls = 'callno' + (large ? ' callno-large' : '');
|
||||
if (!value) return <span class={cls + ' callno-none'} aria-label="No call number yet">–</span>;
|
||||
const cn = parseCallNumber(value);
|
||||
|
||||
@@ -118,3 +118,34 @@ test('decodeLive and decodeThorough return the ISBN of a readable frame', async
|
||||
assert.equal(live.out.isbn, CODE);
|
||||
assert.equal((await decodeThorough(p, null)).isbn, CODE);
|
||||
});
|
||||
|
||||
// --- QR codes on cards ----------------------------------------------------------------------------------
|
||||
import { qrMatrix } from '../server/pdf/qr.ts';
|
||||
import { encodeCardCode } from '../shared/cardcode.ts';
|
||||
|
||||
function qrPixels(text: string, px: number): Pixels {
|
||||
const m = qrMatrix(text), q = 4, size = (m.length + 2 * q) * px, data = new Uint8ClampedArray(size * size * 4).fill(255);
|
||||
for (let r = 0; r < m.length; r++) for (let c = 0; c < m.length; c++) {
|
||||
if (!m[r]![c]) continue;
|
||||
for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {
|
||||
const i = (((r + q) * px + y) * size + (c + q) * px + x) * 4;
|
||||
data[i] = data[i + 1] = data[i + 2] = 0;
|
||||
}
|
||||
}
|
||||
return { data, width: size, height: size };
|
||||
}
|
||||
|
||||
const CARD_TEXT = encodeCardCode({ callNumber: 'QA76.73.R87 K53 2018', approximate: false, title: 'Les Misérables', authors: ['Victor Hugo'], isbn13: null, year: null });
|
||||
|
||||
test('a card QR code is read live and by the Capture burst', async () => {
|
||||
const p = qrPixels(CARD_TEXT, 4);
|
||||
assert.equal((await decodeLive(p, newLiveState())).out.card, CARD_TEXT);
|
||||
assert.equal((await decodeThorough(p, null)).card, CARD_TEXT);
|
||||
});
|
||||
|
||||
test('a QR code that is not a card is ignored without a trace', async () => {
|
||||
const p = qrPixels('https://example.com/some/book', 4);
|
||||
const live = (await decodeLive(p, newLiveState())).out;
|
||||
assert.deepEqual(live, { isbn: null, other: null, card: null });
|
||||
assert.deepEqual(await decodeThorough(p, null), { isbn: null, other: null, card: null });
|
||||
});
|
||||
+23
-11
@@ -1,10 +1,12 @@
|
||||
import { readBarcodes } from 'zxing-wasm/reader';
|
||||
import type { ReaderOptions } from 'zxing-wasm/reader';
|
||||
import { normalizeIsbn } from '../shared/isbn.ts';
|
||||
import { parseCardCode } from '../shared/cardcode.ts';
|
||||
|
||||
/** RGBA pixels, as from ImageData. Plain data so that this module runs in Node tests. */
|
||||
export interface Pixels { data: Uint8ClampedArray | Uint8Array; width: number; height: number }
|
||||
export interface DecodeOutcome { isbn: string | null; other: string | null }
|
||||
/** `card` is the text of a Booksorter card's QR code; QR codes that are not cards are dropped without a trace. */
|
||||
export interface DecodeOutcome { isbn: string | null; other: string | null; card: string | null }
|
||||
|
||||
// ---- image operations (grey, one byte per pixel) -------------------------------------------------------
|
||||
|
||||
@@ -86,6 +88,12 @@ export const BASE: ReaderOptions = {
|
||||
formats: ['EAN13', 'UPCA'], tryHarder: true, tryDownscale: true, tryRotate: false, tryInvert: false, maxNumberOfSymbols: 2,
|
||||
};
|
||||
|
||||
/**
|
||||
* QR codes are looked for only on the variants that keep 2D detail (plain and enlarged); the row-averaged ones
|
||||
* smear a QR code to nothing and stay EAN-only, so their speed and reliability are as before.
|
||||
*/
|
||||
const WITH_QR: ReaderOptions = { ...BASE, formats: ['EAN13', 'UPCA', 'QRCode'] };
|
||||
|
||||
export interface Variant { name: string; opts: ReaderOptions; prep: (g: Grey) => Grey }
|
||||
const rowSmooth = (g: Grey) => upscale(rowAverage(g, 6), 2);
|
||||
|
||||
@@ -97,18 +105,19 @@ const rowSmooth = (g: Grey) => upscale(rowAverage(g, 6), 2);
|
||||
export const VARIANTS: Variant[] = [
|
||||
{ name: 'rows+sharp2x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => sharpenAcross(rowSmooth(g), 3, 1.2) },
|
||||
{ name: 'rows2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: rowSmooth },
|
||||
{ name: 'crop', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g },
|
||||
{ name: 'up2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => upscale(g, 2) },
|
||||
{ name: 'up3x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => upscale(g, 3) },
|
||||
{ name: 'crop', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => g },
|
||||
{ name: 'up2x', opts: { ...WITH_QR, binarizer: 'GlobalHistogram' }, prep: g => upscale(g, 2) },
|
||||
{ name: 'up3x', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => upscale(g, 3) },
|
||||
];
|
||||
/** For the whole frame, which is too big to enlarge: no upscaling. */
|
||||
export const WHOLE_VARIANTS: Variant[] = [
|
||||
{ name: 'whole', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g },
|
||||
{ name: 'whole', opts: { ...WITH_QR, binarizer: 'LocalAverage' }, prep: g => g },
|
||||
{ name: 'whole-rows', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => sharpenAcross(rowAverage(g, 6), 1, 1) },
|
||||
];
|
||||
|
||||
function judge(codes: { text: string }[], into: DecodeOutcome): void {
|
||||
function judge(codes: { text: string; format?: string }[], into: DecodeOutcome): void {
|
||||
for (const c of codes) {
|
||||
if (c.format === 'QRCode') { if (parseCardCode(c.text)) into.card ??= c.text; continue; }
|
||||
const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null;
|
||||
if (isbn) into.isbn ??= isbn; else into.other ??= c.text;
|
||||
}
|
||||
@@ -118,6 +127,9 @@ async function tryVariant(g: Grey, v: Variant, extra: ReaderOptions, into: Decod
|
||||
judge(await readBarcodes(toImage(v.prep(g)) as ImageData, { ...v.opts, ...extra }), into);
|
||||
}
|
||||
|
||||
/** A book ISBN or a card was read: nothing more to try on this frame. */
|
||||
const found = (o: DecodeOutcome): boolean => o.isbn !== null || o.card !== null;
|
||||
|
||||
export interface LiveState { round: number; cursor: number }
|
||||
export const newLiveState = (): LiveState => ({ round: 0, cursor: 0 });
|
||||
/** Every FULL_EVERY-th live round looks at the whole frame instead of the crop. */
|
||||
@@ -134,14 +146,14 @@ export const wantsFull = (st: LiveState): boolean => st.round % FULL_EVERY === F
|
||||
* stopped, so that slow machines still get through every variant across frames.
|
||||
*/
|
||||
export async function decodeLive(p: Pixels, st: LiveState, now: () => number = () => performance.now()): Promise<{ out: DecodeOutcome; state: LiveState }> {
|
||||
const out: DecodeOutcome = { isbn: null, other: null };
|
||||
const out: DecodeOutcome = { isbn: null, other: null, card: null };
|
||||
const began = now(), g = toGrey(p);
|
||||
let cursor = st.cursor;
|
||||
if (wantsFull(st)) {
|
||||
for (const v of WHOLE_VARIANTS) if (!out.isbn) await tryVariant(g, v, {}, out);
|
||||
for (const v of WHOLE_VARIANTS) if (!found(out)) await tryVariant(g, v, {}, out);
|
||||
} else {
|
||||
await tryVariant(g, VARIANTS[0]!, {}, out);
|
||||
for (let i = 0; i < REST.length && !out.isbn && now() - began <= LIVE_BUDGET_MS; i++) {
|
||||
for (let i = 0; i < REST.length && !found(out) && now() - began <= LIVE_BUDGET_MS; i++) {
|
||||
await tryVariant(g, REST[cursor]!, {}, out);
|
||||
cursor = (cursor + 1) % REST.length;
|
||||
}
|
||||
@@ -151,12 +163,12 @@ export async function decodeLive(p: Pixels, st: LiveState, now: () => number = (
|
||||
|
||||
/** Everything we have on one frame, for the Capture burst: every variant, rotated too, crop then whole frame. */
|
||||
export async function decodeThorough(crop: Pixels, whole: Pixels | null): Promise<DecodeOutcome> {
|
||||
const out: DecodeOutcome = { isbn: null, other: null };
|
||||
const out: DecodeOutcome = { isbn: null, other: null, card: null };
|
||||
for (const p of whole ? [crop, whole] : [crop]) {
|
||||
const g = toGrey(p);
|
||||
for (const v of p === crop ? VARIANTS : WHOLE_VARIANTS) {
|
||||
await tryVariant(g, v, { tryRotate: true, tryInvert: true }, out);
|
||||
if (out.isbn) return out;
|
||||
if (found(out)) return out;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
|
||||
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
|
||||
|
||||
const ISBN = '9780306406157';
|
||||
|
||||
@@ -46,3 +46,13 @@ test('markEmitted silences the loop for 5 s', () => {
|
||||
assert.equal(acceptRead(s, ISBN, 2000).emit, null);
|
||||
assert.equal(acceptRead(s, ISBN, 6100).emit, ISBN);
|
||||
});
|
||||
|
||||
test('a card is announced once per 5 s per text, independently of ISBNs', () => {
|
||||
let r = acceptCard(newReadState(), 'card A', 0);
|
||||
assert.equal(r.emit, 'card A');
|
||||
r = acceptCard(r.state, 'card A', 4900);
|
||||
assert.equal(r.emit, null);
|
||||
assert.equal(acceptCard(r.state, 'card B', 4900).emit, 'card B');
|
||||
assert.equal(acceptCard(r.state, 'card A', 5100).emit, 'card A');
|
||||
assert.equal(acceptCard(markCardEmitted(newReadState(), 'card A', 0), 'card A', 100).emit, null);
|
||||
});
|
||||
@@ -35,3 +35,15 @@ export function acceptRead(
|
||||
export function markEmitted(state: ReadState, isbn: string, now: number): ReadState {
|
||||
return { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } };
|
||||
}
|
||||
|
||||
/** A card's QR code, repeat-protected like an ISBN: once per REPEAT_MS per distinct text. */
|
||||
export function acceptCard(state: ReadState, text: string, now: number): { state: ReadState; emit: string | null } {
|
||||
const key = 'card:' + text;
|
||||
const last = state.emittedAt[key];
|
||||
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null };
|
||||
return { state: { ...state, emittedAt: { ...state.emittedAt, [key]: now } }, emit: text };
|
||||
}
|
||||
|
||||
export function markCardEmitted(state: ReadState, text: string, now: number): ReadState {
|
||||
return { ...state, emittedAt: { ...state.emittedAt, ['card:' + text]: now } };
|
||||
}
|
||||
+15
-4
@@ -1,5 +1,5 @@
|
||||
import { prepareZXingModule } from 'zxing-wasm/reader';
|
||||
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
|
||||
import { acceptCard, acceptRead, markCardEmitted, markEmitted, newReadState } from './readstate.ts';
|
||||
import { cropRect } from './frame.ts';
|
||||
import { decodeLive, decodeThorough, newLiveState, sharpness, wantsFull } from './decode.ts';
|
||||
import type { DecodeOutcome, Pixels } from './decode.ts';
|
||||
@@ -62,6 +62,8 @@ function nextFrame(video: HTMLVideoElement, fallbackMs: number): Promise<void> {
|
||||
export interface ScannerHandlers {
|
||||
/** A valid ISBN-13 was read (at most once per 5 seconds per book). */
|
||||
onIsbn(isbn13: string): void;
|
||||
/** A Booksorter card's QR code was read (at most once per 5 seconds per card). */
|
||||
onCard(text: string): void;
|
||||
/** A barcode was read that is not a book ISBN. */
|
||||
onOther(code: string): void;
|
||||
/** The camera stopped by itself (unplugged, taken by another program). */
|
||||
@@ -148,6 +150,11 @@ export async function startScanner(
|
||||
const r = await decodeLive(grab(video, c.x, c.y, c.w, c.h), live);
|
||||
live = r.state;
|
||||
if (stopped || burst) { /* a burst took over: drop this result */ } else {
|
||||
if (r.out.card) {
|
||||
const a = acceptCard(state, r.out.card, Date.now());
|
||||
state = a.state;
|
||||
if (a.emit) handlers.onCard(a.emit);
|
||||
}
|
||||
for (const code of [r.out.isbn, r.out.other]) {
|
||||
if (!code) continue;
|
||||
const a = acceptRead(state, code, Date.now());
|
||||
@@ -180,13 +187,17 @@ export async function startScanner(
|
||||
if (!best || score > best.score) best = { full, score };
|
||||
const out = await decodeThorough(crop, full);
|
||||
other ??= out.other;
|
||||
if (out.card) {
|
||||
state = markCardEmitted(state, out.card, Date.now());
|
||||
return { isbn: null, other, card: out.card, saved: null };
|
||||
}
|
||||
if (out.isbn) {
|
||||
state = markEmitted(state, out.isbn, Date.now());
|
||||
return { isbn: out.isbn, other, saved: null };
|
||||
return { isbn: out.isbn, other, card: null, saved: null };
|
||||
}
|
||||
}
|
||||
if (other) return { isbn: null, other, saved: null };
|
||||
return { isbn: null, other: null, saved: best ? await saveFailed(best.full) : null };
|
||||
if (other) return { isbn: null, other, card: null, saved: null };
|
||||
return { isbn: null, other: null, card: null, saved: best ? await saveFailed(best.full) : null };
|
||||
} finally {
|
||||
burst = false;
|
||||
}
|
||||
|
||||
+2
-9
@@ -1,4 +1,5 @@
|
||||
import type { Book } from '../shared/types.ts';
|
||||
import { compareShelf } from '../shared/shelf.ts';
|
||||
|
||||
export interface BookState { byId: Record<number, Book> }
|
||||
export type BookAction =
|
||||
@@ -25,15 +26,7 @@ export function reduce(state: BookState, action: BookAction): BookState {
|
||||
}
|
||||
}
|
||||
|
||||
/** Shelf order: by sortKey, books without one last, then title. */
|
||||
export function compareShelf(a: Book, b: Book): number {
|
||||
if (a.sortKey !== b.sortKey) {
|
||||
if (a.sortKey === null) return 1;
|
||||
if (b.sortKey === null) return -1;
|
||||
return a.sortKey < b.sortKey ? -1 : 1;
|
||||
}
|
||||
return a.title.localeCompare(b.title);
|
||||
}
|
||||
export { compareShelf };
|
||||
|
||||
export function shelfOrder(state: BookState): Book[] {
|
||||
return Object.values(state.byId).sort(compareShelf);
|
||||
|
||||
@@ -37,7 +37,7 @@ const CameraIcon = () => (
|
||||
* The live camera with its controls on a bar along the bottom edge. `onIsbn` gets every ISBN it reads.
|
||||
* `captureRef.current` is set to a function that takes one careful picture (it returns false when the camera is off).
|
||||
*/
|
||||
export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void; captureRef: { current: (() => boolean) | null } }) {
|
||||
export function Camera({ onIsbn, onCard, captureRef }: { onIsbn: (isbn: string) => void; onCard: (text: string) => void; captureRef: { current: (() => boolean) | null } }) {
|
||||
const cam = useCamera();
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const scanner = useRef<Scanner | null>(null);
|
||||
@@ -65,9 +65,18 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
|
||||
say(`Read ${isbn}`, 'ok');
|
||||
onIsbn(isbn);
|
||||
};
|
||||
const handlers = useRef({ onIsbn: gotIsbn, onOther: () => {}, onEnded: () => {} });
|
||||
const gotCard = (text: string) => {
|
||||
beepAccept();
|
||||
setFlash(true);
|
||||
clearTimeout(flashTimer.current);
|
||||
flashTimer.current = setTimeout(() => setFlash(false), 600);
|
||||
say('Read a card', 'ok');
|
||||
onCard(text);
|
||||
};
|
||||
const handlers = useRef({ onIsbn: gotIsbn, onCard: gotCard, onOther: () => {}, onEnded: () => {} });
|
||||
handlers.current = {
|
||||
onIsbn: gotIsbn,
|
||||
onCard: gotCard,
|
||||
onOther: () => { beepLow(); say('That barcode is not an ISBN', 'warn'); },
|
||||
onEnded: () => {
|
||||
scanner.current = null; setState('off'); setStatus(null); updateCamera({ resolution: '' });
|
||||
@@ -91,7 +100,7 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
|
||||
setState('starting'); setProblem('');
|
||||
try {
|
||||
const sc = await startScanner(video.current, getCamera().deviceId || undefined, {
|
||||
onIsbn: i => handlers.current.onIsbn(i), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
|
||||
onIsbn: i => handlers.current.onIsbn(i), onCard: t => handlers.current.onCard(t), onOther: c => handlers.current.onOther(), onEnded: () => handlers.current.onEnded(),
|
||||
}, ac.signal);
|
||||
if (!sc) return; // turned off or left the screen while the permission prompt was open
|
||||
if (ac.signal.aborted) { sc.stop(); return; }
|
||||
@@ -121,7 +130,8 @@ export function Camera({ onIsbn, captureRef }: { onIsbn: (isbn: string) => void;
|
||||
try {
|
||||
const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true));
|
||||
if (scanner.current !== sc) return;
|
||||
if (r.isbn) gotIsbn(r.isbn);
|
||||
if (r.card) gotCard(r.card);
|
||||
else if (r.isbn) gotIsbn(r.isbn);
|
||||
else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); }
|
||||
else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); }
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef } from 'preact/hooks';
|
||||
import { addByIsbn } from '../actions.ts';
|
||||
import { addByIsbn, addFromCard } from '../actions.ts';
|
||||
import { dialogOpen } from '../dialog.ts';
|
||||
import { unlockAudio } from '../sound.ts';
|
||||
import type { EditorTarget } from '../components/Editor.tsx';
|
||||
@@ -53,7 +53,8 @@ export function Scan({ onEdit }: { onEdit: (t: EditorTarget) => void }) {
|
||||
return (
|
||||
<div class="scan">
|
||||
<div class="scan-left">
|
||||
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }} />
|
||||
<Camera captureRef={capture} onIsbn={isbn => { void addByIsbn(isbn); }}
|
||||
onCard={text => { void addFromCard(text, id => onEdit({ kind: 'edit', id })); }} />
|
||||
<LastScan onFix={fix} />
|
||||
<Entry inputRef={entry} onEdit={onEdit} />
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user