Files
booksorter/scripts/gen-lcc-outline.ts
T

119 lines
5.2 KiB
TypeScript

// Generates src/shared/lcc-outline.ts 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';
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);
// Fix-ups applied to names after sentence-casing / extraction.
const MAIN_FIXES: Record<string, string> = {
'Auxiliary sciences of history': 'Auxiliary sciences of history',
};
const SUB_FIXES: Record<string, string> = {
'Christian Denominations': 'Christian denominations',
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function get(url: string, file: string): Promise<Buffer> {
const p = join(cache, file);
if (existsSync(p)) return readFileSync(p);
const res = await fetch(url, { headers: { 'User-Agent': UA } });
if (!res.ok) throw new Error(`${url}: ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
writeFileSync(p, buf);
await sleep(1000);
return buf;
}
const clean = (s: string) => s.replace(/\s+/g, ' ').trim();
function sentenceCase(s: string): string {
const t = clean(s).toLowerCase();
return t
.replace(/(^|\. )([a-z])/g, (_m, a: string, b: string) => a + b.toUpperCase())
.replace(/\((general)\)/g, '(General)')
.replace(/\b(europe|asia|africa|australia|new zealand|americas?)\b/g, (w) => w.replace(/\b[a-z]/g, (c) => c.toUpperCase()))
.replace(/,? etc$/, ', etc.');
}
// Captions over 120 chars (PT lists many literatures) are cut at the last " - " that fits.
function shorten(s: string): string {
if (s.length <= 120) return s;
const parts = s.split(' - ');
let r = parts[0]!;
for (const p of parts.slice(1)) {
if ((r + ' - ' + p).length > 120) break;
r += ' - ' + p;
}
return r.length <= 120 ? r : r.slice(0, 119).trimEnd() + '…';
}
const indexHtml = (await get(INDEX, 'index.html')).toString('utf8');
const hrefs = [...new Set([...indexHtml.matchAll(/href="([^"]*lcco_[a-z]+\.pdf)"/g)].map((m) => m[1]!))];
if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.length}`);
const MAIN: Record<string, string> = {};
const SUB: Record<string, string> = {};
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');
// Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines.
const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l));
if (ti < 0) throw new Error(`no title in ${name}`);
const tm = lines[ti]!.match(/CLASS ([A-Z])(?:-([A-Z]))? - (.*)$/)!;
let title = tm[3]!;
for (let i = ti + 1; i < lines.length && lines[i]!.trim() && !lines[i]!.includes('Click'); i++) title += ' ' + lines[i]!.trim();
const mainName = sentenceCase(title.replace(/[.,]\s*$/, ''));
for (const c of [tm[1]!, tm[2]].filter(Boolean) as string[]) MAIN[c] = MAIN_FIXES[mainName] ?? mainName;
// Summary list at top: "Subclass QA Mathematics" with indented wrapped continuations.
for (let i = ti; i < lines.length; i++) {
const l = lines[i]!;
if (/^\s*Subclass [A-Z]+\s*$/.test(l) || /^[A-Z]{1,3}\d/.test(l)) break; // detail section starts
const m = l.match(/^\s*Subclass ([A-Z]{1,3})\s{2,}(\S.*)$/);
if (!m) continue;
let cap = m[2]!;
while (i + 1 < lines.length && /^\s{4,}\S/.test(lines[i + 1]!) && !/^\s*Subclass /.test(lines[i + 1]!)) cap += ' ' + lines[++i]!.trim();
cap = clean(cap).replace(/\.$/, '');
SUB[m[1]!] = shorten(SUB_FIXES[cap] ?? cap);
}
}
const q = (s: string) => JSON.stringify(s);
const rec = (o: Record<string, string>) =>
Object.keys(o).sort().map((k) => ` ${k}: ${q(o[k]!)},`).join('\n');
const src = `// 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
export const MAIN_CLASSES: Record<string, string> = {
${rec(MAIN)}
};
export const SUBCLASSES: Record<string, string> = {
${rec(SUB)}
};
export function classNames(letters: string): { className: string | null; subclassName: string | null } {
const l = letters.trim().toUpperCase();
if (!/^[A-Z]{1,3}$/.test(l)) return { className: null, subclassName: null };
const className = MAIN_CLASSES[l[0]!] ?? null;
const subclassName = SUBCLASSES[l] ?? (l.length === 3 ? (SUBCLASSES[l.slice(0, 2)] ?? null) : null);
return { className, subclassName };
}
`;
writeFileSync(out, src);
console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`);