diff --git a/README.md b/README.md index 4f713a3..fa8572d 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,12 @@ The header has **Scan**, **Library (N)** and a gear for settings. 1. Open the PDF and print at **Actual size / 100%** (never "Fit to page"), **single-sided**, through the **manual feed slot**. 2. When the cards came out correctly, answer **Yes, clear them** so they are not printed twice. +Each card also carries a QR code (about 1.25 inches square, above the ISBN line). It holds the book's record as plain text: call number, title, the first two authors, ISBN and year, so a card still means something if the database is lost, and a phone camera shows it as readable text. Hold a card up to the scanner: the book is found in your library, or added from the card (already resolved, and not queued for printing again). Cards for books with no barcode can be scanned this way too. Other QR codes, such as those on a back cover, are ignored. + **Library** shows every book in shelf order, grouped by main class, with search and a *Needs attention* filter. Click a book to edit it, print another card, look it up again, or delete it. A number marked `~` was borrowed from another edition or from similar books; check those. +**How a number is found.** A number is only ever printed without `~` when it came word for word from a catalogue record (Library of Congress, then Open Library) for this exact ISBN or LCCN, and has at least one cutter. Nothing is generated for those. A record that gives only a bare class (such as `GV199.42`, which in that class needs a place cutter next, not an author) is treated as a hint: the app then looks at other editions of the same book in that class, then at similar books in that class, and borrows from them with `~`. If it finds nothing better it prints the bare class and this edition's year with `~`. Books that share a number are shelved by the first author's surname, then title. **Look up again** ignores every saved answer and asks the catalogues afresh. + **Settings** (the gear) holds the camera picker and printer alignment. If the text sits off-centre on the cards, print the calibration page on plain paper, hold it against a real sheet up to the light, and enter the X and Y offsets in millimetres (limit 10). They are saved and applied to every later PDF. ## Where the data lives diff --git a/package-lock.json b/package-lock.json index e922539..4e16d42 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,8 @@ "fast-xml-parser": "^5.12.1", "hono": "^4.13.19", "pdf-lib": "^1.17.1", - "preact": "^11.2.0" + "preact": "^11.2.0", + "qrcode-generator": "^2.0.4" }, "devDependencies": { "@types/node": "^26.6.6", @@ -1052,6 +1053,12 @@ } } }, + "node_modules/qrcode-generator": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz", + "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==", + "license": "MIT" + }, "node_modules/strnum": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz", diff --git a/package.json b/package.json index 6faa6b0..d43f469 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,8 @@ "fast-xml-parser": "^5.12.1", "hono": "^4.13.19", "pdf-lib": "^1.17.1", - "preact": "^11.2.0" + "preact": "^11.2.0", + "qrcode-generator": "^2.0.4" }, "devDependencies": { "@types/node": "^26.6.6", diff --git a/src/server/app.test.ts b/src/server/app.test.ts index 6efe054..715f55b 100644 --- a/src/server/app.test.ts +++ b/src/server/app.test.ts @@ -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 = 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); +}); diff --git a/src/server/app.ts b/src/server/app.ts index 4524c7b..66347fc 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -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!); diff --git a/src/server/db.ts b/src/server/db.ts index b42d6ab..c396c46 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -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)[]; diff --git a/src/server/jobs.ts b/src/server/jobs.ts index 7fd077f..efb3bf1 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -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 } +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; +} // 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(); const attempts = new Map(); + const fresh = new Set(); // Books waiting for a retry: they hold no worker; a timer puts them back in the queue. const waiting = new Map>(); let running: Promise | null = null; @@ -77,7 +83,7 @@ export function createJobs(deps: { async function attempt(id: number): Promise { 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); } diff --git a/src/server/pdf/card.test.ts b/src/server/pdf/card.test.ts index 50fc9df..8b305a3 100644 --- a/src/server/pdf/card.test.ts +++ b/src/server/pdf/card.test.ts @@ -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)); +}); diff --git a/src/server/pdf/card.ts b/src/server/pdf/card.ts index 206de0b..fd26a9f 100644 --- a/src/server/pdf/card.ts +++ b/src/server/pdf/card.ts @@ -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. */ diff --git a/src/server/pdf/qr.test.ts b/src/server/pdf/qr.test.ts new file mode 100644 index 0000000..766db36 --- /dev/null +++ b/src/server/pdf/qr.test.ts @@ -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); +}); diff --git a/src/server/pdf/qr.ts b/src/server/pdf/qr.ts new file mode 100644 index 0000000..d851345 --- /dev/null +++ b/src/server/pdf/qr.ts @@ -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 }; +} diff --git a/src/server/pdf/render.ts b/src/server/pdf/render.ts index 6f33147..bb1a5bd 100644 --- a/src/server/pdf/render.ts +++ b/src/server/pdf/render.ts @@ -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), diff --git a/src/server/resolve/choose.test.ts b/src/server/resolve/choose.test.ts index c064c48..34fddf8 100644 --- a/src/server/resolve/choose.test.ts +++ b/src/server/resolve/choose.test.ts @@ -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'); }); diff --git a/src/server/resolve/choose.ts b/src/server/resolve/choose.ts index 01454d3..7537120 100644 --- a/src/server/resolve/choose.ts +++ b/src/server/resolve/choose.ts @@ -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(); 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 = { 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, 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(); + 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 }; +} diff --git a/src/server/resolve/match.test.ts b/src/server/resolve/match.test.ts index e541a60..7275f0f 100644 --- a/src/server/resolve/match.test.ts +++ b/src/server/resolve/match.test.ts @@ -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'); diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts index 2c7dbba..bd4df87 100644 --- a/src/server/resolve/resolver.test.ts +++ b/src/server/resolve/resolver.test.ts @@ -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 } { const map = new Map(); @@ -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 fetch => + (async (input: string | URL | Request, init?: RequestInit) => + decodeURIComponent(String(input)).includes('bath.title') ? new Response('') : 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, 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(''); + 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('') : 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'); +}); diff --git a/src/server/resolve/resolver.ts b/src/server/resolve/resolver.ts index e717e3a..4c02c34 100644 --- a/src/server/resolve/resolver.ts +++ b/src/server/resolve/resolver.ts @@ -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): Partial => { 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; }): 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((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 { + if (!opts?.fresh) return lookup(input, opts); + bypass++; + try { return await lookup(input, opts); } finally { bypass--; } + } + + async function lookup(input: ResolveInput, opts?: ResolveOpts): Promise { // 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): Promise => { @@ -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; diff --git a/src/server/resolve/similar.test.ts b/src/server/resolve/similar.test.ts index a61c3bb..59f3f6d 100644 --- a/src/server/resolve/similar.test.ts +++ b/src/server/resolve/similar.test.ts @@ -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')), []); +}); diff --git a/src/server/resolve/similar.ts b/src/server/resolve/similar.ts index f17474d..a6b0e8c 100644 --- a/src/server/resolve/similar.ts +++ b/src/server/resolve/similar.ts @@ -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(); - 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(); 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(); 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; diff --git a/src/server/sources/fixture-fetch.ts b/src/server/sources/fixture-fetch.ts index 3ab15cc..7516a9f 100644 --- a/src/server/sources/fixture-fetch.ts +++ b/src/server/sources/fixture-fetch.ts @@ -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; diff --git a/src/server/sources/fixtures/loc-isbn-9780899974248.xml b/src/server/sources/fixtures/loc-isbn-9780899974248.xml new file mode 100644 index 0000000..aa476e8 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9780899974248.xml @@ -0,0 +1,2 @@ + +1.101.1bath.isbn=97808999742481xmlmarcxml diff --git a/src/server/sources/fixtures/loc-isbn-9780899978840.xml b/src/server/sources/fixtures/loc-isbn-9780899978840.xml new file mode 100644 index 0000000..6872152 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9780899978840.xml @@ -0,0 +1,96 @@ + +1.11marcxmlxml + 01493cam a22003015i 4500 + 21750637 + 20250607103417.9 + 201014s2020 alu 000 0 eng + + 21750637 + + + 0 + ibc + orignew + 2 + epcn + 20 + y-gencatlg + + + acquire + 1 shelf copy + policy default + + + xd15 2020-10-14 + xn11 2021-09-22 1 copy rec'd., to USASH + + + 2020947927 + + + 9780899978840 + (paperback) + + + 9780899978857 + (ebook) + + + DLC + eng + rda + DLC + + + pcc + + + Wenk, Elizabeth, + 1974- + author. + + + Sierra South : + backcountry trips in California's Sierra Nevada / + Elizabeth Wenk, Mike White. + + + 9. + + + 1111 + + + Birmingham : + Wilderness Press, + 2020. + + + pages cm + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + "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"-- + Provided by publisher. + + + White, Mike, + 1952- + author. + +11.1bath.isbn=97808999788401xmlmarcxml diff --git a/src/server/sources/fixtures/loc-isbn-9781581572025.xml b/src/server/sources/fixtures/loc-isbn-9781581572025.xml new file mode 100644 index 0000000..7d0f9b2 --- /dev/null +++ b/src/server/sources/fixtures/loc-isbn-9781581572025.xml @@ -0,0 +1,2 @@ + +1.101.1bath.isbn=97815815720251xmlmarcxml diff --git a/src/server/sources/fixtures/loc-lccn-96067014.xml b/src/server/sources/fixtures/loc-lccn-96067014.xml new file mode 100644 index 0000000..808fcec --- /dev/null +++ b/src/server/sources/fixtures/loc-lccn-96067014.xml @@ -0,0 +1,138 @@ + + 01774cam a2200457 a 4500 + 1637833 + 20250607040025.1 + 960422s1996 iduab b 001 0 eng d + + 1637833 + + + 7 + cbc + copycat + 2 + opcn + 19 + y-gencatlg + + + pb22 09-20-96 to hlcd; lk17 10-12-96; lk29 11-08-96; lk18 11-12-96 + + + pn08 04-22-96; OCLC import pb22 09-20-96 + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 96067014 + + + 0963656082 + + + 9780963656087 + + + (DLC) 96067014 + + + (OCoLC)35454757 + + + UM + UM + DLC + + + lccopycat + + + n-us-ut + + + F824.3 + .H84 1996 + + + 917.9204/33 + 21 + + + Huegel, Tony. + + + Utah byways : + backcountry drives for the whole family / + by Tony Huegel ; cover design, maps, art and production by Jerry Painter ; photography by Tony Huegel. + + + At head of title on cover: + Backcountry drives for the whole family + + + 1st ed. + + + Idaho Falls, Idaho : + Post Co., + c1996. + + + 174 p. : + ill., maps ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + "A Post Co. guidebook." + + + "60 roads to adventure statewide, including Canyonlands, Arches, and Capitol Reef national parks"--Cover. + + + Includes bibliographical references (p. 168) and index. + + + Automobile travel + Utah + Guidebooks. + + + All terrain vehicle driving + Utah + Guidebooks. + + + Utah + Tours. + + + **LC HAS REQ'D # OF SHELF COPIES** + + + co + + + c-GenColl + F824.3 + .H84 1996 + 0003357390A + Copy 1 + BOOKS + + diff --git a/src/server/sources/fixtures/loc-similar-pacific-crest-trail.xml b/src/server/sources/fixtures/loc-similar-pacific-crest-trail.xml new file mode 100644 index 0000000..e5d3505 --- /dev/null +++ b/src/server/sources/fixtures/loc-similar-pacific-crest-trail.xml @@ -0,0 +1,2559 @@ + +1.1135marcxmlxml + 01205cam a2200349 4500 + 4553449 + 20250607170602.0 + 730625m19731974caua b 001 0 eng + + 4553449 + + + 7 + cbc + orignew + 2 + opcn + 19 + y-gencatlg + + + LCAP batch update 2025-06-02-04:00: LCAPM-824, LCAPM-644, LCAPM-150 + + + 72096122 + + + 0911824278 + v. 1 + + + 9780911824278 + (v. 1) + + + (DLC) 72096122 + + + DLC + DLC + DLC + + + n-us-ca + n-us-wa + n-us-or + + + F851 + .P174 + + + 917.9/04/3 + + + The Pacific Crest Trail. + + + [Berkeley, Calif. + Wilderness Press, + 1973-74] + + + 2 v. + illus. + 20 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Wilderness Press trail guide series + + + Bibliography: v. 1, p. 27; v. 2, p. 23. + + + v. 1. Winnett, T. California.--v. 2. Schaffer, J. and Hartline, B. & F. Oregon & Washington. + + + Hiking + Pacific States. + + + Pacific Crest Trail. + + + Winnett, Thomas. + + + c-GenColl + F851 + .P174 + 00050795913 + Copy 1 + BOOKS + +1marcxmlxml + 01431cam a2200397 i 4500 + 1288276 + 20250606193950.3 + 771108m19761977cauab b 001 0 eng + + 1288276 + + + 7 + cbc + orignew + 2 + ocip + 19 + y-gencatlg + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 76001354 + + + 0911824588 (v. 1) : + $9.95. + 0911824499 (v. 2) : + $6.95 + + + 9780911824582 + + + 9780911824490 + + + (DLC) 76001354 + + + DLC + DLC + DLC + + + n-us-ca + n-us-or + n-us-wa + + + GV199.42.P3 + P3 1976 + + + 917.9/04/3 + + + The Pacific Crest Trail. + + + 2d ed. + + + Berkeley, CA : + Wilderness Press, + 1976-1977. + + + 2 v. : + ill., maps ; + 20-23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Wilderness Press trail guide series + + + Includes indexes. + + + Bibliography: v. 1, p. [405]-406; v. 2, p. 23. + + + v. 1. Schaffer, J. P. and others. California.--v. 2. Schaffer, J., Harline, B., and Hartline, F. Oregon & Washington. + + + Hiking + Pacific States + Guidebooks. + + + Pacific Crest Trail + Guidebooks. + + + Pacific States + Guidebooks. + + + Schaffer, Jeffrey P. + + + c-GenColl + GV199.42.P3 + P3 1976 + Copy 1 + BOOKS + +2marcxmlxml + 01450cam a2200409 i 4500 + 1322068 + 20250606201337.8 + 800110m19791982caua b 001 0 eng + + 1322068 + + + 7 + cbc + orignew + 2 + opcn + 19 + y-gencatlg + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 78068844 + + + 089997015X + v. 1 + + + 0911824820 (v. 2) : + $9.95 + + + 9780911824827 + + + (DLC) 78068844 + + + DLC + DLC + DLC + + + n-us-wa + n-us-or + n-us-ca + + + GV199.42.P3 + P3 1979 + + + 917.9/04/3 + + + The Pacific Crest Trail. + + + 3d ed. + + + Berkeley, CA : + Wilderness Press, + 1979-1982. + + + 2 v. : + ill. ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Wilderness Press trail guide series + + + Includes indexes. + + + Bibliography: v. 1, p. [463]-464; v. 2, p. [315]-316. + + + v. 1. Schaffer, J.P. and others. California.--v. 2. Schaffer, J.P., Hartline, B. and F. Oregon & Washington. + + + Hiking + Pacific States + Guidebooks. + + + Pacific Crest Trail + Guidebooks. + + + Pacific states + Guidebooks. + + + Schaffer, Jeffrey P. + + + V. 1 added. Entry closed: BA08 2/28/83. + + + c-GenColl + GV199.42.P3 + P3 1979 + Copy 1 + BOOKS + +3marcxmlxml + 01670cam a2200421 a 4500 + 1142319 + 20250606172702.4 + 950505m19901995cauab b 001 0 eng + + 1142319 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + pc03 to sa00 05-05-95; sj06 05-05-95; sj12 05-05-95; sj05 05-08-95; CIP ver. pv07 08-30-95; v. 2 added sj07 07-20-00 + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-893, LCAPM-150 + + + 95009325 + 89070744 + + + 0899971784 + v. 1 + + + 089997113X + v. 2 + + + 9780899971780 + (v. 1) + + + (DLC) 95009325 + + + DLC + DLC + DLC + + + n-us-ca + n-us-or + n-us-wa + + + GV199.42.P3 + P3 1990 + + + 917.904/33 + 21 + + + The Pacific Crest Trail. + + + 5th ed. + + + Berkeley : + Wilderness Press, + c1990-c1995. + + + 2 v. : + ill., col. maps ; + 24 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes bibliographical references and indexes. + + + v. 1. California / Jeffrey P. Schaffer ... [et al.] -- v. 2. Oregon & Washington / Jeffrey P. Schaffer, Andy Selters. + + + Hiking + Pacific Crest Trail + Guidebooks. + + + Hiking + Pacific States + Guidebooks. + + + Pacific Crest Trail + Guidebooks. + + + Pacific States + Guidebooks. + + + Guidebooks. + lcgft + https://id.loc.gov/authorities/genreForms/gf2014026108 + + + Schaffer, Jeffrey P. + + + Vol. 2 published first. + + + c-GenColl + GV199.42.P3 + P3 1995 + Copy 1 + BOOKS + +4marcxmlxml + 01458cam a2200385 a 4500 + 1511176 + 20250607022740.9 + 891213m19009999cauab b 001 0 eng + + 1511176 + + + 7 + cbc + orignew + 1 + opcn + 19 + y-gencatlg + + + CIP ver. he07 05-24-90; to be cancelled--covered by LCCN 95-9325 sj07 07-20-00 + + + LCAP batch update 2025-06-01-04:00: LCAPM-644 + + + 89070744 + + + 089997113X + v. 2 + + + (DLC) 89070744 + + + DLC + DLC + DLC + + + n-us-ca + n-us-wa + n-us-or + + + GV199.42.P3 + S33 1990 + + + 917.97/043 + 20 + + + Schaffer, Jeffrey P. + + + The Pacific Crest Trail / + Jeffrey P. Schaffer, Andy Selters ; maps drawn by Jeffrey P. Schaffer and Kenneth R. Ng. + + + 5th ed. + + + Berkeley, CA : + Wilderness Press, + <1990- > + + + v. <2 > : + ill., col. maps ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes bibliographical references (v. 2, p. [315]-316) and index. + + + -- v. 2. Oregon & Washington. + + + Hiking + Pacific States + Guidebooks. + + + Hiking + Pacific Crest Trail + Guidebooks. + + + Pacific States + Guidebooks. + + + Pacific Crest Trail + Guidebooks. + + + Selters, Andrew. + + + c-GenColl + GV199.42.P3 + S33 1990 + Copy 1 + BOOKS + +5marcxmlxml + 01575cam a2200409 a 4500 + 3806881 + 20250607155342.3 + 860325m19009999cauab b 001 0 eng + + 3806881 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150 + + + 85041030 + + + 0899970605 (pbk. : v. 2) : + $17.95 + + + 9780899970608 + + + (DLC) 85041030 + + + DLC + DLC + DLC + + + n-us-ca + n-us-wa + n-us-or + + + GV199.42.P3 + S33 1986 + + + 917.9/043 + 19 + + + The Pacific Crest Trail / + Jeffrey P. Schaffer, Andy Selters ; maps drawn by Jeffrey P. Schaffer and Kenneth R. Ng. + + + 4th ed. + + + Berkeley, CA : + Wilderness Press, + <1986- > + + + v. <2, > : + ill., maps ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes index. + + + Bibliography: p. v. 2, p. [315]-316. + + + -- v. 2. Oregon & Washington. + + + Hiking + Pacific States + Guidebooks. + + + Hiking + Pacific Crest Trail + Guidebooks. + + + Pacific States + Guidebooks. + + + Pacific Crest Trail + Guidebooks. + + + Schaffer, Jeffrey P. + + + Selters, Andrew. + + + M.e. should be under title--Phone call to pubr.: v. 1, California, by Jeffrey P. Schaffer and others, was published in 1989. + + + c-GenColl + GV199.42.P3 + S33 1986 + 00009396287 + Copy 1 + 2 + BOOKS + +6marcxmlxml + 01258cam a2200373 i 4500 + 787817 + 20250608020211.3 + 750110s1975 dcua 000 0aeng + + 787817 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-150 + + + 74001565 + + + 0870441493 + + + 9780870441493 + + + (DLC) 74001565 + + + DLC + DLC + DLC + + + n-us-wa + n-us-or + n-us-ca + + + F851 + .G8 + + + 917.9/04/3 + + + Gray, William R., + 1946- + + + The Pacific Crest Trail / + by William R. Gray. + + + Washington : + National Geographic Society, + [1975] + + + 199 p., : + ill. (some col.); + 26 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Includes index. + + + Bibliography: p. 198. + + + Gray, William R., + 1946- + + + Hiking + Pacific States. + + + Pacific Crest Trail. + + + Pacific States + Description and travel. + + + National Geographic Society (U.S.). + Special Publications Division. + + + c-GenColl + F851 + .G8 + 00018743590 + Copy 1 + BOOKS + +7marcxmlxml + 01672cem a2200373 i 4500 + 5813344 + 20250607225008.1 + aj canzn + 810921s1964 oru a f 0 eng + + 5813344 + + + 7 + cbc + premver + u + ncip + 19 + y-geogmaps + + + ga09 2017-06-23 sent to CMT + + + map65000051 + + + a + 200000 + + + (DLC)map65000051 + + + DLC + eng + CarP + DLC + rda + + + G4232.P3 1964 + .U5 + + + 4232 + P3 + + + 4281 + + + United States. + Forest Service. + Pacific Northwest Region. + + + Cascade Crest Trail, Washington : + Pacific Crest Trail system / + Forest Service, U.S. Department of Agriculture, Pacific Northwest Region. + + + Pacific Crest Trail system + + + Scale approximately 1:200,000. + + + [Portland, Oregon] : + Forest Service, Pacific Northwest Region, + 1964. + + + 1 map : + color ; + 193 x 17 cm, on sheet 57 x 89 cm, folded to 23 x 15 cm + + + cartographic image + cri + rdacontent + + + unmediated + n + rdamedia + + + sheet + nb + rdacarrier + + + Relief shown by hachures and spot heights. + + + Pacific Crest Trail, a trail running from Mexico to Canada along the crest of the mountains in California, Oregon, and Washington. The original proposal was to link the John Muir Trail, the Tahoe-Yosemite Trail (both in California), the Skyline Trail (in Oregon) and the Cascade Crest Trail (in Washington). + + + Trails + Washington (State) + Maps. + + + Pacific Crest Trail + Maps. + + + Maps. + lcgft + + + c-G&M + G4281 + .P25 1964.U5 + Copy 1 + PREM + +8marcxmlxml + 01409cem a2200361 i 4500 + 18528190 + 20250607063439.1 + aj|canzn + 150317t20142014dcubg a 0 eng + + 18528190 + + + 7 + cbc + orignew + u + ncip + 20 + y-geogmaps + + + ga45 2015-03-17 sent to CMT + + + 2015588471 + + + a + 1700000 + W1240000 + W1160000 + N0480000 + N0340000 + + + DLC + eng + rda + DLC + + + G4232.P3 2014 + .N3 + + + 4232 + P3 + + + National Geographic Maps (Firm) + + + Pacific Crest Trail National Scenic Trail / + National Geographic. + + + Scale 1:1,700,000. 1 in. = 26.8 miles, 1 cm = 17.0 km. + Albers conic equal-area projection. + (W 124°--W 116°/N 48°--N 34°). + + + Washington, D.C. : + National Geographic Society, + [2014] + + + © 2014 + + + 1 map : + color ; + 117 x 41 cm + + + cartographic image + cri + rdacontent + + + unmediated + n + rdamedia + + + sheet + nb + rdacarrier + + + Relief shown by shading and spot heights. + + + Covers California and western parts of Washsington, Oregon and Nevada. + + + Includes distance table and a diagram showing elevations in feet to recreation areas. + + + "20757." + + + Pacific Crest Trail + Maps. + + + Maps. + lcgft + + + National Geographic Society (U.S.) + +9marcxmlxml + 01305cam a2200373 a 4500 + 1528290 + 20250607024016.9 + 900808s1990 cauab 000 0 eng + + 1528290 + + + 7 + cbc + orignew + 2 + opcn + 19 + y-gencatlg + + + pn06 08-08-90; he03 05-09-91; he02 05-15-91; he08 11-09-91; he04 01-22-92 + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 90084004 + + + 0931255066 + + + 9780931255069 + + + (DLC) 90084004 + + + DLC + DLC + DLC + + + n-us-ca + n-us-or + n-us-wa + + + GV1045.5.P33 + P38 1990 + + + 796.6/4/0979 + 20 + + + Paul, Bil, + 1943- + + + The Pacific Crest Bicycle Trail / + Bil Paul. + + + 1st ed. + + + Livermore, Calif. : + Bittersweet Pub. Co., + c1990. + + + 200 p. : + ill., maps ; + 23 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Bicycle touring + Pacific Crest Bicycle Trail + Guidebooks. + + + Bicycle touring + Pacific States + Guidebooks. + + + Pacific Crest Bicycle Trail + Guidebooks. + + + Pacific States + Guidebooks. + + + ad + + + c-GenColl + GV1045.5.P33 + P38 1990 + Copy 1 + BOOKS + +10marcxmlxml + 02820cas a2200625 i 4500 + 22964781 + 20260831104949.1 + 200313c20209999cau x 0 a0eng + + 2023204203 + + + 2837-6048 + 1 + + + (OCoLC)1144495331 + + + Avalon Travel, Hachette Book Group, 1700 Fourth St., Berkeley, CA 94710 + + + UAP + eng + rda + UAP + UAP + JQW + WLM + OCLCO + OCLCQ + DLC + OCLCL + OCLCQ + + + pcc + nsdp + + + n-us-ca + n-us-or + n-us-wa + + + GV199.42.P3 + D75 + + + 917.9 + 23/eng/20230505 + https://id.oclc.org/worldcat/ddc/E3ycPfF9mpCDQjgWMCRr9YW4Hc + + + 796.510979 + 23 + https://id.oclc.org/worldcat/ddc/E33YgJ9vpt9cy9rQjY9xKb3q9m + + + Drive & hike Pacific Crest Trail + + + Drive & hike Pacific Crest Trail. + + + Moon Drive and hike Pacific Crest Trail + + + Moon Drive & hike Pacific Crest Trail + + + Drive and hike Pacific Crest Trail + + + Berkeley : + Avalon Travel, Hachette Book Group, + 2020- + + + volumes : + color illustrations, color maps ; + 20 cm + + + Irregular + + + text + txt + rdacontent + + + still image + sti + rdacontent + + + cartographic image + cri + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + illustration + http://rdaregistry.info/termList/IllusContent/1014 + rdaill + + + polychrome + http://rdaregistry.info/termList/RDAColourContent/1003 + rdacc + + + map + http://rdaregistry.info/termList/IllusContent/1008 + rdaill + + + Began with 1st edition (March 2020). + + + "The best trail towns, day hikes, and road trips in between"--Cover + + + 1st edition (March 2020); title from title page. + + + 1st edition (March 2020). + + + Hiking + Pacific Crest Trail + Guidebooks. + + + Automobile travel + Pacific Crest Trail + Guidebooks. + + + Automobile travel. + fast + (OCoLC)fst00823217 + + + Hiking. + fast + (OCoLC)fst00956758 + + + Pacific Crest Trail + Guidebooks. + + + Pacific Crest Trail + Guides. + + + United States + Pacific Crest Trail. + fast + (OCoLC)fst01243524 + + + Guidebook + + + travel guidebooks. + aat + + + Guidebooks. + fast + (OCoLC)fst01423871 + + + Guidebooks. + lcgft + + + Guides touristiques. + rvmgf + + + Avalon Travel (Firm), + publisher. + + + DLC + + + 7 + cbc + serasst + 2 + ncip + 20 + n-oclcserc + + + Acquire + 1 shelf copy + policy default, 2023-02-23 + + + rh08 2023-02-08 to Selection Officer + rjc, 2023-02-23 to USASH/SER + rh08 2023-05-03 to USASH/SER-AHS ISSN assignment shelf + rh25 2023-05-05 to endstage + rh08 2023-05-31 to BCCD + +11marcxmlxml + 01408cem a2200361 a 4500 + 12876452 + 20250606193908.9 + aj canzn + 020730s1981 oru a f 0 eng + + 12876452 + + + 7 + cbc + origcop + u + ncip + 20 + n-geogmaps + + + ga09 2002-07-30 sent to CMT + + + LCAP batch update 2025-06-01-04:00: LCAPM-893 + + + 2002627500 + + + a + 720000 + + + DLC + DLC + + + G4232.P3 1981 + .U5 + + + 4232 + P3 + + + 4361 + + + United States. + Forest Service. + Pacific Northwest Region. + + + Pacific Crest National Scenic Trail / + U.S.D.A. Forest Service, Pacific Northwest Region. + + + Scale ca. 1:720,000. + + + [Portland, Or.?] : + The Region, + 1981. + + + 2 maps on 1 sheet : + both sides, col. ; + 71 x 87 cm. and 70 x 98 cm., sheet 77 x 102 cm., folded to 19 x 26 cm. + + + "March 1981." + + + Shows locations of management and forest offices. + + + "Base map produced by Engineering, Geometronics, Automated Cartography." + + + "P.C.N.S.T. comprehensive plan." + + + Includes 2 location insets. + + + Northern California -- Southern California. + + + Trails + California + Maps. + + + Pacific Crest Trail + Maps. + + + Maps. + lcgft + https://id.loc.gov/authorities/genreForms/gf2011026387 + +12marcxmlxml + 01048cac a22003133a 4500 + 17010257 + 20250607044538.4 + 111012||||| dcu| g | f00| 0|eng + + 17010257 + + + 0 + ibc + orignew + u + ncip + 20 + y-gencatlg + + + acquire + 1 shelf copy + policy default + + + LCAP batch update 2025-06-02-04:00: LCAPM-644 + + + (DLC-SGP)7072 + + + DLC-SGP 7072 + + + DLC-SGP + DLC-SGP + + + FAC 101044 + + + United States. + Forest Service. + + + Pacific Crest National Scenic Trail Advisory Council. + + + Pacific Crest National Scenic Trail Advisory Committee + + + [197-?]- + + + v. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Federal Advisory Committee depository collection. + + + Committee name may vary. + + + United States. Dept. of Agriculture. Forest Service. + + + https://hdl.loc.gov/loc.sgp/gsa.faca + + + SerFac + +13marcxmlxml + 01332cam a22003611 4500 + 8805770 + 20250608032844.2 + 770803s1945 xx 000 0 eng + + 8805770 + + + 7 + cbc + oclcrpl + u + ncip + 19 + y-gencatlg + + + LCAP batch update 2025-06-02-04:00: LCAPM-644 + + + 45006946 + + + (DLC) 45006946 + + + (OCoLC)3159482 + + + DLC + OC + DLC + + + premarc + + + F851 + .C622 + + + 917.9 + + + Clarke, Clinton C. + + + The Pacific crest trailway, + compiled by Clinton C. Clarke. + + + Pasadena, Calif., + The Pacific crest trail system conference, + 1945. + + + 4 p. l., 11-126 p. + 12 pl., 8 fold. maps. + 24 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Plates and maps in pockets. + + + Contains the data published in Bulletins no. 12-15, 19-22 of the Pacific crest trail system conference. + + + Natural history + Sierra Nevada (Calif. and Nev.) + + + Natural history + Cascade Range. + + + Pacific States + Description and travel. + + + Pacific Crest Trail System Conference. + + + OCLC REPLACEMENT cdsdistr + + + c-GenColl + F851 + .C622 + Copy 1 + OCLCREP + +14marcxmlxml + 00974cam a22003131 4500 + 10174264 + 20250606155341.4 + 881005s1935 cau 000 0 eng + + 10174264 + + + 7 + cbc + oclcrpl + u + ncip + 19 + y-gencatlg + + + LCAP batch update 2025-06-01-04:00: LCAPM-644 + + + 36018592 + + + (DLC) 36018592 + + + (OCoLC)18571366 + + + DLC + CSfSC + CSfSC + DLC + + + F851 + .C62 + + + 917.9 + + + Clarke, Clinton C. + + + The Pacific crest trail, Canada to Mexico. + + + Pasadena, Calif., + C.C. Clarke + [1935] + + + [48] p. + 18 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Cover-title. + + + "Foreword" signed: Clinton C. Clarke. + + + Pacific Coast (U.S.) + Guidebooks. + + + OCLC REPLACEMENT + + + c-GenColl + F851 + .C62 + Copy 1 + OCLCREP + +15marcxmlxml + 02049cam a2200469 a 4500 + 4032370 + 20250607161538.8 + 980122s1998 coua 000 0ceng + + 4032370 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + pc17 to ja00 01-23-98; sj11 01-26-98; sj10 01-26-98; sj05 01-27-98; CIP ver sj06 09-22-98 + + + LCAP batch update 2025-06-02-04:00: LCAPM-644, LCAPM-893, LCAPM-150 + + + 98009590 + + + 1565792777 + + + 9781565792777 + + + (DLC) 98009590 + + + DLC + DLC + DLC + + + n-us-ca + n-us-or + n-us-wa + + + GV199.42.P3 + S65 1998 fol. + + + 917.9 + 21 + + + Smith, Bart, + 1959- + + + Along the Pacific Crest Trail / + photography by Bart Smith ; text by Karen Berger and Daniel R. Smith ; foreword by Bob Ballou. + + + Englewood, Colo. : + Westcliffe Publishers, + c1998. + + + 144 p. : + col. ill. ; + 26 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Smith, Bart, + 1959- + Travel + Pacific Crest Trail. + + + Smith, Bart, + 1959- + Travel + Pacific Crest Trail + Pictorial works. + + + Berger, Karen, + 1959- + Travel + Pacific Crest Trail. + + + Berger, Karen, + 1959- + Travel + Pacific Crest Trail + Pictorial works. + + + Hiking + Pacific Crest Trail. + + + Hiking + Pacific Crest Trail + Pictorial works. + + + Natural history + Pacific Crest Trail. + + + Natural history + Pacific Crest Trail + Pictorial works. + + + Pacific Crest Trail + Description and travel. + + + Pacific Crest Trail + Description and travel + Pictorial works. + + + Illustrated works. + lcgft + https://id.loc.gov/authorities/genreForms/gf2014026111 + + + Berger, Karen, + 1959- + + + Smith, Daniel R. + (Daniel Richard) + + + **LC HAS REQ'D # OF SHELF COPIES** + + + c-GenColl + GV199.42.P3 + S65 1998 fol. + Copy 1 + BOOKS + +16marcxmlxml + 03628cam a2200589 a 4500 + 19025892 + 20250607070829.0 + 160322s2016 nyuab 000 0 eng d + + 19025892 + + + 7 + cbc + copycat + 2 + ncip + 20 + y-gencatlg + + + acquire + 1 shelf copy + policy default + + + re24 2021-01-15 z-processor + re24 2021-01-15 to CALM (telework) + + + pc16 2016-03-22 + + + LCAP batch update 2025-06-02-04:00: LCAPM-893 + + + 2016936717 + + + 0847849767 + + + 9780847849765 + + + (OCoLC)940933014 + + + Random House Inc, Attn Order Entry 400 Hahn rd, Westminster, MD, USA, 21157 + SAN 201-3975 + + + YDXCP + eng + YDXCP + BTCTA + BDX + OCLCQ + AZT + OCLCO + ORX + JRZ + UOL + FM0 + OCLCF + CUY + OCL + XFF + WAU + ILM + XFG + NZAUC + SFR + UTP + OCLCO + OCL + OCLCO + OCLCQ + OCL + DLC + + + lccopycat + + + GV199.42 .P3 + L37 2016 + + + 917.95 + 23 + + + Larabee, Mark, + author. + + + The Pacific Crest trail : + exploring America's wilderness trail / + Mark Larabee and Barney Scout Mann ; foreword by Cheryl Strayed. + + + New York, NY : + Rizzoli International Publications, Inc., + 2016. + + + 334 pages : + illustrations, maps ; + 26 cm + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Folded map in pocket at end. + + + Origins -- Recognition -- It's official -- Literature -- People -- Visions -- Volunteers -- Stewards -- Photo galleries: Mexico to Canada. + + + This official book celebrates the history, beauty, and importance of the West Coast's most iconic hiking trail. Designated as one of the first two national scenic trails in 1968, the Pacific Crest Trail is a continuous footpath of more than 2,650 miles - from the Mexican border to the Canadian border through California, Oregon, and Washington. Hikers from all over the world are drawn to this trail to experience true American wilderness and to challenge themselves - whether for two miles or two thousand. The only illustrated book officially published with the Pacific Crest Trail Association, The Pacific Crest Trail explores this legendary footpath with more than 250 spectacular contemporary images, unpublished historical photos and documents from the PCTA archives, and even the official trail map folded into an inside pocket. This book is perfect for anyone interested in conservation, outdoor recreation, and for all those who dream of one day becoming thru-hikers themselves. + + + Travel. + fast + (OCoLC)fst01155558 + + + Pacific Crest Trail + Description and travel. + + + Pacific Crest Trail + Pictorial works. + + + United States + Pacific Crest Trail. + fast + (OCoLC)fst01243524 + + + Illustrated works. + + + Travel writing. + fast + (OCoLC)fst01919983 + + + Photobooks. + fast + (OCoLC)fst01919950 + + + Personal correspondence. + fast + (OCoLC)fst01919948 + + + Essays. + fast + (OCoLC)fst01919922 + + + Illustrated works. + fast + (OCoLC)fst01423873 + + + Pictorial works. + fast + (OCoLC)fst01423874 + + + Photobooks. + lcgft + + + Travel writing. + lcgft + + + Essays. + lcgft + + + Personal correspondence. + lcgft + + + Illustrated works. + lcgft + https://id.loc.gov/authorities/genreForms/gf2014026111 + + + Mann, Barney Scout, + author. + + + Strayed, Cheryl, + 1968- + writer of foreword. + + + Pacific Crest Trail Association, + issuing body. + +17marcxmlxml + 01804cam a2200421 i 4500 + 20619947 + 20250607091012.5 + 180807t20192019nyua 000 0 eng + + 20619947 + + + 7 + cbc + orignew + 2 + epcn + 20 + y-gencatlg + + + acquire + 1 shelf copy + policy default + + + pc16 2018-08-07 + xn11 2021-07-12 1 copy rec'd., to USASH + re25 2021-09-15 (TW situational) + re12 2021-09-16 to CMD [Telework] + ma02 2022-04-01 TW Situational + + + LCAP batch update 2025-06-02-04:00: LCAPM-893 + + + 2018954290 + + + 9780847864515 + (Hardcover : + alk. paper) + + + DLC + eng + DLC + rda + DLC + + + pcc + + + n-us-ca + n-us-or + n-us-wa + + + GV199.42.P3 + S654 2019 + + + Smith, Bart, + 1959- + author. + + + The Pacific Crest Trail : + hiking America's wilderness trail / + Bart Smith ; foreword by Mark Larabee. + + + First U.S. Edition. + + + New York : + Rizzoli International Publications, Inc., + [2019] + + + © 2019. + + + 222 pages : + color illustrations ; + 14 x 19 cm + + + text + txt + rdacontent + + + still image + sti + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + "Pacific Crest Trail Association." + + + Hiking + Pacific Crest Trail + Pictorial works. + + + Trails + California + Pictorial works. + + + Trails + Oregon + Pictorial works. + + + Trails + Washington (State) + Pictorial works. + + + Pacific Crest Trail + Pictorial works. + + + Illustrated works. + lcgft + https://id.loc.gov/authorities/genreForms/gf2014026111 + + + Larabee, Mark, + author of introduction, etc. + + + Pacific Crest Trail Association, + sponsor. + +18marcxmlxml + 01622cem a2200409 a 4500 + 12969226 + 20250606194816.6 + aj canzn + 021015s1982 orudg a f 0 eng + + 12969226 + + + 7 + cbc + origcop + u + ncip + 20 + n-geogmaps + + + ga09 2002-10-15 sent to CMT + + + LCAP batch update 2025-06-01-04:00: LCAPM-779, LCAPM-893 + + + 2002628614 + + + a + + + DLC + DLC + + + G4232.P3E63 1982 + .U53 + + + 4232 + P3 + + + 4281 + + + E63 + lcg + + + United States. + Forest Service. + Pacific Northwest Region. + + + Pacific Crest National Scenic Trail : + Washington / + Forest Service, U.S. Department of Agriculture, Pacific Northwest Region. + + + Rev. 1974, [1982]. + + + Scale not given. + + + Portland, Or. : + The Region, + [1982] + + + 1 map in 8 sections on 1 sheet : + both sides, col. ; + on sheet 57 x 89 cm., folded to 22 x 14 cm. + + + cartographic image + cri + rdacontent + + + unmediated + n + rdamedia + + + sheet + nb + rdacarrier + + + Relief shown by hachures and spot heights. + + + "*G.P.O. 1982 594-817." + + + Panel title. + + + Includes text, descriptive trail logs, area map, map of "Pacific Crest National Scenic Trail," and ill. + + + Outdoor recreation + Pacific Crest Trail + Maps. + + + Trails + Washington (State) + Maps. + + + Outdoor recreation + Washington (State) + Maps. + + + Maps. + lcgft + https://id.loc.gov/authorities/genreForms/gf2011026387 + +19marcxmlxml + 01643cem a2200397 i 4500 + 23478083 + 20250607124519.9 + aj canzn + 231221s1971 dcud a f 0 eng + + 23478083 + + + 7 + cbc + origcop + u + ncip + 20 + y-geogmaps + + + acquire + 1 shelf copy + policy default + + + ga45 2012-12-21 + + + LCAP batch update 2025-06-02-04:00: LCAPM-893 + + + 2023599641 + + + a + + + DLC + eng + rda + DLC + + + G4232.P3E63 1971 + .U52 + + + 4232 + P3 + + + 4291 + + + United States. + Forest Service. + Pacific Northwest Region, + cartographer. + + + Pacific Crest National Scenic Trail, Oregon / + Forest Service, U.S. Department of Agriculture, Pacific Northwest Region. + + + Scale not given. + + + [Washington, D.C.] : + Forest Service, U.S. Dept. of Agriculture, + 1971. + + + 8 maps on 1 sheet : + both sides ; + maps 26 x 17 cm, sheet 57 x 89 cm., folded to 23 x 15 cm + + + cartographic image + cri + rdacontent + + + unmediated + n + rdamedia + + + sheet + nb + rdacarrier + + + Title from panel. + + + "*G.P.O. 998-753." + + + Text, trail log information, coverage map, and illustrations on verso. + + + [Map] "A" -- [Map] "B" -- [Map] "C" -- [Map] "D" -- [Map] "E" -- [Map] "F" -- [Map] "G" -- [Map] "I". + + + Outdoor recreation + Pacific Crest Trail + Maps. + + + Trails + Oregon + Maps. + + + Outdoor recreation + Oregon + Maps. + + + Maps. + lcgft + https://id.loc.gov/authorities/genreForms/gf2011026387 + +20211.1bath.any=pacific and bath.any=crest and bath.any=trail20xmlmarcxml diff --git a/src/server/sources/fixtures/loc-title-day-hikes-overnights-on-the-pacific-crest-trail.xml b/src/server/sources/fixtures/loc-title-day-hikes-overnights-on-the-pacific-crest-trail.xml new file mode 100644 index 0000000..6e4920c --- /dev/null +++ b/src/server/sources/fixtures/loc-title-day-hikes-overnights-on-the-pacific-crest-trail.xml @@ -0,0 +1,2 @@ + +1.101.1bath.title="Day hikes & overnights on the Pacific Crest Trail" and bath.author="Kast-Myers"5xmlmarcxml diff --git a/src/server/sources/fixtures/loc-title-sierra-south.xml b/src/server/sources/fixtures/loc-title-sierra-south.xml new file mode 100644 index 0000000..953018d --- /dev/null +++ b/src/server/sources/fixtures/loc-title-sierra-south.xml @@ -0,0 +1,135 @@ + +1.11marcxmlxml + 01502cam a2200421 a 4500 + 1052150 + 20250606162656.9 + 900402s1990 cauab 001 0 eng + + 1052150 + + + 7 + cbc + orignew + 1 + ocip + 19 + y-gencatlg + + + CIP ver. he06 08-13-90 + + + LCAP batch update 2025-06-01-04:00: LCAPM-644, LCAPM-150 + + + 90012325 + + + 0899971156 + + + 9780899971155 + + + (DLC) 90012325 + + + DLC + DLC + DLC + + + n-us-ca + n-us-nv + + + GV199.42.S55 + W564 1990 + + + 917.94/80453 + 20 + + + Winnett, Thomas. + + + Sierra south : + 100 back-country trips in California's Sierra / + Thomas Winnett, Jason Winnett, and Kathy Morey. + + + 5th ed. + + + Berkeley : + Wilderness Press, + 1990. + + + 296 p. : + ill., map ; + 20 cm. + + + text + txt + rdacontent + + + unmediated + n + rdamedia + + + volume + nc + rdacarrier + + + Folded map in pocket. + + + Backpacking + Sierra Nevada (Calif. and Nev.) + Guidebooks. + + + Hiking + Sierra Nevada (Calif. and Nev.) + Guidebooks. + + + Backpacking + California + Guidebooks. + + + Hiking + California + Guidebooks. + + + Sierra Nevada (Calif. and Nev.) + Guidebooks. + + + California + Guidebooks. + + + Winnett, Jason. + + + Morey, Kathy. + + + c-GenColl + GV199.42.S55 + W564 1990 + 00056351747 + Copy 1 + BOOKS + +11.1bath.title="Sierra South" and bath.author="Morey"5xmlmarcxml diff --git a/src/server/sources/fixtures/ol-data-9780899974248.json b/src/server/sources/fixtures/ol-data-9780899974248.json new file mode 100644 index 0000000..4d6dbf1 --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9780899974248.json @@ -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"}}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-data-9780899978840.json b/src/server/sources/fixtures/ol-data-9780899978840.json new file mode 100644 index 0000000..f1fba1d --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9780899978840.json @@ -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"}]}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-data-9781581572025.json b/src/server/sources/fixtures/ol-data-9781581572025.json new file mode 100644 index 0000000..f8cd83d --- /dev/null +++ b/src/server/sources/fixtures/ol-data-9781581572025.json @@ -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"}}} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9780899974248.json b/src/server/sources/fixtures/ol-search-9780899974248.json new file mode 100644 index 0000000..57b30b7 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9780899974248.json @@ -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"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9780899978840.json b/src/server/sources/fixtures/ol-search-9780899978840.json new file mode 100644 index 0000000..3933aa5 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9780899978840.json @@ -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"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-search-9781581572025.json b/src/server/sources/fixtures/ol-search-9781581572025.json new file mode 100644 index 0000000..2909326 --- /dev/null +++ b/src/server/sources/fixtures/ol-search-9781581572025.json @@ -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"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights-hikes.json b/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights-hikes.json new file mode 100644 index 0000000..d69ed75 --- /dev/null +++ b/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights-hikes.json @@ -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"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights.json b/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights.json new file mode 100644 index 0000000..021d713 --- /dev/null +++ b/src/server/sources/fixtures/ol-similar-pacific-crest-trail-overnights.json @@ -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"]}]} \ No newline at end of file diff --git a/src/server/sources/fixtures/ol-similar-pacific-crest-trail.json b/src/server/sources/fixtures/ol-similar-pacific-crest-trail.json new file mode 100644 index 0000000..571ff09 --- /dev/null +++ b/src/server/sources/fixtures/ol-similar-pacific-crest-trail.json @@ -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-0199.42000000.U82 P234 2009"],"subtitle":"tales of the Pacific Crest Trail","title":"A thru-hiker's heart","subject":["Travel","Description and travel","Hiking"]},{"first_publish_year":1976,"key":"/works/OL27734259W","lcc":["F--0851.00000000.P34"],"title":"Pacific Crest Trail hike planning guide","subject":["Hiking","Trails"]},{"author_name":["Ann Sutton"],"first_publish_year":1975,"key":"/works/OL4378785W","lcc":["F--0851.00000000.S97"],"title":"The Pacific Crest Trail","subject":["Trails","Guidebooks","Hiking"]},{"author_name":["Paul Gerald"],"first_publish_year":2012,"key":"/works/OL20152570W","lcc":["GV-0199.42000000.O7G47 2019","GV-0199.42000000.O7 G47 2012"],"title":"Day & Section Hikes Pacific Crest Trail","subject":["Hiking","Oregon, guidebooks","Pacific crest trail","Guidebooks"]},{"author_name":["Ray Jardine"],"first_publish_year":1996,"key":"/works/OL3010370W","lcc":["GV-0199.62000000.J37 1996"],"subtitle":"innovative techniques and trail tested instruction for the long distance hiker","title":"The Pacific Crest Trail hiker's handbook","subject":["Equipment and supplies","Backpacking","Handbooks, manuals"]},{"author_name":["Andrea Lankford"],"first_publish_year":2023,"key":"/works/OL34049532W","title":"Trail of the Lost","subject":["nyt:hardcover-nonfiction=2023-09-10","New York Times bestseller"]},{"author_name":["Jeffrey Schaffer"],"first_publish_year":2003,"key":"/works/OL9604907W","lcc":["GV-0199.42000000.P3 S32 2004"],"title":"The Pacific crest trail","subject":["Guidebooks","Hiking","Pacific states, guidebooks","California, guidebooks","Trails","Oregon, description and travel","Washington (d.c.), description and travel"]},{"author_name":["Pacific Crest Trail Data Book"],"first_publish_year":2000,"key":"/works/OL9734727W","title":"Pacific Crest Trail Data Book"},{"author_name":["Bart Smith"],"first_publish_year":2019,"key":"/works/OL20163098W","title":"The Pacific Crest Trail"},{"author_name":["K. Scott Parks"],"first_publish_year":2011,"key":"/works/OL20424114W","title":"Pacific Crest Trail Pocket Maps - Southern California","subject":["Pacific crest trail","California, maps"]},{"author_name":["George Semb","Patricia Semb"],"first_publish_year":2000,"key":"/works/OL18168439W","lcc":["GV-0199.42000000.O7S46 2000"],"title":"Day hikes on the Pacific Crest Trail","subject":["Guidebooks","Hiking","Oregon, guidebooks","Washington (state), guidebooks","Pacific crest trail"]}]} \ No newline at end of file diff --git a/src/server/sources/loc.ts b/src/server/sources/loc.ts index 81dfb9e..fe316d4 100644 --- a/src/server/sources/loc.ts +++ b/src/server/sources/loc.ts @@ -19,6 +19,8 @@ export interface Loc { byTitle(title: string, author: string): Promise; /** Records whose title, subjects or notes mention every keyword (the `bath.any` index). */ byKeywords(keywords: string[]): Promise; + /** Records whose title alone has every word (the `bath.title` index, unquoted so the words may be apart). */ + byTitleWords(words: string[]): Promise; } 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([]); diff --git a/src/server/sources/marc.test.ts b/src/server/sources/marc.test.ts index b37aa61..15a065b 100644 --- a/src/server/sources/marc.test.ts +++ b/src/server/sources/marc.test.ts @@ -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[]) => `${a.map((x) => `${x}`).join('')}`; + assert.deepEqual(parseMarcXml(xml(['0201835959 (pbk.)', '9780201835953', 'not an isbn']))[0]!.isbns, ['9780201835953']); + assert.deepEqual(parseMarcXml('x')[0]!.isbns, []); +}); diff --git a/src/server/sources/marc.ts b/src/server/sources/marc.ts index c3f6639..556f842 100644 --- a/src/server/sources/marc.ts +++ b/src/server/sources/marc.ts @@ -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; @@ -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. */ diff --git a/src/shared/callnumber.ts b/src/shared/callnumber.ts index a745292..3221a0b 100644 --- a/src/shared/callnumber.ts +++ b/src/shared/callnumber.ts @@ -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 : ''); } diff --git a/src/shared/cardcode.test.ts b/src/shared/cardcode.test.ts new file mode 100644 index 0000000..be2fac1 --- /dev/null +++ b/src/shared/cardcode.test.ts @@ -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 }); +}); diff --git a/src/shared/cardcode.ts b/src/shared/cardcode.ts new file mode 100644 index 0000000..4e8b11b --- /dev/null +++ b/src/shared/cardcode.ts @@ -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 }; +} diff --git a/src/shared/shelf.test.ts b/src/shared/shelf.test.ts new file mode 100644 index 0000000..8ed2351 --- /dev/null +++ b/src/shared/shelf.test.ts @@ -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]); +}); diff --git a/src/shared/shelf.ts b/src/shared/shelf.ts new file mode 100644 index 0000000..5b75882 --- /dev/null +++ b/src/shared/shelf.ts @@ -0,0 +1,22 @@ +import type { Book } from './types.ts'; +import { mainEntry } from './cutter.ts'; + +type Shelved = Pick; + +/** + * 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; +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 054ee7a..dc06993 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -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[]; diff --git a/src/web/actions.ts b/src/web/actions.ts index ea6efdc..aa66f4b 100644 --- a/src/web/actions.ts +++ b/src/web/actions.ts @@ -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>(); @@ -41,3 +41,33 @@ export async function addFromResult(r: SearchResult): Promise { 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>(); + +/** + * 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 { + 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; +} diff --git a/src/web/api.ts b/src/web/api.ts index 486ea3d..3c5db8d 100644 --- a/src/web/api.ts +++ b/src/web/api.ts @@ -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('GET', `/api/search?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`), diff --git a/src/web/components/CallNo.tsx b/src/web/components/CallNo.tsx index dbfa328..cedde75 100644 --- a/src/web/components/CallNo.tsx +++ b/src/web/components/CallNo.tsx @@ -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 –; const cn = parseCallNumber(value); diff --git a/src/web/decode.test.ts b/src/web/decode.test.ts index 23d0544..c241bfe 100644 --- a/src/web/decode.test.ts +++ b/src/web/decode.test.ts @@ -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 }); +}); diff --git a/src/web/decode.ts b/src/web/decode.ts index 9fbdac1..7bf3191 100644 --- a/src/web/decode.ts +++ b/src/web/decode.ts @@ -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 { - 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; diff --git a/src/web/readstate.test.ts b/src/web/readstate.test.ts index 1c63a2c..8141bd0 100644 --- a/src/web/readstate.test.ts +++ b/src/web/readstate.test.ts @@ -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); +}); diff --git a/src/web/readstate.ts b/src/web/readstate.ts index d528f53..caa3df6 100644 --- a/src/web/readstate.ts +++ b/src/web/readstate.ts @@ -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 } }; +} diff --git a/src/web/scanner.ts b/src/web/scanner.ts index 28be836..e0ab87d 100644 --- a/src/web/scanner.ts +++ b/src/web/scanner.ts @@ -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 { 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; } diff --git a/src/web/store.ts b/src/web/store.ts index 607ac76..e4eb50b 100644 --- a/src/web/store.ts +++ b/src/web/store.ts @@ -1,4 +1,5 @@ import type { Book } from '../shared/types.ts'; +import { compareShelf } from '../shared/shelf.ts'; export interface BookState { byId: Record } 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); diff --git a/src/web/views/Camera.tsx b/src/web/views/Camera.tsx index 385858d..63ff5ab 100644 --- a/src/web/views/Camera.tsx +++ b/src/web/views/Camera.tsx @@ -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(null); const scanner = useRef(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 { diff --git a/src/web/views/Scan.tsx b/src/web/views/Scan.tsx index 2d35f10..0b72126 100644 --- a/src/web/views/Scan.tsx +++ b/src/web/views/Scan.tsx @@ -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 (
- { void addByIsbn(isbn); }} /> + { void addByIsbn(isbn); }} + onCard={text => { void addFromCard(text, id => onEdit({ kind: 'edit', id })); }} />