Print the subject hierarchy as a tree on cards, remove the QR code
Each card now shows, under the call number, the Library of Congress outline levels for its class (from the published outline, down to the narrowest range) followed by the place or topic from the catalogue record's subject heading, one level per line. Existing books get the subject part filled in by a background job at startup that changes nothing else about them. The QR code and everything that read it are removed; the subjects line on the card is replaced by the tree. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
c9b2c2e8c9
commit
7ae1bcef0a
46 files changed
+8591
-545
No files matched your search
@@ -1,17 +1,21 @@
|
||||
// Generates src/shared/lcc-outline.ts from the Library of Congress Classification
|
||||
// Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication.
|
||||
// Generates src/shared/lcc-outline.ts (main classes and subclasses, used by the web app too) and
|
||||
// src/server/lcc-ranges.ts (every nested number range with its caption, server only) from the Library of
|
||||
// Congress Classification Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication.
|
||||
// Usage: node scripts/gen-lcc-outline.ts [cacheDir] (or env LCC_CACHE_DIR)
|
||||
// Requires `pdftotext` (poppler). Downloads are cached outside the repo.
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { parseOutlineText } from './lcc-parse.ts';
|
||||
import type { Range } from './lcc-parse.ts';
|
||||
|
||||
const INDEX = 'https://www.loc.gov/catdir/cpso/lcco/';
|
||||
const UA = 'Mozilla/5.0 (compatible; lcc-outline-generator)';
|
||||
const cache = process.argv[2] ?? process.env.LCC_CACHE_DIR ?? join(tmpdir(), 'lcc-outline-cache');
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const out = new URL('../src/shared/lcc-outline.ts', import.meta.url);
|
||||
const outRanges = new URL('../src/server/lcc-ranges.ts', import.meta.url);
|
||||
|
||||
// Fix-ups applied to names after sentence-casing / extraction.
|
||||
const MAIN_FIXES: Record<string, string> = {
|
||||
@@ -61,12 +65,17 @@ if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.l
|
||||
|
||||
const MAIN: Record<string, string> = {};
|
||||
const SUB: Record<string, string> = {};
|
||||
const RANGES = new Map<string, Range[]>();
|
||||
|
||||
for (const href of hrefs) {
|
||||
const name = href.split('/').pop()!;
|
||||
const pdf = join(cache, name);
|
||||
await get(new URL(href, INDEX).href, name);
|
||||
const lines = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\n');
|
||||
const text = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 });
|
||||
const lines = text.split('\n');
|
||||
const parsed = parseOutlineText(text);
|
||||
for (const [letters, rows] of parsed.ranges) RANGES.set(letters, rows);
|
||||
for (const p of parsed.problems) console.warn(`${name}: skipped "${p}"`);
|
||||
|
||||
// Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines.
|
||||
const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l));
|
||||
@@ -116,3 +125,21 @@ export function classNames(letters: string): { className: string | null; subclas
|
||||
`;
|
||||
writeFileSync(out, src);
|
||||
console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`);
|
||||
|
||||
const rangesSrc = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand.
|
||||
// Source: Library of Congress Classification Outline, ${INDEX}
|
||||
// (a US government publication). Re-run: node scripts/gen-lcc-outline.ts
|
||||
// Server only: the web app does not import this file.
|
||||
|
||||
/** [lo, hi, caption], or [lo, hi, caption, cutterLo, cutterHi] for a range bounded by cutters. Captions are verbatim. */
|
||||
export type OutlineRange = [lo: number, hi: number, caption: string, cutterLo?: string, cutterHi?: string];
|
||||
|
||||
/** Every range of the outline by class letters, in outline order (a range comes before the ranges nested in it). */
|
||||
export const OUTLINE_RANGES: Record<string, OutlineRange[]> = {
|
||||
${[...RANGES.keys()].sort().map((k) => ` ${k}: [\n${RANGES.get(k)!.map((r) => ' ' + JSON.stringify(r)).join(',\n')},\n ],`).join('\n')}
|
||||
};
|
||||
`;
|
||||
writeFileSync(outRanges, rangesSrc);
|
||||
const perClass: Record<string, number> = {};
|
||||
for (const [k, rows] of RANGES) perClass[k[0]!] = (perClass[k[0]!] ?? 0) + rows.length;
|
||||
console.log(`wrote ${[...RANGES.values()].reduce((n, r) => n + r.length, 0)} ranges in ${RANGES.size} subclasses; per main class: ${Object.entries(perClass).map(([k, n]) => k + '=' + n).join(' ')}`);
|
||||
@@ -0,0 +1,67 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { cleanCaption, parseBounds, parseOutlineText } from './lcc-parse.ts';
|
||||
|
||||
test('number ranges in every form the outline uses', () => {
|
||||
assert.deepEqual(parseBounds('191.2-200.66'), { lo: 191.2, hi: 200.66 });
|
||||
assert.deepEqual(parseBounds('1201.5'), { lo: 1201.5, hi: 1201.5 });
|
||||
assert.deepEqual(parseBounds('1115-(1193)'), { lo: 1115, hi: 1193 });
|
||||
assert.deepEqual(parseBounds('(1)-1281'), { lo: 1, hi: 1281 });
|
||||
assert.deepEqual(parseBounds('1569.C2'), { lo: 1569, hi: 1569, cutterLo: 'C2', cutterHi: 'C2' });
|
||||
assert.deepEqual(parseBounds('469.M21-.M38'), { lo: 469, hi: 469, cutterLo: 'M21', cutterHi: 'M38' });
|
||||
assert.deepEqual(parseBounds('990.U45-U46', 'DA'), { lo: 990, hi: 990, cutterLo: 'U45', cutterHi: 'U46' });
|
||||
assert.deepEqual(parseBounds('1.A5-3.3'), { lo: 1, hi: 3.3, cutterLo: 'A5' });
|
||||
assert.deepEqual(parseBounds('12.5-.9'), { lo: 12.5, hi: 12.9 });
|
||||
assert.deepEqual(parseBounds('1003-Z1005.5', 'Z'), { lo: 1003, hi: 1005.5 });
|
||||
assert.equal(parseBounds('4440-4406'), null);
|
||||
assert.equal(parseBounds('274.5-6'), null);
|
||||
});
|
||||
|
||||
test('captions: wraps joined, notes dropped, headers and breaks ignored, nesting kept in order', () => {
|
||||
const text = [
|
||||
' LIBRARY OF CONGRESS CLASSIFICATION OUTLINE',
|
||||
'Subclass GV Recreation. Leisure',
|
||||
'Subclass GV',
|
||||
'',
|
||||
'GV1-1860 Recreation. Leisure',
|
||||
'GV191.2-200.66 Outdoor life. Outdoor recreation',
|
||||
'GV199-199.62 Hiking. Pedestrian tours',
|
||||
'GV346-351.5 School and college athletics. Intramural',
|
||||
' and interscholastic athletics',
|
||||
'GV401-433 Physical education facilities.',
|
||||
' Including gymnasiums, athletic fields,',
|
||||
' playgrounds, etc.',
|
||||
'\fGV1470-1511 Parties. Party games and stunts',
|
||||
'GV1201.5 Hobbies (General)',
|
||||
'Subclass GX',
|
||||
'GX5 Heading',
|
||||
' Individual states',
|
||||
].join('\n');
|
||||
const { ranges, problems } = parseOutlineText(text);
|
||||
assert.deepEqual(problems, []);
|
||||
assert.deepEqual(ranges.get('GV'), [
|
||||
[1, 1860, 'Recreation. Leisure'],
|
||||
[191.2, 200.66, 'Outdoor life. Outdoor recreation'],
|
||||
[199, 199.62, 'Hiking. Pedestrian tours'],
|
||||
[346, 351.5, 'School and college athletics. Intramural and interscholastic athletics'],
|
||||
[401, 433, 'Physical education facilities'],
|
||||
[1470, 1511, 'Parties. Party games and stunts'],
|
||||
[1201.5, 1201.5, 'Hobbies (General)'],
|
||||
]);
|
||||
assert.deepEqual(ranges.get('GX'), [[5, 5, 'Heading']]);
|
||||
});
|
||||
|
||||
test('unreadable ranges are reported, not guessed', () => {
|
||||
const { ranges, problems } = parseOutlineText('Subclass KZ\nKZD4440-4406 Liability for accidents\nKZ5 Fine\n');
|
||||
assert.equal(problems.length, 1);
|
||||
assert.deepEqual(ranges.get('KZ'), [[5, 5, 'Fine']]);
|
||||
});
|
||||
|
||||
test('caption clean-up trims debris only', () => {
|
||||
assert.equal(cleanCaption(' Law and\n order , '), 'Law and order');
|
||||
assert.equal(cleanCaption('Museology. Museum methods, technique, etc.'), 'Museology. Museum methods, technique, etc.');
|
||||
assert.equal(cleanCaption('Purānas .'), 'Purānas');
|
||||
assert.equal(cleanCaption('1789'), '1789-');
|
||||
assert.equal(cleanCaption('1871- . Later 19th century'), '1871- . Later 19th century');
|
||||
assert.equal(cleanCaption('Persian wars, 499-479 B.C.'), 'Persian wars, 499-479 B.C.');
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
// Parses the text of one Library of Congress Classification Outline PDF (from `pdftotext -layout`)
|
||||
// into its number ranges with their captions. Used by gen-lcc-outline.ts; no I/O here.
|
||||
|
||||
/** [lo, hi, caption] or, for ranges bounded by cutters, [lo, hi, caption, cutterLo, cutterHi]. */
|
||||
export type Range = [lo: number, hi: number, caption: string, cutterLo?: string, cutterHi?: string];
|
||||
|
||||
export interface Parsed {
|
||||
/** Ranges by class letters (PS, GV, KBM), in the order they appear in the outline. */
|
||||
ranges: Map<string, Range[]>;
|
||||
/** Lines that looked like a range but could not be read; reported by the generator. */
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
const NUM = String.raw`\(?(\d+(?:\.\d+)?)\)?`;
|
||||
const START = new RegExp(String.raw`^${NUM}(?:\.([A-Z]\d*))?$`);
|
||||
const END_NUMBER = new RegExp(String.raw`^([A-Z]{1,3}(?=[\d(]))?${NUM}(?:\.([A-Z]\d*))?$`);
|
||||
const END_DECIMAL = /^\.(\d+)$/;
|
||||
const END_CUTTER = /^\.?([A-Z]\d*)$/;
|
||||
const NOTE = /^(Including|Class |For |See |Subarrange|Cf\.)/;
|
||||
|
||||
export interface Bounds { lo: number; hi: number; cutterLo?: string; cutterHi?: string }
|
||||
|
||||
/** The number part of a code such as `191.2-200.66`, `1569.C2`, `469.M21-.M38` or `1115-(1193)`; null if unreadable. */
|
||||
export function parseBounds(code: string, letters = ''): Bounds | null {
|
||||
const dash = code.indexOf('-');
|
||||
const startText = dash < 0 ? code : code.slice(0, dash);
|
||||
const s = START.exec(startText);
|
||||
if (!s) return null;
|
||||
const lo = Number(s[1]);
|
||||
const out: Bounds = { lo, hi: lo };
|
||||
if (s[2]) out.cutterLo = s[2];
|
||||
if (dash < 0) { if (s[2]) out.cutterHi = s[2]; return out; }
|
||||
const endText = code.slice(dash + 1);
|
||||
let m: RegExpExecArray | null;
|
||||
// "U46" after "DA990.U45" is a cutter; "Z1003.5" after "Z1" repeats the class letters. Tell them apart by the letters.
|
||||
if ((m = END_NUMBER.exec(endText)) && (!m[1] || m[1] === letters) && Number(m[2]) >= lo) {
|
||||
out.hi = Number(m[2]);
|
||||
if (m[3]) out.cutterHi = m[3];
|
||||
} else if ((m = END_DECIMAL.exec(endText))) {
|
||||
out.hi = Number(`${Math.trunc(lo)}.${m[1]}`);
|
||||
} else if ((m = END_CUTTER.exec(endText))) {
|
||||
out.cutterHi = m[1]!;
|
||||
} else return null;
|
||||
if (out.hi < out.lo) return null;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A caption as published: one line of text, no stray marks; a lone full stop (a diacritic dot the PDF set on its own line) is dropped. */
|
||||
export function cleanCaption(raw: string): string {
|
||||
let s = raw.replace(//g, '-').replace(/\s+/g, ' ').trim();
|
||||
s = s.replace(/(?<!-) \.(?= |$)/g, '').replace(/\s+/g, ' ').trim();
|
||||
// Trailing debris only: commas, semicolons, colons and a lone full stop after a word; "etc." and "Co." style stops stay.
|
||||
s = s.replace(/[,;:\s]+$/, '');
|
||||
if (/[a-z]{3,}\.$/.test(s) && !/\betc\.$/.test(s)) s = s.slice(0, -1);
|
||||
return s;
|
||||
}
|
||||
|
||||
export function parseOutlineText(text: string): Parsed {
|
||||
const ranges = new Map<string, Range[]>();
|
||||
const problems: string[] = [];
|
||||
let started = false;
|
||||
let cur: { letters: string; index: number; capCol: number; caption: string } | null = null;
|
||||
let inNote = false;
|
||||
|
||||
const finish = () => {
|
||||
if (!cur) return;
|
||||
const list = ranges.get(cur.letters)!;
|
||||
const r = list[cur.index]!;
|
||||
r[2] = cleanCaption(cur.caption);
|
||||
cur = null;
|
||||
};
|
||||
|
||||
for (const rawLine of text.split('\n')) {
|
||||
const line = rawLine.replace(/\f/g, '').replace(/\s+$/, '');
|
||||
if (/^(?:Sub)?[Cc]lass [A-Z]{1,3}\s*$/.test(line)) { finish(); started = true; inNote = false; continue; }
|
||||
if (!started || !line.trim()) continue;
|
||||
|
||||
const codeLine = /^([A-Z]{1,3})((?:\(\d+\)|\d)\S*)\s+(\S.*)$/.exec(line) ?? /^([A-Z]{1,3})((?:\(\d+\)|\d)\S*)\s*$/.exec(line);
|
||||
if (codeLine) {
|
||||
finish();
|
||||
inNote = false;
|
||||
const [, letters, code, caption = ''] = codeLine as unknown as [string, string, string, string?];
|
||||
const b = parseBounds(code, letters);
|
||||
if (!b) { problems.push(line.trim()); continue; }
|
||||
if (!ranges.has(letters)) ranges.set(letters, []);
|
||||
const list = ranges.get(letters)!;
|
||||
const row: Range = [b.lo, b.hi, ''];
|
||||
if (b.cutterLo !== undefined || b.cutterHi !== undefined) { row[3] = b.cutterLo ?? ''; row[4] = b.cutterHi ?? ''; }
|
||||
list.push(row);
|
||||
cur = { letters, index: list.length - 1, capCol: line.length - caption.length, caption };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Anything else: a wrapped caption, a note under a caption, or a heading without a range.
|
||||
const indent = line.length - line.trimStart().length;
|
||||
const t = line.trim();
|
||||
if (!cur) continue;
|
||||
if (indent <= cur.capCol) { finish(); inNote = false; continue; } // a heading line, not part of the range above
|
||||
if (inNote) continue;
|
||||
if (NOTE.test(t)) { inNote = true; continue; }
|
||||
cur.caption += ' ' + t;
|
||||
}
|
||||
finish();
|
||||
for (const [letters, list] of ranges) {
|
||||
ranges.set(letters, list.filter((r) => {
|
||||
if (r[2]) return true;
|
||||
problems.push(`${letters}${r[0]}-${r[1]}: empty caption`);
|
||||
return false;
|
||||
}));
|
||||
}
|
||||
return { ranges, problems };
|
||||
}
|
||||
Reference in new issue
Block a user