@effortlessmotion/pdf-to-md 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/analyze.js.map +1 -1
- package/dist/cjs/audit.js.map +1 -1
- package/dist/cjs/cli/audit.js.map +1 -1
- package/dist/cjs/cli/extract.js.map +1 -1
- package/dist/cjs/cli/index.js.map +1 -1
- package/dist/cjs/cli/render.js.map +1 -1
- package/dist/cjs/cli/types.js.map +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/collect.js.map +1 -1
- package/dist/cjs/dict.js.map +1 -1
- package/dist/cjs/emit.js.map +1 -1
- package/dist/cjs/engines/tesseract.js.map +1 -1
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/extract.js.map +1 -1
- package/dist/cjs/geometry.js.map +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lines.js.map +1 -1
- package/dist/cjs/markdown.js.map +1 -1
- package/dist/cjs/page-marker.js.map +1 -1
- package/dist/cjs/pdf-open.js.map +1 -1
- package/dist/cjs/raster.js.map +1 -1
- package/dist/cjs/render-analysis.js.map +1 -1
- package/dist/cjs/report.js.map +1 -1
- package/dist/cjs/resolve.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/validate.js.map +1 -1
- package/dist/esm/analyze.js.map +1 -1
- package/dist/esm/audit.js.map +1 -1
- package/dist/esm/cli/audit.js.map +1 -1
- package/dist/esm/cli/extract.js.map +1 -1
- package/dist/esm/cli/index.js.map +1 -1
- package/dist/esm/cli/render.js.map +1 -1
- package/dist/esm/cli/types.js.map +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/collect.js.map +1 -1
- package/dist/esm/dict.js.map +1 -1
- package/dist/esm/emit.js.map +1 -1
- package/dist/esm/engines/tesseract.js.map +1 -1
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/extract.js.map +1 -1
- package/dist/esm/geometry.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lines.js.map +1 -1
- package/dist/esm/markdown.js.map +1 -1
- package/dist/esm/page-marker.js.map +1 -1
- package/dist/esm/pdf-open.js.map +1 -1
- package/dist/esm/raster.js.map +1 -1
- package/dist/esm/render-analysis.js.map +1 -1
- package/dist/esm/report.js.map +1 -1
- package/dist/esm/resolve.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/validate.js.map +1 -1
- package/package.json +10 -1
package/dist/cjs/analyze.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/analyze.ts"],"sourcesContent":["// analyze() plus the OCR-path core (buildOcrAnalysisPages) that extractOcr\n// shares with it — same buildPageOCR -> emitPage -> renderPagesToMarkdown pipeline, so OCR-path markdown is byte-identical by construction, not two implementations kept in sync by hand. The TEXT path is NOT shared this way (see analyzeText).\nimport { collect, pageCount } from './collect.ts';\nimport { dictAvailable, dictUnavailableWarning } from './dict.ts';\nimport type { EmitBlock } from './emit.ts';\nimport { emitPage, renderEmitBlock } from './emit.ts';\n// Type-only: erased at compile time, so this does NOT create a runtime\n// circular dependency even though src/extract.ts imports (value-level) from this module.\nimport type { ExtractOcrOptions, ExtractTextOptions, OcrWordInput } from './extract.ts';\nimport type { PageOCR, Tuning, Word } from './geometry.ts';\nimport { buildPageOCR, DEFAULT_TUNING, headingLevels } from './geometry.ts';\nimport { toLines } from './lines.ts';\nimport { buildMarkdown } from './markdown.ts';\nimport { renderPagesToMarkdown } from './render-analysis.ts';\nimport { buildOcrReport, buildReport, OUTPUT_VERSION } from './report.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage, AnalysisWord, Line, PageLines } from './types.ts';\nimport { validateOcrAnalysisInput, validatePages, validateWordsInput } from './validate.ts';\n\n/** analyze(pdf) with the default/'text' path — OCR-only fields don't exist\n * on this branch, so passing e.g. `tuning` without `path: 'ocr'` is a compile error. */\nexport type AnalyzeTextOptions = ExtractTextOptions & { path?: 'text' };\n\n/** analyze(pdf, {path:'ocr'}) — same fields as {@link ExtractOcrOptions},\n * unlocked only once `path: 'ocr'` is set. */\nexport type AnalyzeOcrOptions = ExtractOcrOptions & { path: 'ocr' };\n\n/** Options for {@link analyze}: which fields type-check depends on `path`\n * (ignored, forced 'ocr', when `input` is a `{ words }` replay). */\nexport type AnalyzeOptions = AnalyzeTextOptions | AnalyzeOcrOptions;\n\nfunction toAnalysisWord(w: OcrWordInput): AnalysisWord {\n const box = { x: w.x, y: w.y, w: w.w, h: w.h };\n return w.confidence === undefined ? { text: w.text, box } : { text: w.text, box, confidence: w.confidence };\n}\n\n// EmitBlock -> AnalysisBlock: collapses emit.ts's 'quote' kind (a pull-quote)\n// into Analysis's 'paragraph' type, `text` keeping its literal '> ' prefix — see AnalysisBlock's doc comment (src/types.ts) for why.\nfunction toAnalysisBlock(b: EmitBlock, wordIndex: Map<Word, number>): AnalysisBlock {\n const wordIndexes = b.words.map((w) => wordIndex.get(w) as number);\n if (b.kind === 'heading') return { type: 'heading', text: b.text, level: b.level, wordIndexes };\n if (b.kind === 'review') return { type: 'review', text: renderEmitBlock(b), wordIndexes };\n return { type: 'paragraph', text: renderEmitBlock(b), wordIndexes };\n}\n\n/** The OCR-path core shared by extractOcr and analyze(..., {path:'ocr'}):\n * recognizes (or replays) words and runs the unchanged buildPageOCR/emitPage pipeline. Word IDENTITY (object reference), not value, carries indices through into the emitted blocks — see `geometry.ts`'s OcrLine.words. */\nexport async function buildOcrAnalysisPages(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions, warn: (m: string) => void): Promise<{ pages: AnalysisPage[]; words: OcrWordInput[] }> {\n const tuning: Tuning = { ...DEFAULT_TUNING, ...opts.tuning };\n const validated = validateOcrAnalysisInput(input);\n\n let words: OcrWordInput[];\n let first: number;\n let last: number;\n if ('words' in validated) {\n // Replay: page range from --pages if given, else every page up to the highest one the dump mentions.\n words = validated.words;\n first = opts.pages?.first ?? 1;\n last = opts.pages?.last ?? opts.pages?.first ?? Math.max(1, ...words.map((w) => w.page));\n } else {\n const { recognizePdf } = await import('./engines/tesseract.ts');\n const totalPages = await pageCount(validated.pdfPath);\n const rawFirst = opts.pages?.first ?? 1;\n const rawLast = opts.pages?.last ?? (opts.pages ? rawFirst : totalPages);\n first = Math.min(Math.max(1, rawFirst), Math.max(1, totalPages));\n last = Math.min(Math.max(first, rawLast), totalPages);\n const result = await recognizePdf(validated.pdfPath, first, last, {\n dpi: opts.dpi,\n onProgress: opts.onProgress,\n onWarning: warn,\n });\n words = result.words;\n }\n\n opts.onWords?.(words);\n\n // Stable per-page index, assigned in recognition/replay order — this IS\n // the page's flat `words` list order; `wordIndex` recovers it later since geometry.ts never clones a Word (object identity survives row-building).\n const byPage = new Map<number, OcrWordInput[]>();\n const wordIndex = new Map<Word, number>();\n for (const w of words) {\n const list = byPage.get(w.page);\n if (list) {\n wordIndex.set(w, list.length);\n list.push(w);\n } else {\n wordIndex.set(w, 0);\n byPage.set(w.page, [w]);\n }\n }\n\n const pageOcrs = new Map<number, PageOCR>();\n for (let pn = first; pn <= last; pn++) pageOcrs.set(pn, buildPageOCR(byPage.get(pn) ?? [], tuning));\n const { levelOf } = headingLevels([...pageOcrs.values()], tuning);\n\n const pages: AnalysisPage[] = [];\n for (let pn = first; pn <= last; pn++) {\n const p = pageOcrs.get(pn) as PageOCR;\n // An in-range page with no recognized words stays visible (marker +\n // warning), never silently absent — same rule as extractOcr.\n if (!byPage.has(pn)) warn(`p${pn}: no recognized words, page emitted with no OCR text`);\n\n const blocks: AnalysisBlock[] = emitPage(p, levelOf, tuning).map((b) => toAnalysisBlock(b, wordIndex));\n // Decorative fragments always render as one visible \"> [floats]\" aside\n // per page (matching the one printed line) — see geometry.ts's PageOCR.floats.\n if (p.floats.length) {\n blocks.push({\n type: 'float',\n text: `> [floats] ${p.floats.map((f) => f.text).join(' · ')}`,\n wordIndexes: p.floats.flatMap((f) => f.words).map((w) => wordIndex.get(w) as number),\n });\n }\n\n pages.push({\n page: pn,\n words: (byPage.get(pn) ?? []).map(toAnalysisWord),\n blocks,\n });\n }\n\n return { pages, words };\n}\n\nasync function analyzeOcr(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const { pages, words } = await buildOcrAnalysisPages(input, opts, warn);\n const md = renderPagesToMarkdown(pages, { forcePageMarkers: true, pageMarkers: true });\n const report = buildOcrReport({ md, fallback: opts.fallback, words });\n return { outputVersion: OUTPUT_VERSION, report, pages };\n}\n\n// TEXT path: deliberately NOT routed through the OCR shared-core pattern —\n// buildMarkdown's reflow/hyphen-rejoin/list rules don't fit the 4-type Analysis block union, so this is an independent, intentionally coarser reconstruction (one word/block per visual LINE) — honest, not byte-identical to extractText (see AnalysisPage, src/types.ts).\n\n// Converts a text-path Line's page-point geometry (src/lines.ts) into the\n// same normalized box contract the OCR path uses (see AnalysisPage.words) — only the coordinate SYSTEM changes; `box.y` anchors on the line's baseline, `box.w` stays 0.\nfunction textLineBox(l: Line, dims: { width: number; height: number }): AnalysisWord['box'] {\n const { width, height } = dims;\n return {\n x: width > 0 ? l.x / width : 0,\n y: height > 0 ? (height - l.y) / height : 0,\n w: 0,\n h: height > 0 ? l.h / height : 0,\n };\n}\n\nasync function analyzeText(pdfPath: string, opts: ExtractTextOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const range = opts.pages ? { first: opts.pages.first, last: opts.pages.last ?? opts.pages.first } : {};\n const { numPages, pages, heightChars } = await collect(pdfPath, range);\n const pageDims = new Map(pages.map((p) => [p.page, { width: p.width, height: p.height }]));\n const pageLines: PageLines[] = pages.map((p) => ({ page: p.page, lines: toLines(p) }));\n const pageMarkers = opts.pageMarkers ?? false;\n const { md, stats, bodyH, headingSizes } = buildMarkdown(pageLines, heightChars, { pageMarkers });\n const statsMd = pageMarkers ? md : buildMarkdown(pageLines, heightChars, { pageMarkers: true }).md;\n\n const hybridPages = pages.filter((p) => p.largeImage).map((p) => p.page);\n for (const n of hybridPages) {\n warn(`p${n}: text layer used but page carries large image(s); if it has baked-in text this output won't have it — compare (don't blindly replace) against --pages ${n} --ocr, which can itself introduce errors`);\n }\n\n // Report is measured from the REAL markdown above — accurate regardless of\n // the coarser block/word reconstruction below.\n const report = buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages });\n\n // headingSizes is offset-independent — reused directly, then re-leveled\n // here with offset 0 regardless of `opts.pageMarkers` (see AnalysisPage).\n const levelOf = new Map(headingSizes.slice(0, 6).map((h, i) => [h, Math.min(6, i + 1)]));\n const analysisPages: AnalysisPage[] = pageLines.map(({ page, lines }) => {\n const dims = pageDims.get(page) as { width: number; height: number };\n const words: AnalysisWord[] = lines.map((l) => ({ text: l.text, box: textLineBox(l, dims) }));\n const blocks: AnalysisBlock[] = lines.map((l, i) => {\n const level = levelOf.get(l.h);\n return level !== undefined ? { type: 'heading' as const, text: l.text, level, wordIndexes: [i] } : { type: 'paragraph' as const, text: l.text, wordIndexes: [i] };\n });\n return { page, words, blocks };\n });\n\n return { outputVersion: OUTPUT_VERSION, report, pages: analysisPages };\n}\n\n/**\n * Analyze a PDF (or replay an already-recognized OCR word dump) into\n * `Analysis`: plain, JSON-serializable per-page `words`/`blocks` plus the same QA `report` the other entry points return. Render with toMarkdown()/toText(), or hand-edit/splice it (no merge API — see toMarkdown's doc comment).\n *\n * @param input a bare pdf path, or `{ words }` to replay a dump (always analyzed as OCR) — unlike extractOcr, never `{ pdfPath }`\n * @param opts see {@link AnalyzeOptions}; for a pdf path, `opts.path` picks 'text' (default) or 'ocr' — analyze() makes no auto-fallback decision (that's pdfToMarkdown's job)\n */\nexport async function analyze(input: string | { words: OcrWordInput[] }, opts: AnalyzeOptions = {}): Promise<Analysis> {\n validatePages(opts.pages);\n if (typeof input !== 'string') return analyzeOcr({ words: validateWordsInput(input) }, opts);\n if (opts.path === 'ocr') return analyzeOcr({ pdfPath: input }, opts);\n return analyzeText(input, opts);\n}\n"],"names":["analyze","buildOcrAnalysisPages","toAnalysisWord","w","box","x","y","h","confidence","undefined","text","toAnalysisBlock","b","wordIndex","wordIndexes","words","map","get","kind","type","level","renderEmitBlock","input","opts","warn","byPage","tuning","validated","first","last","Math","recognizePdf","totalPages","rawFirst","rawLast","result","list","pageOcrs","pn","levelOf","pages","p","blocks","DEFAULT_TUNING","validateOcrAnalysisInput","max","page","pageCount","pdfPath","min","dpi","onProgress","onWarning","onWords","Map","set","length","push","buildPageOCR","headingLevels","values","has","emitPage","floats","f","join","flatMap","analyzeOcr","md","report","m","dictAvailable","dictUnavailableWarning","renderPagesToMarkdown","forcePageMarkers","pageMarkers","buildOcrReport","fallback","outputVersion","OUTPUT_VERSION","textLineBox","l","dims","width","height","analyzeText","range","numPages","heightChars","pageDims","pageLines","buildMarkdown","stats","bodyH","headingSizes","statsMd","hybridPages","n","analysisPages","collect","lines","toLines","filter","largeImage","buildReport","slice","i","validatePages","validateWordsInput","path"],"mappings":"AAAA,2EAA2E;AAC3E,kPAAkP;;;;;;;;;;;;QA4L5NA;eAAAA;;QA/IAC;eAAAA;;;yBA5Ca;sBACmB;sBAEZ;0BAKkB;uBACpC;0BACM;gCACQ;wBACsB;0BAEgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAc5E,SAASC,eAAeC,CAAe;IACrC,IAAMC,MAAM;QAAEC,GAAGF,EAAEE,CAAC;QAAEC,GAAGH,EAAEG,CAAC;QAAEH,GAAGA,EAAEA,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C,SAACiE;mCAAO;gCAAEvE,MAAMuE,EAAEvE,IAAI;gCAAEN,KAAK4E,YAAYC,GAAGC;4BAAM;;wBAC1F,IAAMxC,SAA0B0D,MAAMpF,GAAG,CAAC,SAACiE,GAAGyB;4BAC5C,IAAMtF,QAAQmB,QAAQtB,GAAG,CAACgE,EAAE1E,CAAC;4BAC7B,OAAOa,UAAUX,YAAY;gCAAEU,MAAM;gCAAoBT,MAAMuE,EAAEvE,IAAI;gCAAEU,OAAAA;gCAAON,aAAa;oCAAC4F;iCAAE;4BAAC,IAAI;gCAAEvF,MAAM;gCAAsBT,MAAMuE,EAAEvE,IAAI;gCAAEI,aAAa;oCAAC4F;iCAAE;4BAAC;wBAClK;wBACA,OAAO;4BAAE5D,MAAAA;4BAAM/B,OAAAA;4BAAO2B,QAAAA;wBAAO;oBAC/B;oBAEA;;wBAAO;4BAAEoC,eAAeC,wBAAc;4BAAEV,QAAAA;4BAAQ7B,OAAO0D;wBAAc;;;;IACvE;;AASO,SAAelG;wCAAQsB,KAAyC;YAAEC;;;YAAAA,OAAAA,oEAAuB,CAAC;YAC/FoF,IAAAA,yBAAa,EAACpF,KAAKiB,KAAK;YACxB,IAAI,OAAOlB,UAAU,UAAU;;gBAAO6C,WAAW;oBAAEpD,OAAO6F,IAAAA,8BAAkB,EAACtF;gBAAO,GAAGC;;YACvF,IAAIA,KAAKsF,IAAI,KAAK,OAAO;;gBAAO1C,WAAW;oBAAEnB,SAAS1B;gBAAM,GAAGC;;YAC/D;;gBAAO8D,YAAY/D,OAAOC;;;IAC5B"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/analyze.ts"],"sourcesContent":["// analyze() plus the OCR-path core (buildOcrAnalysisPages) that extractOcr\n// shares with it — same buildPageOCR -> emitPage -> renderPagesToMarkdown pipeline, so OCR-path markdown is byte-identical by construction, not two implementations kept in sync by hand. The TEXT path is NOT shared this way (see analyzeText).\nimport { collect, pageCount } from './collect.ts';\nimport { dictAvailable, dictUnavailableWarning } from './dict.ts';\nimport type { EmitBlock } from './emit.ts';\nimport { emitPage, renderEmitBlock } from './emit.ts';\n// Type-only: erased at compile time, so this does NOT create a runtime\n// circular dependency even though src/extract.ts imports (value-level) from this module.\nimport type { ExtractOcrOptions, ExtractTextOptions, OcrWordInput } from './extract.ts';\nimport type { PageOCR, Tuning, Word } from './geometry.ts';\nimport { buildPageOCR, DEFAULT_TUNING, headingLevels } from './geometry.ts';\nimport { toLines } from './lines.ts';\nimport { buildMarkdown } from './markdown.ts';\nimport { renderPagesToMarkdown } from './render-analysis.ts';\nimport { buildOcrReport, buildReport, OUTPUT_VERSION } from './report.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage, AnalysisWord, Line, PageLines } from './types.ts';\nimport { validateOcrAnalysisInput, validatePages, validateWordsInput } from './validate.ts';\n\n/** analyze(pdf) with the default/'text' path — OCR-only fields don't exist\n * on this branch, so passing e.g. `tuning` without `path: 'ocr'` is a compile error. */\nexport type AnalyzeTextOptions = ExtractTextOptions & { path?: 'text' };\n\n/** analyze(pdf, {path:'ocr'}) — same fields as {@link ExtractOcrOptions},\n * unlocked only once `path: 'ocr'` is set. */\nexport type AnalyzeOcrOptions = ExtractOcrOptions & { path: 'ocr' };\n\n/** Options for {@link analyze}: which fields type-check depends on `path`\n * (ignored, forced 'ocr', when `input` is a `{ words }` replay). */\nexport type AnalyzeOptions = AnalyzeTextOptions | AnalyzeOcrOptions;\n\nfunction toAnalysisWord(w: OcrWordInput): AnalysisWord {\n const box = { x: w.x, y: w.y, w: w.w, h: w.h };\n return w.confidence === undefined ? { text: w.text, box } : { text: w.text, box, confidence: w.confidence };\n}\n\n// EmitBlock -> AnalysisBlock: collapses emit.ts's 'quote' kind (a pull-quote)\n// into Analysis's 'paragraph' type, `text` keeping its literal '> ' prefix — see AnalysisBlock's doc comment (src/types.ts) for why.\nfunction toAnalysisBlock(b: EmitBlock, wordIndex: Map<Word, number>): AnalysisBlock {\n const wordIndexes = b.words.map((w) => wordIndex.get(w) as number);\n if (b.kind === 'heading') return { type: 'heading', text: b.text, level: b.level, wordIndexes };\n if (b.kind === 'review') return { type: 'review', text: renderEmitBlock(b), wordIndexes };\n return { type: 'paragraph', text: renderEmitBlock(b), wordIndexes };\n}\n\n/** The OCR-path core shared by extractOcr and analyze(..., {path:'ocr'}):\n * recognizes (or replays) words and runs the unchanged buildPageOCR/emitPage pipeline. Word IDENTITY (object reference), not value, carries indices through into the emitted blocks — see `geometry.ts`'s OcrLine.words. */\nexport async function buildOcrAnalysisPages(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions, warn: (m: string) => void): Promise<{ pages: AnalysisPage[]; words: OcrWordInput[] }> {\n const tuning: Tuning = { ...DEFAULT_TUNING, ...opts.tuning };\n const validated = validateOcrAnalysisInput(input);\n\n let words: OcrWordInput[];\n let first: number;\n let last: number;\n if ('words' in validated) {\n // Replay: page range from --pages if given, else every page up to the highest one the dump mentions.\n words = validated.words;\n first = opts.pages?.first ?? 1;\n last = opts.pages?.last ?? opts.pages?.first ?? Math.max(1, ...words.map((w) => w.page));\n } else {\n const { recognizePdf } = await import('./engines/tesseract.ts');\n const totalPages = await pageCount(validated.pdfPath);\n const rawFirst = opts.pages?.first ?? 1;\n const rawLast = opts.pages?.last ?? (opts.pages ? rawFirst : totalPages);\n first = Math.min(Math.max(1, rawFirst), Math.max(1, totalPages));\n last = Math.min(Math.max(first, rawLast), totalPages);\n const result = await recognizePdf(validated.pdfPath, first, last, {\n dpi: opts.dpi,\n onProgress: opts.onProgress,\n onWarning: warn,\n });\n words = result.words;\n }\n\n opts.onWords?.(words);\n\n // Stable per-page index, assigned in recognition/replay order — this IS\n // the page's flat `words` list order; `wordIndex` recovers it later since geometry.ts never clones a Word (object identity survives row-building).\n const byPage = new Map<number, OcrWordInput[]>();\n const wordIndex = new Map<Word, number>();\n for (const w of words) {\n const list = byPage.get(w.page);\n if (list) {\n wordIndex.set(w, list.length);\n list.push(w);\n } else {\n wordIndex.set(w, 0);\n byPage.set(w.page, [w]);\n }\n }\n\n const pageOcrs = new Map<number, PageOCR>();\n for (let pn = first; pn <= last; pn++) pageOcrs.set(pn, buildPageOCR(byPage.get(pn) ?? [], tuning));\n const { levelOf } = headingLevels([...pageOcrs.values()], tuning);\n\n const pages: AnalysisPage[] = [];\n for (let pn = first; pn <= last; pn++) {\n const p = pageOcrs.get(pn) as PageOCR;\n // An in-range page with no recognized words stays visible (marker +\n // warning), never silently absent — same rule as extractOcr.\n if (!byPage.has(pn)) warn(`p${pn}: no recognized words, page emitted with no OCR text`);\n\n const blocks: AnalysisBlock[] = emitPage(p, levelOf, tuning).map((b) => toAnalysisBlock(b, wordIndex));\n // Decorative fragments always render as one visible \"> [floats]\" aside\n // per page (matching the one printed line) — see geometry.ts's PageOCR.floats.\n if (p.floats.length) {\n blocks.push({\n type: 'float',\n text: `> [floats] ${p.floats.map((f) => f.text).join(' · ')}`,\n wordIndexes: p.floats.flatMap((f) => f.words).map((w) => wordIndex.get(w) as number),\n });\n }\n\n pages.push({\n page: pn,\n words: (byPage.get(pn) ?? []).map(toAnalysisWord),\n blocks,\n });\n }\n\n return { pages, words };\n}\n\nasync function analyzeOcr(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const { pages, words } = await buildOcrAnalysisPages(input, opts, warn);\n const md = renderPagesToMarkdown(pages, { forcePageMarkers: true, pageMarkers: true });\n const report = buildOcrReport({ md, fallback: opts.fallback, words });\n return { outputVersion: OUTPUT_VERSION, report, pages };\n}\n\n// TEXT path: deliberately NOT routed through the OCR shared-core pattern —\n// buildMarkdown's reflow/hyphen-rejoin/list rules don't fit the 4-type Analysis block union, so this is an independent, intentionally coarser reconstruction (one word/block per visual LINE) — honest, not byte-identical to extractText (see AnalysisPage, src/types.ts).\n\n// Converts a text-path Line's page-point geometry (src/lines.ts) into the\n// same normalized box contract the OCR path uses (see AnalysisPage.words) — only the coordinate SYSTEM changes; `box.y` anchors on the line's baseline, `box.w` stays 0.\nfunction textLineBox(l: Line, dims: { width: number; height: number }): AnalysisWord['box'] {\n const { width, height } = dims;\n return {\n x: width > 0 ? l.x / width : 0,\n y: height > 0 ? (height - l.y) / height : 0,\n w: 0,\n h: height > 0 ? l.h / height : 0,\n };\n}\n\nasync function analyzeText(pdfPath: string, opts: ExtractTextOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const range = opts.pages ? { first: opts.pages.first, last: opts.pages.last ?? opts.pages.first } : {};\n const { numPages, pages, heightChars } = await collect(pdfPath, range);\n const pageDims = new Map(pages.map((p) => [p.page, { width: p.width, height: p.height }]));\n const pageLines: PageLines[] = pages.map((p) => ({ page: p.page, lines: toLines(p) }));\n const pageMarkers = opts.pageMarkers ?? false;\n const { md, stats, bodyH, headingSizes } = buildMarkdown(pageLines, heightChars, { pageMarkers });\n const statsMd = pageMarkers ? md : buildMarkdown(pageLines, heightChars, { pageMarkers: true }).md;\n\n const hybridPages = pages.filter((p) => p.largeImage).map((p) => p.page);\n for (const n of hybridPages) {\n warn(`p${n}: text layer used but page carries large image(s); if it has baked-in text this output won't have it — compare (don't blindly replace) against --pages ${n} --ocr, which can itself introduce errors`);\n }\n\n // Report is measured from the REAL markdown above — accurate regardless of\n // the coarser block/word reconstruction below.\n const report = buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages });\n\n // headingSizes is offset-independent — reused directly, then re-leveled\n // here with offset 0 regardless of `opts.pageMarkers` (see AnalysisPage).\n const levelOf = new Map(headingSizes.slice(0, 6).map((h, i) => [h, Math.min(6, i + 1)]));\n const analysisPages: AnalysisPage[] = pageLines.map(({ page, lines }) => {\n const dims = pageDims.get(page) as { width: number; height: number };\n const words: AnalysisWord[] = lines.map((l) => ({ text: l.text, box: textLineBox(l, dims) }));\n const blocks: AnalysisBlock[] = lines.map((l, i) => {\n const level = levelOf.get(l.h);\n return level !== undefined ? { type: 'heading' as const, text: l.text, level, wordIndexes: [i] } : { type: 'paragraph' as const, text: l.text, wordIndexes: [i] };\n });\n return { page, words, blocks };\n });\n\n return { outputVersion: OUTPUT_VERSION, report, pages: analysisPages };\n}\n\n/**\n * Analyze a PDF (or replay an already-recognized OCR word dump) into\n * `Analysis`: plain, JSON-serializable per-page `words`/`blocks` plus the same QA `report` the other entry points return. Render with toMarkdown()/toText(), or hand-edit/splice it (no merge API — see toMarkdown's doc comment).\n *\n * @param input a bare pdf path, or `{ words }` to replay a dump (always analyzed as OCR) — unlike extractOcr, never `{ pdfPath }`\n * @param opts see {@link AnalyzeOptions}; for a pdf path, `opts.path` picks 'text' (default) or 'ocr' — analyze() makes no auto-fallback decision (that's pdfToMarkdown's job)\n */\nexport async function analyze(input: string | { words: OcrWordInput[] }, opts: AnalyzeOptions = {}): Promise<Analysis> {\n validatePages(opts.pages);\n if (typeof input !== 'string') return analyzeOcr({ words: validateWordsInput(input) }, opts);\n if (opts.path === 'ocr') return analyzeOcr({ pdfPath: input }, opts);\n return analyzeText(input, opts);\n}\n"],"names":["analyze","buildOcrAnalysisPages","toAnalysisWord","w","box","x","y","h","confidence","undefined","text","toAnalysisBlock","b","wordIndex","wordIndexes","words","map","get","kind","type","level","renderEmitBlock","input","opts","warn","byPage","tuning","validated","first","last","Math","recognizePdf","totalPages","rawFirst","rawLast","result","list","pageOcrs","pn","levelOf","pages","p","blocks","DEFAULT_TUNING","validateOcrAnalysisInput","max","page","pageCount","pdfPath","min","dpi","onProgress","onWarning","onWords","Map","set","length","push","buildPageOCR","headingLevels","values","has","emitPage","floats","f","join","flatMap","analyzeOcr","md","report","m","dictAvailable","dictUnavailableWarning","renderPagesToMarkdown","forcePageMarkers","pageMarkers","buildOcrReport","fallback","outputVersion","OUTPUT_VERSION","textLineBox","l","dims","width","height","analyzeText","range","numPages","heightChars","pageDims","pageLines","buildMarkdown","stats","bodyH","headingSizes","statsMd","hybridPages","n","analysisPages","collect","lines","toLines","filter","largeImage","buildReport","slice","i","validatePages","validateWordsInput","path"],"mappings":"AAAA,2EAA2E;AAC3E,kPAAkP;;;;;;;;;;;;QA4L5NA;eAAAA;;QA/IAC;eAAAA;;;yBA5Ca;sBACmB;sBAEZ;0BAKkB;uBACpC;0BACM;gCACQ;wBACsB;0BAEgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAc5E,SAASC,eAAeC,CAAe;IACrC,IAAMC,MAAM;QAAEC,GAAGF,EAAEE,CAAC;QAAEC,GAAGH,EAAEG,CAAC;QAAEH,GAAGA,EAAEA,CAAC;QAAEI,GAAGJ,EAAEI,CAAC;IAAC;IAC7C,OAAOJ,EAAEK,UAAU,KAAKC,YAAY;QAAEC,MAAMP,EAAEO,IAAI;QAAEN,KAAAA;IAAI,IAAI;QAAEM,MAAMP,EAAEO,IAAI;QAAEN,KAAAA;QAAKI,YAAYL,EAAEK,UAAU;IAAC;AAC5G;AAEA,8EAA8E;AAC9E,qIAAqI;AACrI,SAASG,gBAAgBC,CAAY,EAAEC,SAA4B;IACjE,IAAMC,cAAcF,EAAEG,KAAK,CAACC,GAAG,CAAC,SAACb;eAAMU,UAAUI,GAAG,CAACd;;IACrD,IAAIS,EAAEM,IAAI,KAAK,WAAW,OAAO;QAAEC,MAAM;QAAWT,MAAME,EAAEF,IAAI;QAAEU,OAAOR,EAAEQ,KAAK;QAAEN,aAAAA;IAAY;IAC9F,IAAIF,EAAEM,IAAI,KAAK,UAAU,OAAO;QAAEC,MAAM;QAAUT,MAAMW,IAAAA,uBAAe,EAACT;QAAIE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;AASO,SAAelG;wCAAQsB,KAAyC;YAAEC;;;YAAAA,OAAAA,oEAAuB,CAAC;YAC/FoF,IAAAA,yBAAa,EAACpF,KAAKiB,KAAK;YACxB,IAAI,OAAOlB,UAAU,UAAU;;gBAAO6C,WAAW;oBAAEpD,OAAO6F,IAAAA,8BAAkB,EAACtF;gBAAO,GAAGC;;YACvF,IAAIA,KAAKsF,IAAI,KAAK,OAAO;;gBAAO1C,WAAW;oBAAEnB,SAAS1B;gBAAM,GAAGC;;YAC/D;;gBAAO8D,YAAY/D,OAAOC;;;IAC5B"}
|
package/dist/cjs/audit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/audit.ts"],"sourcesContent":["// audit.ts — the severity-1 audit instrument (README's \"Design contract\"),\n// shipped as part of the product, not just a path into the source tree.\n//\n// Every recognized word (a --debug-words dump, or an Analysis page's\n// `words`) must appear in its page's markdown — normalized, compared as a per-page multiset, with substring repair for hyphen joins.\n//\n// NOTE: no producer guarantees JSON key order in a --debug-words dump —\n// parse, never grep.\nimport { readFileSync } from 'node:fs';\nimport { bodyByPage } from './page-marker.ts';\n\nfunction norm(s: string): string {\n return s\n .normalize('NFKD')\n .replace(/\\p{M}/gu, '')\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '');\n}\n\nfunction counter(items: Iterable<string>): Map<string, number> {\n const m = new Map<string, number>();\n for (const item of items) m.set(item, (m.get(item) ?? 0) + 1);\n return m;\n}\n\n/** auditWords()'s result — the severity-1 no-silent-loss check. */\nexport interface AuditResult {\n /** JSON lines successfully parsed from the word dump */\n parsed: number;\n /** lines in the dump that were not parseable JSON, skipped rather than\n * failing the whole audit (same policy `--words-json` itself uses) */\n nonJsonSkipped: number;\n /** distinct page numbers present in the dump */\n pages: number;\n /** total recognized words across all pages in the dump */\n words: number;\n /** words present in the dump but not found verbatim on their page, BEFORE\n * hyphen-join/split repair is applied; always `>= missing` */\n strictDeficits: number;\n /** words genuinely absent from the markdown after repair-checking; `0` is\n * the only passing value (`pdf-to-md audit` exits 1 otherwise) */\n missing: number;\n /** per-page detail for every page with at least one missing word (capped\n * sample of the missing tokens per page) */\n perPage: { page: number; missing: string[] }[];\n /** the one-line `parsed=… pages=… words=… strict_deficits=… MISSING=…`\n * summary, also the last entry of `lines` */\n summaryLine: string;\n /** every line `pdf-to-md audit` prints, in order: one per page with\n * missing words, then `summaryLine` */\n lines: string[];\n}\n\n/**\n * Audit a --debug-words dump against a markdown file: every recognized word\n * must land somewhere in its page's markdown. `result.missing === 0` is the pass/fail signal.\n *\n * @param wordsPath path to a --debug-words JSON-lines dump (`{page, text, ...}` per line)\n * @param mdPath path to the markdown file to check the dump against\n */\nexport function auditWords(wordsPath: string, mdPath: string): AuditResult {\n const rec = new Map<number, string[]>();\n let parsed = 0;\n let skipped = 0;\n\n const wordsRaw = readFileSync(wordsPath, 'utf8');\n // A trailing \"\\n\" at EOF must not yield a spurious final empty line; a\n // genuine blank line mid-file does count, as skipped.\n const rawLines = wordsRaw.split('\\n');\n if (rawLines.length > 0 && rawLines[rawLines.length - 1] === '') rawLines.pop();\n for (let line of rawLines) {\n line = line.trim();\n if (!line.startsWith('{')) {\n skipped++;\n continue;\n }\n let o: { page: number; text: string };\n try {\n o = JSON.parse(line);\n } catch {\n skipped++;\n continue;\n }\n parsed++;\n const t = norm(o.text);\n if (t) {\n const arr = rec.get(o.page);\n if (arr) arr.push(t);\n else rec.set(o.page, [t]);\n }\n }\n\n const md = readFileSync(mdPath, 'utf8');\n const out = bodyByPage(md);\n\n const lines: string[] = [];\n let total = 0;\n let strict = 0;\n const perPage: { page: number; missing: string[] }[] = [];\n const pages = [...rec.keys()].sort((a, b) => a - b);\n\n for (const page of pages) {\n const toks = (out.get(page)?.match(/\\S+/g) ?? []).map(norm).filter((t) => t.length > 0);\n const ms = counter(toks);\n const joined = toks.join('');\n const missing: string[] = [];\n for (const [tok, n] of counter(rec.get(page) ?? [])) {\n const d = n - (ms.get(tok) ?? 0);\n if (d <= 0) continue;\n strict += d;\n if (joined.includes(tok)) continue; // hyphen-join / split repair\n for (let i = 0; i < d; i++) missing.push(tok);\n }\n if (missing.length > 0) {\n total += missing.length;\n perPage.push({ page, missing });\n lines.push(`p${page}: MISSING ${missing.length}: ${pyRepr(missing.slice(0, 12))}`);\n }\n }\n\n const words = pages.reduce((sum, p) => sum + (rec.get(p)?.length ?? 0), 0);\n const summaryLine = `parsed=${parsed} non-json-skipped=${skipped} pages=${rec.size} words=${words} strict_deficits=${strict} MISSING=${total}`;\n lines.push(summaryLine);\n\n return {\n parsed,\n nonJsonSkipped: skipped,\n pages: rec.size,\n words,\n strictDeficits: strict,\n missing: total,\n perPage,\n summaryLine,\n lines,\n };\n}\n\n// Renders a string list as ['a', 'b'] (single-quoted) to match frozen baseline comparisons byte-for-byte.\nfunction pyRepr(items: string[]): string {\n return `[${items.map((s) => `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`).join(', ')}]`;\n}\n"],"names":["auditWords","norm","s","normalize","replace","toLowerCase","counter","items","m","Map","item","set","get","wordsPath","mdPath","rec","parsed","skipped","wordsRaw","readFileSync","rawLines","split","length","pop","line","trim","startsWith","o","JSON","parse","t","text","arr","page","push","md","out","bodyByPage","lines","total","strict","perPage","pages","keys","sort","a","b","toks","match","map","filter","ms","joined","join","missing","tok","n","d","includes","i","pyRepr","slice","words","reduce","sum","p","summaryLine","size","nonJsonSkipped","strictDeficits"],"mappings":"AAAA,2EAA2E;AAC3E,wEAAwE;AACxE,EAAE;AACF,qEAAqE;AACrE,qIAAqI;AACrI,EAAE;AACF,wEAAwE;AACxE,qBAAqB;;;;;+BAqDLA;;;eAAAA;;;sBApDa;4BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3B,SAASC,KAAKC,CAAS;IACrB,OA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["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/audit.ts"],"sourcesContent":["// audit command — the severity-1 audit instrument (README's \"Design\n// contract\") as a first-class subcommand. Thin wrapper over src/audit.ts's auditWords (the library returns data, only the CLI prints and exits).\nimport type { Command } from './types.ts';\n\nconst USAGE = 'usage: pdf-to-md audit <words.jsonl> <file.md>';\n\nconst audit: Command = async (ctx) => {\n if (ctx.rest.includes('-h') || ctx.rest.includes('--help')) {\n console.log(USAGE);\n return;\n }\n const [wordsPath, mdPath] = ctx.rest;\n if (!wordsPath || !mdPath) ctx.usageError(USAGE);\n\n // Imported here, not at module top, same lazy-load rule as every other\n // command — `pdf-to-md audit` should never pay for what the other commands need.\n const { auditWords } = await import('../audit.ts');\n const result = auditWords(wordsPath, mdPath);\n for (const line of result.lines) console.log(line);\n\n // MISSING>0 is the severity-1 fail signal: a recognized word this markdown\n // lost. Exit 1 so the subcommand is usable as a CI gate; strict_deficits from hyphen-join repairs are reported but not failures.\n if (result.missing > 0) process.exitCode = 1;\n};\n\nexport default audit;\n"],"names":["USAGE","audit","ctx","wordsPath","mdPath","auditWords","result","line","rest","includes","console","log","usageError","lines","missing","process","exitCode"],"mappings":"AAAA,oEAAoE;AACpE,iJAAiJ;;;;;+BAwBjJ;;;eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AArBA,IAAMA,QAAQ;AAEd,IAAMC,QAAiB,eAAOC;;YAKAA,WAArBC,WAAWC,QAKVC,YACFC,QACD,2BAAA,mBAAA,gBAAA,WAAA,OAAMC;;;;oBAXX,IAAIL,IAAIM,IAAI,CAACC,QAAQ,CAAC,SAASP,IAAIM,IAAI,CAACC,QAAQ,CAAC,WAAW;wBAC1DC,QAAQC,GAAG,CAACX;wBACZ;;;oBACF;oBAC4BE,6BAAAA,IAAIM,IAAI,MAA7BL,YAAqBD,cAAVE,SAAUF;oBAC5B,IAAI,CAACC,aAAa,CAACC,QAAQF,IAAIU,UAAU,CAACZ;oBAInB;;wBAAM;2EAAA,QAAO;;;;oBAA5BK,aAAe,cAAfA;oBACFC,SAASD,WAAWF,WAAWC;oBAChC,kCAAA,2BAAA;;wBAAL,IAAK,YAAcE,OAAOO,KAAK,uBAA1B,6BAAA,QAAA,yBAAA;4BAAMN,OAAN;4BAA4BG,QAAQC,GAAG,CAACJ;;;wBAAxC;wBAAA;;;iCAAA,6BAAA;gCAAA;;;gCAAA;sCAAA;;;;oBAEL,2EAA2E;oBAC3E,iIAAiI;oBACjI,IAAID,OAAOQ,OAAO,GAAG,GAAGC,QAAQC,QAAQ,GAAG;;;;;;IAC7C;;IAEA,WAAef"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/cli/extract.ts"],"sourcesContent":["// extract command — parse this command's flags, call src/extract.ts, print\n// and write the result. No business logic here — the library returns data and throws; only the CLI prints and exits.\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport type { OcrWordInput } from '../extract.ts';\nimport type { Tuning } from '../geometry.ts';\nimport type { Analysis, Report } from '../types.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE =\n 'usage: pdf-to-md [extract] <file.pdf> [out.md] [--json] [--page-markers] [--ocr] [--no-ocr] ' +\n '[--pages N[-M]] [--stdout] [--words-json=FILE] [--debug-words=FILE] ' +\n '[--format md|txt|raw (default md; raw = Analysis JSON incl. the report; txt = reading-order plain text)] ' +\n '[--dpi=N (OCR render resolution, default 288; raise for tiny print or chart/label pages, ' +\n '>~400 measured worse on ordinary prose pages)] ' +\n '[--float-max-words=N] [--float-max-width=F] [--float-margin=F] [--para-gap=F] [--heading-scale=F] ' +\n '[--col-max-width=F] [--col-split=F] [--line-y-tol=F] [--line-height-ratio=F]';\n\nconst FORMATS = ['md', 'txt', 'raw'] as const;\ntype Format = (typeof FORMATS)[number];\n\n// A bad tuning-flag value (non-numeric, or <= 0 unless the flag allows zero) is a usage error, not a silent no-op.\nconst TUNING_FLAGS: {\n name: string;\n key: keyof Tuning;\n allowZero?: boolean;\n isInt?: boolean;\n}[] = [\n {\n name: 'float-max-words',\n key: 'floatMaxWords',\n allowZero: true,\n isInt: true,\n },\n { name: 'float-max-width', key: 'floatMaxWidth' },\n { name: 'float-margin', key: 'floatMargin' },\n { name: 'para-gap', key: 'paraGap' },\n { name: 'heading-scale', key: 'headingScale' },\n { name: 'col-max-width', key: 'colMaxWidth' },\n { name: 'col-split', key: 'colSplit' },\n { name: 'line-y-tol', key: 'lineYTol' },\n { name: 'line-height-ratio', key: 'lineHeightRatio' },\n];\n\nconst extract: Command = async (ctx) => {\n // --debug-words takes a required FILE value; a bare --debug-words is a\n // usage error, checked before parseArgs so it can't silently swallow the next token as its value.\n if (ctx.rest.includes('--debug-words')) {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n json: { type: 'boolean', default: false },\n 'page-markers': { type: 'boolean', default: false },\n ocr: { type: 'boolean', default: false },\n 'no-ocr': { type: 'boolean', default: false },\n stdout: { type: 'boolean', default: false },\n 'debug-words': { type: 'string' },\n help: { type: 'boolean', default: false, short: 'h' },\n pages: { type: 'string' },\n dpi: { type: 'string' },\n format: { type: 'string', default: 'md' },\n 'words-json': { type: 'string' },\n ...Object.fromEntries(TUNING_FLAGS.map((f) => [f.name, { type: 'string' as const }])),\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const values = parsed.values as Record<string, string | boolean | undefined>;\n const positionals = parsed.positionals;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [src, outArg] = positionals;\n const wordsPath = values['words-json'] as string | undefined;\n if (!src && !wordsPath) ctx.usageError(USAGE);\n\n const formatRaw = values.format as string;\n if (!(FORMATS as readonly string[]).includes(formatRaw)) {\n ctx.usageError(`${USAGE}\\n--format must be one of ${FORMATS.join('|')} (got ${JSON.stringify(formatRaw)})`);\n }\n const format = formatRaw as Format;\n\n // --pages: a malformed spec is a usage error; out-of-range page NUMBERS\n // clamp instead (collect.ts / the engine apply the same clamping policy).\n let pages: { first: number; last: number } | undefined;\n if (values.pages !== undefined) {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(values.pages as string);\n const first = m ? Number(m[1]) : Number.NaN;\n const last = m ? (m[2] !== undefined ? Number(m[2]) : first) : Number.NaN;\n if (!m || first < 1 || last < first) {\n ctx.usageError(`${USAGE}\\n--pages requires N or N-M, N >= 1, M >= N (got ${JSON.stringify(values.pages)})`);\n }\n pages = { first, last };\n }\n\n const tuning: Partial<Tuning> = {};\n for (const spec of TUNING_FLAGS) {\n const raw = values[spec.name] as string | undefined;\n if (raw === undefined) continue;\n const value = Number(raw);\n const ok = raw !== '' && Number.isFinite(value) && (spec.allowZero ? value >= 0 : value > 0);\n if (!ok) {\n ctx.usageError(`${USAGE}\\n--${spec.name} requires a ${spec.allowZero ? 'non-negative' : 'positive'} number (got ${JSON.stringify(raw)})`);\n }\n (tuning[spec.key] as number) = spec.isInt ? Math.trunc(value) : value;\n }\n\n // --dpi: page-render resolution, validated like the tuning flags. Default\n // 288 is the measured operating point; >~400 measured WORSE on ordinary pages — not a \"bigger is safer\" knob.\n let dpi: number | undefined;\n if (values.dpi !== undefined) {\n const raw = values.dpi as string;\n const value = Number(raw);\n if (raw === '' || !Number.isFinite(value) || value <= 0) {\n ctx.usageError(`${USAGE}\\n--dpi requires a positive number (got ${JSON.stringify(raw)})`);\n }\n dpi = value;\n }\n\n // In --words-json mode there may be no PDF positional; the words file\n // stands in for naming, extension stripped so the default dest can never overwrite the input. Default extension follows --format.\n const source = src ?? (wordsPath as string);\n const defaultExt = format === 'raw' ? 'json' : format === 'txt' ? 'txt' : 'md';\n const dest = outArg || `${source.replace(/\\.(pdf|jsonl)$/i, '')}.${defaultExt}`;\n\n const onWarning = (m: string) => console.error(m);\n const showProgress = process.stderr.isTTY;\n // onProgress carries per-page timing/count only; human-readable\n // diagnostics (e.g. the sparse-retry notice) arrive via onWarning instead, so they print regardless of TTY-ness.\n const onProgress = (e: { type: 'page'; page: number; words: number; ms: number }) => {\n if (showProgress) console.error(`p${e.page}: ${e.words} words, ${e.ms}ms`);\n };\n const debugWordsPath = values['debug-words'] as string | undefined;\n if (debugWordsPath !== undefined && debugWordsPath.trim() === '') {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n // The severity-1 audit instrument: every recognized word as clean JSON\n // lines to its own file. stderr stays a human channel (mixed prose), never a dump target — this file is guaranteed byte-for-byte parseable.\n const onWords = debugWordsPath\n ? (words: OcrWordInput[]) => {\n const lines = words.map((w) => {\n const entry: OcrWordInput = { page: w.page, text: w.text, x: w.x, y: w.y, w: w.w, h: w.h };\n if (w.confidence !== undefined) entry.confidence = w.confidence;\n return JSON.stringify(entry);\n });\n writeFileSync(debugWordsPath, lines.length ? `${lines.join('\\n')}\\n` : '');\n }\n : undefined;\n\n const common = { pages, onWarning };\n const ocrCommon = {\n ...common,\n tuning,\n dpi,\n onProgress,\n onWords,\n };\n\n let words: OcrWordInput[] | undefined;\n let skipped = 0;\n if (wordsPath !== undefined) {\n ({ words, skipped } = parseWordLines(readFileSync(wordsPath, 'utf8')));\n if (skipped > 0) console.error(`--words-json: skipped ${skipped} non-JSON line(s)`);\n }\n\n let content: string;\n let report: Report;\n if (format === 'md') {\n // Unchanged path: extractOcr/pdfToMarkdown directly, exactly as before\n // --format existed.\n const { extractOcr, pdfToMarkdown } = await import('../extract.ts');\n let markdown: string;\n if (words !== undefined) {\n ({ markdown, report } = await extractOcr({ words }, ocrCommon));\n } else {\n ({ markdown, report } = await pdfToMarkdown(src, {\n ...ocrCommon,\n ocr: values.ocr as boolean,\n noOcr: values['no-ocr'] as boolean,\n pageMarkers: values['page-markers'] as boolean,\n }));\n }\n content = markdown;\n } else {\n // raw/txt: both render from an Analysis — raw IS the Analysis as JSON;\n // txt is toText(analysis). Mirrors pdfToMarkdown's own auto-OCR fallback decision so a different --format doesn't silently pick a different path.\n const { analyze } = await import('../analyze.ts');\n const { toText } = await import('../render-analysis.ts');\n const { needsOcrFallback, ocrFallbackNotice } = await import('../extract.ts');\n let analysis: Analysis;\n if (words !== undefined) {\n analysis = await analyze({ words }, { ...ocrCommon, path: 'ocr' });\n } else if (values.ocr) {\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr' });\n } else {\n const text = await analyze(src, { ...common, path: 'text', pageMarkers: values['page-markers'] as boolean });\n if (needsOcrFallback(text.report.charsPerPage) && !values['no-ocr']) {\n onWarning(ocrFallbackNotice(text.report.charsPerPage));\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr', fallback: true });\n } else {\n analysis = text;\n }\n }\n report = analysis.report;\n content = format === 'raw' ? JSON.stringify(analysis, null, 1) : toText(analysis);\n }\n\n if (values.stdout) process.stdout.write(content);\n else writeFileSync(dest, content);\n\n // The library's Report stays clean of source/out; --json consumers keep\n // report.json files around and need to know which input produced each one, so the CLI (only) decorates the printed JSON with source/out here.\n if (values.json) console.log(JSON.stringify({ source, out: dest, ...report }, null, 1));\n else if (report.path === 'ocr') {\n console.error(`${path.basename(dest).padEnd(32)} OCR path heads=${report.headings}(junk ${report.junkHeadings}) ` + `paras=${report.paragraphs} callouts=${report.callouts} floats=${report.floats ?? 0} dangling=${report.danglingLong} (long) ` + `~${report.charsPerPage} chars/page`);\n } else {\n console.error(\n `${path.basename(dest).padEnd(32)} body=${report.bodyFontHeight}pt heads=${report.headings}(junk ${report.junkHeadings}) ` +\n `lists=${report.listItems} paras=${report.paragraphs} callouts=${report.callouts} pairs=${report.joinedPairs} ` +\n `~${report.charsPerPage} chars/page` +\n (report.sparse ? ' ⚠️ implausibly sparse — pages are likely images; re-run with --ocr' : '')\n );\n }\n};\n\n// Parse one word-dump JSON line per word — key order is not guaranteed, parse\n// never grep. Non-JSON lines are skipped with a count, not fatal (the auditor applies the same policy).\nfunction parseWordLines(raw: string): { words: OcrWordInput[]; skipped: number } {\n const words: OcrWordInput[] = [];\n let skipped = 0;\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n words.push(JSON.parse(line));\n } catch {\n skipped++;\n }\n }\n return { words, skipped };\n}\n\nexport default extract;\n"],"names":["USAGE","FORMATS","TUNING_FLAGS","name","key","allowZero","isInt","extract","ctx","parsed","values","positionals","src","outArg","wordsPath","formatRaw","format","pages","m","first","last","tuning","spec","raw","value","ok","dpi","source","defaultExt","dest","onWarning","showProgress","onProgress","debugWordsPath","onWords","common","ocrCommon","words","skipped","content","report","extractOcr","pdfToMarkdown","markdown","analyze","toText","needsOcrFallback","ocrFallbackNotice","analysis","text","rest","includes","usageError","parseArgs","args","options","json","type","default","ocr","stdout","help","short","Object","fromEntries","map","f","allowPositionals","err","message","console","log","JSON","join","stringify","undefined","exec","Number","NaN","isFinite","Math","trunc","replace","error","process","stderr","isTTY","e","page","ms","trim","lines","w","entry","x","y","h","confidence","writeFileSync","length","parseWordLines","readFileSync","noOcr","pageMarkers","path","charsPerPage","fallback","write","out","basename","padEnd","headings","junkHeadings","paragraphs","callouts","floats","danglingLong","bodyFontHeight","listItems","joinedPairs","sparse","split","line","push","parse"],"mappings":"AAAA,2EAA2E;AAC3E,qHAAqH;;;;;+BA6PrH;;;eAAA;;;sBA5P4C;+DAC3B;wBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;IACF;;AAEA,8EAA8E;AAC9E,wGAAwG;AACxG,SAASpB,eAAe7E,GAAW;IACjC,IAAMc,QAAwB,EAAE;IAChC,IAAIC,UAAU;QACT,kCAAA,2BAAA;;QAAL,QAAK,YAAcf,IAAIkG,KAAK,CAAC,0BAAxB,SAAA,6BAAA,QAAA,yBAAA,iCAA+B;YAA/B,IAAMC,OAAN;YACH,IAAI,CAACA,KAAKhC,IAAI,IAAI;YAClB,IAAI;gBACFrD,MAAMsF,IAAI,CAACnD,KAAKoD,KAAK,CAACF;YACxB,EAAE,eAAM;gBACNpF;YACF;QACF;;QAPK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAQL,OAAO;QAAED,OAAAA;QAAOC,SAAAA;IAAQ;AAC1B;IAEA,WAAe/B"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/extract.ts"],"sourcesContent":["// extract command — parse this command's flags, call src/extract.ts, print\n// and write the result. No business logic here — the library returns data and throws; only the CLI prints and exits.\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport type { OcrWordInput } from '../extract.ts';\nimport type { Tuning } from '../geometry.ts';\nimport type { Analysis, Report } from '../types.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE =\n 'usage: pdf-to-md [extract] <file.pdf> [out.md] [--json] [--page-markers] [--ocr] [--no-ocr] ' +\n '[--pages N[-M]] [--stdout] [--words-json=FILE] [--debug-words=FILE] ' +\n '[--format md|txt|raw (default md; raw = Analysis JSON incl. the report; txt = reading-order plain text)] ' +\n '[--dpi=N (OCR render resolution, default 288; raise for tiny print or chart/label pages, ' +\n '>~400 measured worse on ordinary prose pages)] ' +\n '[--float-max-words=N] [--float-max-width=F] [--float-margin=F] [--para-gap=F] [--heading-scale=F] ' +\n '[--col-max-width=F] [--col-split=F] [--line-y-tol=F] [--line-height-ratio=F]';\n\nconst FORMATS = ['md', 'txt', 'raw'] as const;\ntype Format = (typeof FORMATS)[number];\n\n// A bad tuning-flag value (non-numeric, or <= 0 unless the flag allows zero) is a usage error, not a silent no-op.\nconst TUNING_FLAGS: {\n name: string;\n key: keyof Tuning;\n allowZero?: boolean;\n isInt?: boolean;\n}[] = [\n {\n name: 'float-max-words',\n key: 'floatMaxWords',\n allowZero: true,\n isInt: true,\n },\n { name: 'float-max-width', key: 'floatMaxWidth' },\n { name: 'float-margin', key: 'floatMargin' },\n { name: 'para-gap', key: 'paraGap' },\n { name: 'heading-scale', key: 'headingScale' },\n { name: 'col-max-width', key: 'colMaxWidth' },\n { name: 'col-split', key: 'colSplit' },\n { name: 'line-y-tol', key: 'lineYTol' },\n { name: 'line-height-ratio', key: 'lineHeightRatio' },\n];\n\nconst extract: Command = async (ctx) => {\n // --debug-words takes a required FILE value; a bare --debug-words is a\n // usage error, checked before parseArgs so it can't silently swallow the next token as its value.\n if (ctx.rest.includes('--debug-words')) {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n json: { type: 'boolean', default: false },\n 'page-markers': { type: 'boolean', default: false },\n ocr: { type: 'boolean', default: false },\n 'no-ocr': { type: 'boolean', default: false },\n stdout: { type: 'boolean', default: false },\n 'debug-words': { type: 'string' },\n help: { type: 'boolean', default: false, short: 'h' },\n pages: { type: 'string' },\n dpi: { type: 'string' },\n format: { type: 'string', default: 'md' },\n 'words-json': { type: 'string' },\n ...Object.fromEntries(TUNING_FLAGS.map((f) => [f.name, { type: 'string' as const }])),\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const values = parsed.values as Record<string, string | boolean | undefined>;\n const positionals = parsed.positionals;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [src, outArg] = positionals;\n const wordsPath = values['words-json'] as string | undefined;\n if (!src && !wordsPath) ctx.usageError(USAGE);\n\n const formatRaw = values.format as string;\n if (!(FORMATS as readonly string[]).includes(formatRaw)) {\n ctx.usageError(`${USAGE}\\n--format must be one of ${FORMATS.join('|')} (got ${JSON.stringify(formatRaw)})`);\n }\n const format = formatRaw as Format;\n\n // --pages: a malformed spec is a usage error; out-of-range page NUMBERS\n // clamp instead (collect.ts / the engine apply the same clamping policy).\n let pages: { first: number; last: number } | undefined;\n if (values.pages !== undefined) {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(values.pages as string);\n const first = m ? Number(m[1]) : Number.NaN;\n const last = m ? (m[2] !== undefined ? Number(m[2]) : first) : Number.NaN;\n if (!m || first < 1 || last < first) {\n ctx.usageError(`${USAGE}\\n--pages requires N or N-M, N >= 1, M >= N (got ${JSON.stringify(values.pages)})`);\n }\n pages = { first, last };\n }\n\n const tuning: Partial<Tuning> = {};\n for (const spec of TUNING_FLAGS) {\n const raw = values[spec.name] as string | undefined;\n if (raw === undefined) continue;\n const value = Number(raw);\n const ok = raw !== '' && Number.isFinite(value) && (spec.allowZero ? value >= 0 : value > 0);\n if (!ok) {\n ctx.usageError(`${USAGE}\\n--${spec.name} requires a ${spec.allowZero ? 'non-negative' : 'positive'} number (got ${JSON.stringify(raw)})`);\n }\n (tuning[spec.key] as number) = spec.isInt ? Math.trunc(value) : value;\n }\n\n // --dpi: page-render resolution, validated like the tuning flags. Default\n // 288 is the measured operating point; >~400 measured WORSE on ordinary pages — not a \"bigger is safer\" knob.\n let dpi: number | undefined;\n if (values.dpi !== undefined) {\n const raw = values.dpi as string;\n const value = Number(raw);\n if (raw === '' || !Number.isFinite(value) || value <= 0) {\n ctx.usageError(`${USAGE}\\n--dpi requires a positive number (got ${JSON.stringify(raw)})`);\n }\n dpi = value;\n }\n\n // In --words-json mode there may be no PDF positional; the words file\n // stands in for naming, extension stripped so the default dest can never overwrite the input. Default extension follows --format.\n const source = src ?? (wordsPath as string);\n const defaultExt = format === 'raw' ? 'json' : format === 'txt' ? 'txt' : 'md';\n const dest = outArg || `${source.replace(/\\.(pdf|jsonl)$/i, '')}.${defaultExt}`;\n\n const onWarning = (m: string) => console.error(m);\n const showProgress = process.stderr.isTTY;\n // onProgress carries per-page timing/count only; human-readable\n // diagnostics (e.g. the sparse-retry notice) arrive via onWarning instead, so they print regardless of TTY-ness.\n const onProgress = (e: { type: 'page'; page: number; words: number; ms: number }) => {\n if (showProgress) console.error(`p${e.page}: ${e.words} words, ${e.ms}ms`);\n };\n const debugWordsPath = values['debug-words'] as string | undefined;\n if (debugWordsPath !== undefined && debugWordsPath.trim() === '') {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n // The severity-1 audit instrument: every recognized word as clean JSON\n // lines to its own file. stderr stays a human channel (mixed prose), never a dump target — this file is guaranteed byte-for-byte parseable.\n const onWords = debugWordsPath\n ? (words: OcrWordInput[]) => {\n const lines = words.map((w) => {\n const entry: OcrWordInput = { page: w.page, text: w.text, x: w.x, y: w.y, w: w.w, h: w.h };\n if (w.confidence !== undefined) entry.confidence = w.confidence;\n return JSON.stringify(entry);\n });\n writeFileSync(debugWordsPath, lines.length ? `${lines.join('\\n')}\\n` : '');\n }\n : undefined;\n\n const common = { pages, onWarning };\n const ocrCommon = {\n ...common,\n tuning,\n dpi,\n onProgress,\n onWords,\n };\n\n let words: OcrWordInput[] | undefined;\n let skipped = 0;\n if (wordsPath !== undefined) {\n ({ words, skipped } = parseWordLines(readFileSync(wordsPath, 'utf8')));\n if (skipped > 0) console.error(`--words-json: skipped ${skipped} non-JSON line(s)`);\n }\n\n let content: string;\n let report: Report;\n if (format === 'md') {\n // Unchanged path: extractOcr/pdfToMarkdown directly, exactly as before\n // --format existed.\n const { extractOcr, pdfToMarkdown } = await import('../extract.ts');\n let markdown: string;\n if (words !== undefined) {\n ({ markdown, report } = await extractOcr({ words }, ocrCommon));\n } else {\n ({ markdown, report } = await pdfToMarkdown(src, {\n ...ocrCommon,\n ocr: values.ocr as boolean,\n noOcr: values['no-ocr'] as boolean,\n pageMarkers: values['page-markers'] as boolean,\n }));\n }\n content = markdown;\n } else {\n // raw/txt: both render from an Analysis — raw IS the Analysis as JSON;\n // txt is toText(analysis). Mirrors pdfToMarkdown's own auto-OCR fallback decision so a different --format doesn't silently pick a different path.\n const { analyze } = await import('../analyze.ts');\n const { toText } = await import('../render-analysis.ts');\n const { needsOcrFallback, ocrFallbackNotice } = await import('../extract.ts');\n let analysis: Analysis;\n if (words !== undefined) {\n analysis = await analyze({ words }, { ...ocrCommon, path: 'ocr' });\n } else if (values.ocr) {\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr' });\n } else {\n const text = await analyze(src, { ...common, path: 'text', pageMarkers: values['page-markers'] as boolean });\n if (needsOcrFallback(text.report.charsPerPage) && !values['no-ocr']) {\n onWarning(ocrFallbackNotice(text.report.charsPerPage));\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr', fallback: true });\n } else {\n analysis = text;\n }\n }\n report = analysis.report;\n content = format === 'raw' ? JSON.stringify(analysis, null, 1) : toText(analysis);\n }\n\n if (values.stdout) process.stdout.write(content);\n else writeFileSync(dest, content);\n\n // The library's Report stays clean of source/out; --json consumers keep\n // report.json files around and need to know which input produced each one, so the CLI (only) decorates the printed JSON with source/out here.\n if (values.json) console.log(JSON.stringify({ source, out: dest, ...report }, null, 1));\n else if (report.path === 'ocr') {\n console.error(`${path.basename(dest).padEnd(32)} OCR path heads=${report.headings}(junk ${report.junkHeadings}) ` + `paras=${report.paragraphs} callouts=${report.callouts} floats=${report.floats ?? 0} dangling=${report.danglingLong} (long) ` + `~${report.charsPerPage} chars/page`);\n } else {\n console.error(\n `${path.basename(dest).padEnd(32)} body=${report.bodyFontHeight}pt heads=${report.headings}(junk ${report.junkHeadings}) ` +\n `lists=${report.listItems} paras=${report.paragraphs} callouts=${report.callouts} pairs=${report.joinedPairs} ` +\n `~${report.charsPerPage} chars/page` +\n (report.sparse ? ' ⚠️ implausibly sparse — pages are likely images; re-run with --ocr' : '')\n );\n }\n};\n\n// Parse one word-dump JSON line per word — key order is not guaranteed, parse\n// never grep. Non-JSON lines are skipped with a count, not fatal (the auditor applies the same policy).\nfunction parseWordLines(raw: string): { words: OcrWordInput[]; skipped: number } {\n const words: OcrWordInput[] = [];\n let skipped = 0;\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n words.push(JSON.parse(line));\n } catch {\n skipped++;\n }\n }\n return { words, skipped };\n}\n\nexport default extract;\n"],"names":["USAGE","FORMATS","TUNING_FLAGS","name","key","allowZero","isInt","extract","ctx","parsed","values","positionals","src","outArg","wordsPath","formatRaw","format","pages","m","first","last","tuning","spec","raw","value","ok","dpi","source","defaultExt","dest","onWarning","showProgress","onProgress","debugWordsPath","onWords","common","ocrCommon","words","skipped","content","report","extractOcr","pdfToMarkdown","markdown","analyze","toText","needsOcrFallback","ocrFallbackNotice","analysis","text","rest","includes","usageError","parseArgs","args","options","json","type","default","ocr","stdout","help","short","Object","fromEntries","map","f","allowPositionals","err","message","console","log","JSON","join","stringify","undefined","exec","Number","NaN","isFinite","Math","trunc","replace","error","process","stderr","isTTY","e","page","ms","trim","lines","w","entry","x","y","h","confidence","writeFileSync","length","parseWordLines","readFileSync","noOcr","pageMarkers","path","charsPerPage","fallback","write","out","basename","padEnd","headings","junkHeadings","paragraphs","callouts","floats","danglingLong","bodyFontHeight","listItems","joinedPairs","sparse","split","line","push","parse"],"mappings":"AAAA,2EAA2E;AAC3E,qHAAqH;;;;;+BA6PrH;;;eAAA;;;sBA5P4C;+DAC3B;wBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAK,YAAcf,IAAIkG,KAAK,CAAC,0BAAxB,SAAA,6BAAA,QAAA,yBAAA,iCAA+B;YAA/B,IAAMC,OAAN;YACH,IAAI,CAACA,KAAKhC,IAAI,IAAI;YAClB,IAAI;gBACFrD,MAAMsF,IAAI,CAACnD,KAAKoD,KAAK,CAACF;YACxB,EAAE,eAAM;gBACNpF;YACF;QACF;;QAPK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAQL,OAAO;QAAED,OAAAA;QAAOC,SAAAA;IAAQ;AAC1B;IAEA,WAAe/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/index.ts"],"sourcesContent":["import type { Command } from './types.ts';\n\n// Lazy registry: a command's imports load only when it runs. These names are\n// reserved — a PDF literally named `extract`/`render` (no extension) needs a ./ prefix.\nexport const COMMANDS: Record<string, () => Promise<{ default: Command }>> = {\n extract: () => import('./extract.ts'),\n render: () => import('./render.ts'),\n audit: () => import('./audit.ts'),\n};\n\nexport type { Command, Ctx } from './types.ts';\n"],"names":["COMMANDS","extract","render","audit"],"mappings":";;;;+BAIaA;;;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAN,IAAMA,WAAgE;IAC3EC,SAAS,SAATA;eAAe;2DAAA,QAAO;;;IACtBC,QAAQ,SAARA;eAAc;2DAAA,QAAO;;;IACrBC,OAAO,SAAPA;eAAa;2DAAA,QAAO;;;AACtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/render.ts"],"sourcesContent":["// render command — render PDF pages to PNG for human/vision-model\n// verification (extraction output is a claim; the page itself is the truth). Thin wrapper: parse flags, call src/raster.ts, write files.\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { PdfToMdError } from '../errors.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE = 'usage: pdf-to-md render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]';\n\nconst render: Command = async (ctx) => {\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n dpi: { type: 'string', default: '288', short: 'd' },\n out: { type: 'string', short: 'o' },\n help: { type: 'boolean', default: false, short: 'h' },\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const { values, positionals } = parsed;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [pdfPath, spec] = positionals;\n if (!pdfPath || !spec) ctx.usageError(USAGE);\n\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(spec);\n if (m === null) throw ctx.usageError(`${USAGE}\\ncould not parse page spec: ${spec}`);\n const firstPage = Number(m[1]);\n const lastPage = m[2] !== undefined ? Number(m[2]) : firstPage;\n if (!(firstPage >= 1) || !(lastPage >= firstPage)) throw ctx.usageError(`${USAGE}\\ninvalid page spec: ${spec}`);\n\n const dpi = Number.parseFloat(values.dpi as string);\n if (!(dpi > 0)) ctx.usageError(`${USAGE}\\n--dpi must be positive`);\n\n const outDir = values.out ?? process.cwd();\n mkdirSync(outDir, { recursive: true });\n const stem = path.basename(pdfPath, path.extname(pdfPath)).replaceAll(' ', '-');\n\n // Imported here, not at module top: keeps pdfjs/canvas out of every other command's startup.\n const { awaitPdfOpen, openPdfForRender } = await import('../pdf-open.ts');\n const { renderLoadedPage } = await import('../raster.ts');\n const loadingTask = openPdfForRender(pdfPath);\n try {\n const doc = await awaitPdfOpen(loadingTask, pdfPath);\n\n // Whole-range check before any file is written, so a partly-valid range\n // fails atomically; renderLoadedPage re-validates per page.\n if (lastPage > doc.numPages) {\n throw new PdfToMdError('PAGE_RANGE', `page range ${firstPage}-${lastPage} is outside this document (1-${doc.numPages})`);\n }\n for (let n = firstPage; n <= lastPage; n++) {\n const { png } = await renderLoadedPage(doc, n, dpi);\n const outPath = path.join(outDir, `${stem}-p${n}.png`);\n writeFileSync(outPath, png);\n console.log(outPath);\n }\n } finally {\n await loadingTask.destroy();\n }\n};\n\nexport default render;\n"],"names":["USAGE","render","ctx","values","parsed","positionals","pdfPath","spec","m","firstPage","lastPage","dpi","outDir","stem","awaitPdfOpen","openPdfForRender","renderLoadedPage","loadingTask","doc","n","png","outPath","parseArgs","args","rest","options","type","default","short","out","help","allowPositionals","err","usageError","message","console","log","exec","Number","undefined","parseFloat","process","cwd","mkdirSync","recursive","path","basename","extname","replaceAll","numPages","PdfToMdError","join","writeFileSync","destroy"],"mappings":"AAAA,kEAAkE;AAClE,yIAAyI;;;;;+BAwEzI;;;eAAA;;;sBAvEyC;+DACxB;wBACS;wBACG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAG7B,IAAMA,QAAQ;AAEd,IAAMC,SAAkB,gBAAOC;;YAoCdC,aAnCTC,QAgBED,QAAQE,aAOQA,cAAjBC,SAASC,MAGVC,GAEAC,WACAC,UAGAC,KAGAC,QAEAC,MAGqC,MAAnCC,cAAcC,kBACdC,kBACFC,aAEEC,KAOGC,GACCC,KACFC;;;;oBArDJjB,SAAS,AAAC;wBACd,IAAI;4BACF,OAAOkB,IAAAA,mBAAS,EAAC;gCACfC,MAAMrB,IAAIsB,IAAI;gCACdC,SAAS;oCACPd,KAAK;wCAAEe,MAAM;wCAAUC,SAAS;wCAAOC,OAAO;oCAAI;oCAClDC,KA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B/B,OAAOgC,iBAAI,CAACC,QAAQ,CAACxC,SAASuC,iBAAI,CAACE,OAAO,CAACzC,UAAU0C,UAAU,CAAC,KAAK;oBAGhC;;wBAAM;2EAAA,QAAO;;;;oBAAb,OAAA,eAAnClC,eAAmC,KAAnCA,cAAcC,mBAAqB,KAArBA;oBACO;;wBAAM;2EAAA,QAAO;;;;oBAAlCC,mBAAqB,cAArBA;oBACFC,cAAcF,iBAAiBT;;;;;;;;;oBAEvB;;wBAAMQ,aAAaG,aAAaX;;;oBAAtCY,MAAM;oBAEZ,wEAAwE;oBACxE,4DAA4D;oBAC5D,IAAIR,WAAWQ,IAAI+B,QAAQ,EAAE;wBAC3B,MAAM,IAAIC,sBAAY,CAAC,cAAc,AAAC,cAA0BxC,OAAbD,WAAU,KAA2CS,OAAxCR,UAAS,iCAA4C,OAAbQ,IAAI+B,QAAQ,EAAC;oBACvH;oBACS9B,IAAIV;;;yBAAWU,CAAAA,KAAKT,QAAO;;;;oBAClB;;wBAAMM,iBAAiBE,KAAKC,GAAGR;;;oBAAvCS,MAAQ,cAARA;oBACFC,UAAUwB,iBAAI,CAACM,IAAI,CAACvC,QAAQ,AAAC,GAAWO,OAATN,MAAK,MAAM,OAAFM,GAAE;oBAChDiC,IAAAA,qBAAa,EAAC/B,SAASD;oBACvBe,QAAQC,GAAG,CAACf;;;oBAJyBF;;;;;;;;;;;oBAOvC;;wBAAMF,YAAYoC,OAAO;;;oBAAzB;;;;;;;;;;IAEJ;;IAEA,WAAepD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/types.ts"],"sourcesContent":["// Handed to every command; the command word is peeled off in src/cli.ts and\n// each command owns its own parseArgs table over `rest` (our commands' flags are disjoint, so a shared table would let `render --para-gap=2` parse silently as a no-op).\nexport interface Ctx {\n /** binary name, for usage strings */\n name: string;\n /** argv after the command word */\n rest: string[];\n /** print the message and exit 2 — every malformed-invocation path.\n * Readonly property (not method) syntax: TS only applies never-return control-flow analysis to readonly property-typed function members. */\n readonly usageError: (message: string) => never;\n}\n\nexport type Command = (ctx: Ctx) => Promise<void> | void;\n"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,yKAAyK"}
|
package/dist/cjs/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli.ts"],"sourcesContent":["// Parsing and dispatch only. Commands live in src/cli/, one file each,\n// lazy-loaded — nothing tree- or dependency-heavy may be imported at the top of this file (`render` must never load the OCR engine, `--version` must load almost nothing).\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { COMMANDS } from './cli/index.ts';\nimport type { Ctx } from './cli/types.ts';\n\n// __dirname (CJS) or its ESM equivalent, then two fixed hops up to the\n// package root. NOT `import.meta.resolve('pdf-to-md/package.json')` — Node's self-reference lookup throws ERR_MODULE_NOT_FOUND from a file this deep; a location-relative path is stable across both build targets.\nconst __dirname = path.dirname(typeof __filename !== 'undefined' ? __filename : fileURLToPath(import.meta.url));\n\nfunction packageVersion(): string {\n try {\n const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { version?: string };\n return pkg.version ?? 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n// Exported so the comparison is unit-testable without spawning a subprocess\n// with a faked Node version. null means unparseable input, not \"not below\".\nexport function isBelowNodeFloor(version: string, floor: string): boolean | null {\n const parts = (v: string) => v.replace(/^v/, '').replace(/^>=/, '').split('.').map(Number);\n const v = parts(version);\n const f = parts(floor);\n if (v.length !== 3 || f.length !== 3 || v.some(Number.isNaN) || f.some(Number.isNaN)) return null;\n const [rMaj, rMin, rPat] = v;\n const [fMaj, fMin, fPat] = f;\n return rMaj !== fMaj ? rMaj < fMaj : rMin !== fMin ? rMin < fMin : rPat < fPat;\n}\n\n// Reads engines.node from package.json (kept as the single source of truth,\n// not hardcoded here) and returns it iff process.version is below it.\nfunction belowNodeFloor(version = process.version): string | null {\n try {\n const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { engines?: { node?: string } };\n const floor = pkg.engines?.node;\n if (!floor) return null;\n return isBelowNodeFloor(version, floor) ? floor.replace(/^>=/, '') : null;\n } catch {\n return null;\n }\n}\n\nfunction usage(name: string): string {\n return (\n `usage: ${name} <file.pdf> [out.md] [flags...] convert a PDF to markdown\\n` +\n ` ${name} extract <file.pdf> [out.md] [flags...] (same, explicit)\\n` +\n ` ${name} render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]\\n` +\n ` ${name} audit <words.jsonl> <file.md> severity-1 word-loss check\\n` +\n ` ${name} --version | --help\\n` +\n '\\n' +\n 'extract flags:\\n' +\n ' --ocr force the OCR path (image-only/scanned pages)\\n' +\n ' --no-ocr never fall back to OCR; keep sparse text output\\n' +\n ' --pages N[-M] convert only these 1-based source pages\\n' +\n ' --stdout write markdown to stdout instead of a file\\n' +\n ' --json print the full QA report as JSON\\n' +\n ` --page-markers emit a \"### pN\" heading per page\\n` +\n ' --format md|txt|raw output format (default md; raw = Analysis JSON incl. the\\n' +\n ' report; txt = reading-order plain text)\\n' +\n ' --words-json=FILE OCR path from a recognized-word dump (offline replay)\\n' +\n ' --debug-words=FILE dump every recognized word as JSON lines to FILE\\n' +\n ' --dpi=N OCR render resolution (default 288; raise for tiny print or\\n' +\n ' chart/label pages, >~400 measured worse on ordinary prose)\\n' +\n '\\n' +\n `extract tuning (measured defaults; see README's tuning table):\\n` +\n ' --float-max-words=N --float-max-width=F --float-margin=F --para-gap=F\\n' +\n ' --heading-scale=F --col-max-width=F --col-split=F --line-y-tol=F\\n' +\n ' --line-height-ratio=F\\n' +\n '\\n' +\n 'examples:\\n' +\n ` ${name} book.pdf # text layer -> book.md (auto-OCR if scanned)\\n` +\n ` ${name} scan.pdf out.md --ocr --json # force OCR, print the QA report\\n` +\n ` ${name} book.pdf --pages 27-31 --stdout # re-extract a page range to stdout\\n` +\n ` ${name} render book.pdf 27 # render p27 to PNG for eyeballing (288 dpi)\\n` +\n ` ${name} audit words.jsonl book.md # check no recognized word was lost`\n );\n}\n\n// Thrown errors -> exit 1 with the message verbatim; usage errors exit 2.\nexport default async function cli(argv: string[], name: string): Promise<void> {\n const floor = belowNodeFloor();\n if (floor) console.error(`${name}: Node ${process.version} is below the required >=${floor} — the OCR path can silently find no words instead of erroring; upgrade Node.`);\n\n if (argv[0] === '--version' || argv[0] === '-v') {\n console.log(packageVersion());\n return;\n }\n if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {\n // No args is a usage ERROR (bare `pdf-to-md` can't do anything); asking\n // for --help is not.\n if (argv.length === 0) {\n console.error(usage(name));\n process.exit(2);\n }\n console.log(`${name} v${packageVersion()}`);\n console.log('');\n console.log(usage(name));\n return;\n }\n\n const ctx: Ctx = {\n name,\n rest: argv.slice(1),\n usageError(message) {\n console.error(message);\n process.exit(2);\n },\n };\n\n try {\n const load = COMMANDS[argv[0]];\n if (load) {\n await (await load()).default(ctx);\n } else {\n // Compat shim: `pdf-to-md file.pdf [...]` — any first word that isn't\n // a reserved command is extract's own first argument.\n ctx.rest = argv;\n await (await COMMANDS.extract()).default(ctx);\n }\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n}\n"],"names":["cli","isBelowNodeFloor","__dirname","path","dirname","__filename","fileURLToPath","packageVersion","pkg","pkgPath","resolve","JSON","parse","readFileSync","version","floor","parts","v","replace","split","map","Number","f","length","some","isNaN","rMaj","rMin","rPat","fMaj","fMin","fPat","belowNodeFloor","process","engines","node","usage","name","argv","ctx","load","err","console","error","log","exit","rest","slice","usageError","message","COMMANDS","default","extract"],"mappings":"AAAA,uEAAuE;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eAAeA,IAAI,CAAC,EAAE,KAAK,MAAM;wBAC/CI,QAAQE,GAAG,CAACrC;wBACZ;;;oBACF;oBACA,IAAI+B,KAAKf,MAAM,KAAK,KAAKe,IAAI,CAAC,EAAE,KAAK,YAAYA,IAAI,CAAC,EAAE,KAAK,MAAM;wBACjE,wEAAwE;wBACxE,qBAAqB;wBACrB,IAAIA,KAAKf,MAAM,KAAK,GAAG;4BACrBmB,QAAQC,KAAK,CAACP,MAAMC;4BACpBJ,QAAQY,IAAI,CAAC;wBACf;wBACAH,QAAQE,GAAG,CAAC,AAAC,GAAWrC,OAAT8B,MAAK,MAAqB,OAAjB9B;wBACxBmC,QAAQE,GAAG,CAAC;wBACZF,QAAQE,GAAG,CAACR,MAAMC;wBAClB;;;oBACF;oBAEME,MAAW;wBACfF,MAAAA;wBACAS,MAAMR,KAAKS,KAAK,CAAC;wBACjBC,YAAAA,SAAAA,WAAWC,OAAO;4BAChBP,QAAQC,KAAK,CAACM;4BACdhB,QAAQY,IAAI,CAAC;wBACf;oBACF;;;;;;;;;oBAGQL,OAAOU,iBAAQ,CAACZ,IAAI,CAAC,EAAE,CAAC;yBAC1BE,MAAAA;;;;oBACK;;wBAAMA;;;oBAAb;;wBAAO,cAAcW,OAAO,CAACZ;;;oBAA7B;;;;;;oBAEA,sEAAsE;oBACtE,sDAAsD;oBACtDA,IAAIO,IAAI,GAAGR;oBACJ;;wBAAMY,iBAAQ,CAACE,OAAO;;;oBAA7B;;wBAAO,cAA0BD,OAAO,CAACZ;;;oBAAzC;;;;;;;;oBAEKE;oBACPC,QAAQC,KAAK,CAAC,AAACF,IAAcQ,OAAO;oBACpChB,QAAQY,IAAI,CAAC;;;;;;;;;;;IAEjB"}
|
package/dist/cjs/collect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/collect.ts"],"sourcesContent":["// Pass 1: load the PDF and collect positioned glyphs per page, plus the\n// document-wide char-weighted font-height histogram. Heights round to 0.1pt for stable histogram keys; y is flipped so sorting ascending reads top-down.\nimport type { PDFPageProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { OPS } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { openDocument } from './pdf-open.ts';\nimport type { CollectedPage, CollectResult, Glyph } from './types.ts';\n\n// HYBRID-PAGE DETECTION (README's \"Design contract\"): a page can carry a\n// real text layer AND a separately-painted large image with its OWN baked-in text that `page.getTextContent()` never sees.\n//\n// Signal: scan the operator list for `OPS.paintImageXObject`, whose args are\n// `[objId, width, height]` — available synchronously, `large` is >=200x200px. Masks/nested Form XObjects aren't walked (accepted gap); missing dims fall back to \"op present\" as the signal.\nconst LARGE_IMAGE_MIN_PX = 200;\nasync function hasLargeImage(page: PDFPageProxy): Promise<boolean> {\n const { fnArray, argsArray } = await page.getOperatorList();\n for (let i = 0; i < fnArray.length; i++) {\n if (fnArray[i] !== OPS.paintImageXObject) continue;\n const [, w, h] = argsArray[i];\n if (typeof w === 'number' && typeof h === 'number') {\n if (w >= LARGE_IMAGE_MIN_PX && h >= LARGE_IMAGE_MIN_PX) return true;\n } else return true; // dims unavailable: coarser \"op present\" signal\n }\n return false;\n}\n\n// { first, last }: 1-based, inclusive page range (the CLI's --pages).\n// Out-of-range values CLAMP to the document's bounds; `page` on each returned entry is always the SOURCE page number, so markers/splicing stay correct.\n//\n// CAVEAT: `heightChars` is built ONLY from the pages actually collected, so\n// a `--pages` subset's heading levels can differ from a full run's — accepted since re-extracted pages get spliced back in for their prose, not diffed.\n\n// Cheap page-count-only load (no per-page text extraction) — the OCR path\n// needs it to resolve its own [first, last] clamping and print a \"### pN\" marker for every page in range, including ones with no recognized words.\nexport async function pageCount(src: string): Promise<number> {\n const doc = await openDocument(src);\n return doc.numPages;\n}\n\nexport async function collect(src: string, { first, last }: { first?: number; last?: number } = {}): Promise<CollectResult> {\n const doc = await openDocument(src);\n const from = Math.min(Math.max(1, first ?? 1), Math.max(1, doc.numPages));\n const to = Math.min(Math.max(from, last ?? doc.numPages), doc.numPages);\n const pages: CollectedPage[] = [];\n const heightChars = new Map<number, number>();\n for (let p = from; p <= to; p++) {\n const page = await doc.getPage(p);\n const { items } = await page.getTextContent();\n const vp = page.getViewport({ scale: 1 });\n const glyphs: Glyph[] = [];\n let textChars = 0;\n for (const it of items) {\n if (!('str' in it) || typeof it.str !== 'string') continue;\n textChars += it.str.length;\n if (!it.str.trim()) continue;\n const h = Math.round(Math.abs(it.transform[3]) * 10) / 10;\n glyphs.push({\n s: it.str,\n x: it.transform[4],\n y: vp.height - it.transform[5],\n w: it.width,\n h,\n });\n heightChars.set(h, (heightChars.get(h) || 0) + it.str.length);\n }\n // \"text layer used\" for hybrid-page purposes (page text > 80 chars) — a\n // page with only a couple of stray scraps isn't \"using\" the text layer even if it also carries a large image.\n const largeImage = textChars > 80 && (await hasLargeImage(page));\n pages.push({\n page: p,\n glyphs,\n width: vp.width,\n height: vp.height,\n textChars,\n largeImage,\n });\n }\n // `numPages` is the SELECTED count, not doc.numPages: the auto-OCR\n // chars/page floor must judge a `--pages` subset against its own page count, or a genuinely image-only page reads as merely \"sparse\".\n return { numPages: pages.length, pages, heightChars };\n}\n"],"names":["collect","pageCount","LARGE_IMAGE_MIN_PX","hasLargeImage","page","fnArray","argsArray","i","w","h","getOperatorList","length","OPS","paintImageXObject","src","doc","openDocument","numPages","first","last","from","to","pages","heightChars","p","items","vp","glyphs","textChars","it","largeImage","Math","min","max","Map","getPage","getTextContent","getViewport","scale","str","trim","round","abs","transform","push","s","x","y","height","width","set","get"],"mappings":"AAAA,wEAAwE;AACxE,yJAAyJ;;;;;;;;;;;;QAqCnIA;eAAAA;;QALAC;eAAAA;;;mBA9BF;yBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAY;+BAAZA;;;;oBAAmB;;wBAAMzB,cAAcC;;;2BAApB;;;oBAAhC0B;oBACNR,MAAMsB,IAAI,CAAC;wBACTxC,MAAMoB;wBACNG,QAAAA;wBACAsB,OAAOvB,GAAGuB,KAAK;wBACfD,QAAQtB,GAAGsB,MAAM;wBACjBpB,WAAAA;wBACAE,YAAAA;oBACF;;;oBA9B0BN;;;;;;oBAgC5B,mEAAmE;oBACnE,sIAAsI;oBACtI;;wBAAO;4BAAEP,UAAUK,MAAMX,MAAM;4BAAEW,OAAAA;4BAAOC,aAAAA;wBAAY;;;;IACtD"}
|
package/dist/cjs/dict.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/dict.ts"],"sourcesContent":["// The hyphen-rejoin dictionary, shared by src/emit.ts and src/markdown.ts.\n// Loaded once, lazily, on first use — never at import — so importing the library does no file IO on its own.\nimport { existsSync, readFileSync } from 'node:fs';\nimport wordListPath from 'word-list';\n\n// Bundled list (not the OS's /usr/share/dict/words) → identical rejoin decisions on every\n// OS/machine. PDF_TO_MD_DICT_PATH overrides it — the test seam for simulating no dictionary.\nexport const DICT_PATH = process.env.PDF_TO_MD_DICT_PATH || wordListPath;\n\nlet cache: { words: Set<string>; available: boolean } | null = null;\n\nfunction load(): { words: Set<string>; available: boolean } {\n if (!cache) {\n const available = existsSync(DICT_PATH);\n cache = { words: available ? new Set(readFileSync(DICT_PATH, 'utf8').toLowerCase().split('\\n')) : new Set(), available };\n }\n return cache;\n}\n\n/** The hyphen-rejoin dictionary; an empty set if none was found. */\nexport function getDict(): Set<string> {\n return load().words;\n}\n\n/** False when no dictionary file exists at DICT_PATH — every line-final\n * hyphen then stays unresolved. */\nexport function dictAvailable(): boolean {\n return load().available;\n}\n\n/** The notice callers surface via warn() when dictAvailable() is false. */\nexport function dictUnavailableWarning(): string {\n return `no dictionary at ${DICT_PATH} — line-final hyphens kept unresolved`;\n}\n"],"names":["DICT_PATH","dictAvailable","dictUnavailableWarning","getDict","process","env","PDF_TO_MD_DICT_PATH","wordListPath","cache","load","available","existsSync","words","Set","readFileSync","toLowerCase","split"],"mappings":"AAAA,2EAA2E;AAC3E,6GAA6G;;;;;;;;;;;;QAMhGA;eAAAA;;QAmBGC;eAAAA;;QAKAC;eAAAA;;QAXAC;eAAAA;;;sBAlByB;+DAChB;;;;;;AAIlB,IAAMH,YAAYI,QAAQC,GAAG,CAACC,mBAAmB,IAAIC,iBAAY;AAExE,IAAIC,QAA2D;AAE/D,SAASC;IACP,IAAI,CAACD,OAAO;QACV,IAAME,YAAYC,IAAAA,kBAAU,EAACX;QAC7BQ,QAAQ;YAAEI,OAAOF,YAAY,IAAIG,IAAIC,IAAAA,oBAAY,EAACd,WAAW,QAAQe,WAAW,GAAGC,KAAK,CAAC,SAAS,IAAIH;YAAOH,WAAAA;QAAU;IACzH;IACA,OAAOF;AACT;AAGO,SAASL;IACd,OAAOM,OAAOG,KAAK;AACrB;AAIO,SAASX;IACd,OAAOQ,OAAOC,SAAS;AACzB;AAGO,SAASR;IACd,OAAO,AAAC,oBAA6B,OAAVF,WAAU;AACvC"}
|
package/dist/cjs/emit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/emit.ts"],"sourcesContent":["// emit.ts — OCR-path pass 3: lines -> markdown blocks.\nimport { getDict } from './dict.ts';\nimport type { OcrLine, PageOCR, Tuning, Word } from './geometry.ts';\nimport { bucket } from './geometry.ts';\n\n// Join a wrapped line onto the open paragraph, closing a line-final hyphen\n// only when the dictionary confirms the joined form is a word.\nfunction hyphenJoin(acc: string, next: string): string {\n if (acc.endsWith('-')) {\n const withoutDash = acc.slice(0, -1);\n const pen = withoutDash.at(-1);\n if (pen && /[A-Za-z0-9]/.test(pen)) {\n const head = withoutDash.split(' ').pop() ?? '';\n const firstTok = next.split(' ')[0] ?? '';\n const filtered = [...firstTok].filter((c) => /[A-Za-z-]/.test(c)).join('');\n const tail = filtered.split('-')[0] ?? '';\n const close = getDict().has((head + tail).toLowerCase());\n return (close ? withoutDash : acc) + next;\n }\n }\n return `${acc} ${next}`;\n}\n\n// Blocks with too few word-like tokens to trust as prose (see\n// UNSTRUCTURED_WORDLIKE_FRACTION below) are labeled `> [review: reason] text` instead of guessed at.\nconst REVIEW_REASON = {\n unstructuredLabels: 'unstructured labels',\n} as const;\n\n/** Share of word-like tokens (3+ letter run) below which a block counts as\n * unstructured. Measured (`review-blocks.test.ts`): junk 0.000-0.100 vs prose 0.743-0.857, cut 0.4. */\nexport const UNSTRUCTURED_WORDLIKE_FRACTION = 0.4;\nfunction isUnstructured(text: string): boolean {\n const tokens = text.split(/\\s+/).filter(Boolean);\n if (tokens.length === 0) return false; // never mark an empty block\n const wordLike = tokens.filter((t) => /[A-Za-z]{3}/.test(t)).length;\n return wordLike / tokens.length < UNSTRUCTURED_WORDLIKE_FRACTION;\n}\n\nfunction reviewLine(reason: string, text: string): string {\n return `> [review: ${reason}] ${text}`;\n}\n\n// One classified block, carrying constituent words for analyze()'s\n// block->word linkage; discriminated on `kind` so `reason`/`level` are compile-time guaranteed present on their variants.\nexport type EmitBlock =\n | { kind: 'heading'; text: string; level: number; words: Word[] }\n | { kind: 'paragraph'; text: string; words: Word[] }\n | { kind: 'quote'; text: string; words: Word[] }\n | {\n kind: 'review';\n text: string;\n /** The parseable reason inside `> [review: ...]`, carried on the block\n * so more reasons can be added without changing the render format. */\n reason: string;\n words: Word[];\n };\n\n// Renders one EmitBlock to the exact markdown emitPage used to push\n// directly — shared so extract.ts and analyze.ts produce byte-identical text.\nexport function renderEmitBlock(b: EmitBlock): string {\n switch (b.kind) {\n case 'heading':\n return `${'#'.repeat(b.level)} ${b.text}`;\n case 'quote':\n return `> ${b.text}`;\n case 'review':\n return reviewLine(b.reason, b.text);\n default:\n return b.text;\n }\n}\n\nexport function emitPage(p: PageOCR, levelOf: Map<number, number>, tuning: Tuning): EmitBlock[] {\n const blocks: EmitBlock[] = [];\n let para: OcrLine[] = [];\n const flush = () => {\n if (!para.length) return;\n const texts = para.map((l) => l.text);\n const merged = texts.slice(1).reduce(hyphenJoin, texts[0]);\n const words = para.flatMap((l) => l.words);\n // Same review-marker rule as the heading path below: no word may be\n // dropped or reordered here, only how the block renders changes.\n blocks.push(isUnstructured(merged) ? { kind: 'review', text: merged, reason: REVIEW_REASON.unstructuredLabels, words } : { kind: 'paragraph', text: merged, words });\n para = [];\n };\n\n let i = 0;\n while (i < p.lines.length) {\n const line: OcrLine = p.lines[i];\n const prev = i > 0 ? p.lines[i - 1] : null;\n if (prev && (line.col !== prev.col || prev.midY - line.midY > p.pitch * tuning.paraGap)) {\n // Join across a column break (instead of flushing) only when the column\n // changed, the paragraph dangles (no terminal punct), and the new text starts lowercase; a miss stays visible via pageStats.danglingLong.\n const danglingEnd = para.length > 0 && !/[.!?:;\"'”’)\\]]$/.test(para[para.length - 1].text);\n const continuationStart = /^[a-z]/.test(line.text);\n const joinAcrossColumns = line.col !== prev.col && danglingEnd && continuationStart && !levelOf.has(bucket(line.h));\n if (!joinAcrossColumns) flush();\n }\n\n if (levelOf.has(bucket(line.h))) {\n // Gather the run of consecutive heading-size lines: a wrapped title is\n // one heading, a long run is a pull quote in a bigger face.\n flush();\n const run: OcrLine[] = [line];\n let maxB = bucket(line.h);\n while (i + 1 < p.lines.length && levelOf.has(bucket(p.lines[i + 1].h)) && p.lines[i + 1].col === p.lines[i].col && p.lines[i].midY - p.lines[i + 1].midY < Math.max(p.lines[i].h, p.lines[i + 1].h) * 2.2) {\n i++;\n run.push(p.lines[i]);\n maxB = Math.max(maxB, bucket(p.lines[i].h));\n }\n const runTexts = run.map((l) => l.text);\n const merged = runTexts.slice(1).reduce(hyphenJoin, runTexts[0]);\n const words = run.flatMap((l) => l.words);\n // Below UNSTRUCTURED_WORDLIKE_FRACTION = chart labels/stray numerals,\n // not a heading; checked FIRST so a long numeral run isn't asserted as a pull quote.\n const junk = isUnstructured(merged);\n if (junk) blocks.push({ kind: 'review', text: merged, reason: REVIEW_REASON.unstructuredLabels, words });\n else if (merged.length > 150) blocks.push({ kind: 'quote', text: merged, words });\n else blocks.push({ kind: 'heading', text: merged, level: levelOf.get(maxB) as number, words });\n } else {\n para.push(line);\n }\n i++;\n }\n flush();\n return blocks;\n}\n"],"names":["UNSTRUCTURED_WORDLIKE_FRACTION","emitPage","renderEmitBlock","hyphenJoin","acc","next","endsWith","withoutDash","slice","pen","at","test","filtered","head","split","pop","firstTok","filter","c","join","tail","close","getDict","has","toLowerCase","REVIEW_REASON","unstructuredLabels","isUnstructured","text","tokens","Boolean","length","wordLike","t","reviewLine","reason","b","kind","repeat","level","p","levelOf","tuning","blocks","para","flush","texts","map","l","merged","reduce","words","flatMap","push","i","lines","line","prev","col","midY","pitch","paraGap","danglingEnd","continuationStart","joinAcrossColumns","bucket","h","run","maxB","Math","max","runTexts","junk","get"],"mappings":"AAAA,uDAAuD;;;;;;;;;;;;QA+B1CA;eAAAA;;QA0CGC;eAAAA;;QAbAC;eAAAA;;;sBA3DQ;0BAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvB,2EAA2E;AAC3E,+DAA+D;AAC/D,SAASC,WAAWC,GAAW,EAAEC,IAAY;IAC3C,IAAID,IAAIE,QAAQ,CAAC,MAAM;QACrB,IAAMC,cAAcH,IAAII,KAAK,CAAC,GAAG,CAAC;QAClC,IAAMC,MAAMF,YAAYG,EAAE,CAAC,CAAC;QAC5B,IAAID,OAAO,cAAcE,IAAI,CAACF,MAAM;gBACrBF,wBACIF,cAEJO;YAHb,IAAMC,QAAON,yBAAAA,YAAYO,KAAK,CAAC,KAAKC,GAAG,gBAA1BR,oCAAAA,yBAAgC;YAC7C,IAAMS,YAAWX,eAAAA,KAAKS,KAAK,CAAC,IAAI,CAAC,EAAE,cAAlBT,0BAAAA,eAAsB;YACvC,IAAMO,WAAW,AAAC,qBAAG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5B,IAAIuB,MAAM7B,OAAOU,IAAI,CAAC;gBAAEhB,MAAM;gBAAUT,MAAMqB;gBAAQd,QAAQV,cAAcC,kBAAkB;gBAAEyB,OAAAA;YAAM;iBACjG,IAAIF,OAAOlB,MAAM,GAAG,KAAKY,OAAOU,IAAI,CAAC;gBAAEhB,MAAM;gBAAST,MAAMqB;gBAAQE,OAAAA;YAAM;iBAC1ER,OAAOU,IAAI,CAAC;gBAAEhB,MAAM;gBAAWT,MAAMqB;gBAAQV,OAAOE,QAAQgC,GAAG,CAACL;gBAAiBjB,OAAAA;YAAM;QAC9F,OAAO;YACLP,KAAKS,IAAI,CAACG;QACZ;QACAF;IACF;IACAT;IACA,OAAOF;AACT"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/emit.ts"],"sourcesContent":["// emit.ts — OCR-path pass 3: lines -> markdown blocks.\nimport { getDict } from './dict.ts';\nimport type { OcrLine, PageOCR, Tuning, Word } from './geometry.ts';\nimport { bucket } from './geometry.ts';\n\n// Join a wrapped line onto the open paragraph, closing a line-final hyphen\n// only when the dictionary confirms the joined form is a word.\nfunction hyphenJoin(acc: string, next: string): string {\n if (acc.endsWith('-')) {\n const withoutDash = acc.slice(0, -1);\n const pen = withoutDash.at(-1);\n if (pen && /[A-Za-z0-9]/.test(pen)) {\n const head = withoutDash.split(' ').pop() ?? '';\n const firstTok = next.split(' ')[0] ?? '';\n const filtered = [...firstTok].filter((c) => /[A-Za-z-]/.test(c)).join('');\n const tail = filtered.split('-')[0] ?? '';\n const close = getDict().has((head + tail).toLowerCase());\n return (close ? withoutDash : acc) + next;\n }\n }\n return `${acc} ${next}`;\n}\n\n// Blocks with too few word-like tokens to trust as prose (see\n// UNSTRUCTURED_WORDLIKE_FRACTION below) are labeled `> [review: reason] text` instead of guessed at.\nconst REVIEW_REASON = {\n unstructuredLabels: 'unstructured labels',\n} as const;\n\n/** Share of word-like tokens (3+ letter run) below which a block counts as\n * unstructured. Measured (`review-blocks.test.ts`): junk 0.000-0.100 vs prose 0.743-0.857, cut 0.4. */\nexport const UNSTRUCTURED_WORDLIKE_FRACTION = 0.4;\nfunction isUnstructured(text: string): boolean {\n const tokens = text.split(/\\s+/).filter(Boolean);\n if (tokens.length === 0) return false; // never mark an empty block\n const wordLike = tokens.filter((t) => /[A-Za-z]{3}/.test(t)).length;\n return wordLike / tokens.length < UNSTRUCTURED_WORDLIKE_FRACTION;\n}\n\nfunction reviewLine(reason: string, text: string): string {\n return `> [review: ${reason}] ${text}`;\n}\n\n// One classified block, carrying constituent words for analyze()'s\n// block->word linkage; discriminated on `kind` so `reason`/`level` are compile-time guaranteed present on their variants.\nexport type EmitBlock =\n | { kind: 'heading'; text: string; level: number; words: Word[] }\n | { kind: 'paragraph'; text: string; words: Word[] }\n | { kind: 'quote'; text: string; words: Word[] }\n | {\n kind: 'review';\n text: string;\n /** The parseable reason inside `> [review: ...]`, carried on the block\n * so more reasons can be added without changing the render format. */\n reason: string;\n words: Word[];\n };\n\n// Renders one EmitBlock to the exact markdown emitPage used to push\n// directly — shared so extract.ts and analyze.ts produce byte-identical text.\nexport function renderEmitBlock(b: EmitBlock): string {\n switch (b.kind) {\n case 'heading':\n return `${'#'.repeat(b.level)} ${b.text}`;\n case 'quote':\n return `> ${b.text}`;\n case 'review':\n return reviewLine(b.reason, b.text);\n default:\n return b.text;\n }\n}\n\nexport function emitPage(p: PageOCR, levelOf: Map<number, number>, tuning: Tuning): EmitBlock[] {\n const blocks: EmitBlock[] = [];\n let para: OcrLine[] = [];\n const flush = () => {\n if (!para.length) return;\n const texts = para.map((l) => l.text);\n const merged = texts.slice(1).reduce(hyphenJoin, texts[0]);\n const words = para.flatMap((l) => l.words);\n // Same review-marker rule as the heading path below: no word may be\n // dropped or reordered here, only how the block renders changes.\n blocks.push(isUnstructured(merged) ? { kind: 'review', text: merged, reason: REVIEW_REASON.unstructuredLabels, words } : { kind: 'paragraph', text: merged, words });\n para = [];\n };\n\n let i = 0;\n while (i < p.lines.length) {\n const line: OcrLine = p.lines[i];\n const prev = i > 0 ? p.lines[i - 1] : null;\n if (prev && (line.col !== prev.col || prev.midY - line.midY > p.pitch * tuning.paraGap)) {\n // Join across a column break (instead of flushing) only when the column\n // changed, the paragraph dangles (no terminal punct), and the new text starts lowercase; a miss stays visible via pageStats.danglingLong.\n const danglingEnd = para.length > 0 && !/[.!?:;\"'”’)\\]]$/.test(para[para.length - 1].text);\n const continuationStart = /^[a-z]/.test(line.text);\n const joinAcrossColumns = line.col !== prev.col && danglingEnd && continuationStart && !levelOf.has(bucket(line.h));\n if (!joinAcrossColumns) flush();\n }\n\n if (levelOf.has(bucket(line.h))) {\n // Gather the run of consecutive heading-size lines: a wrapped title is\n // one heading, a long run is a pull quote in a bigger face.\n flush();\n const run: OcrLine[] = [line];\n let maxB = bucket(line.h);\n while (i + 1 < p.lines.length && levelOf.has(bucket(p.lines[i + 1].h)) && p.lines[i + 1].col === p.lines[i].col && p.lines[i].midY - p.lines[i + 1].midY < Math.max(p.lines[i].h, p.lines[i + 1].h) * 2.2) {\n i++;\n run.push(p.lines[i]);\n maxB = Math.max(maxB, bucket(p.lines[i].h));\n }\n const runTexts = run.map((l) => l.text);\n const merged = runTexts.slice(1).reduce(hyphenJoin, runTexts[0]);\n const words = run.flatMap((l) => l.words);\n // Below UNSTRUCTURED_WORDLIKE_FRACTION = chart labels/stray numerals,\n // not a heading; checked FIRST so a long numeral run isn't asserted as a pull quote.\n const junk = isUnstructured(merged);\n if (junk) blocks.push({ kind: 'review', text: merged, reason: REVIEW_REASON.unstructuredLabels, words });\n else if (merged.length > 150) blocks.push({ kind: 'quote', text: merged, words });\n else blocks.push({ kind: 'heading', text: merged, level: levelOf.get(maxB) as number, words });\n } else {\n para.push(line);\n }\n i++;\n }\n flush();\n return blocks;\n}\n"],"names":["UNSTRUCTURED_WORDLIKE_FRACTION","emitPage","renderEmitBlock","hyphenJoin","acc","next","endsWith","withoutDash","slice","pen","at","test","filtered","head","split","pop","firstTok","filter","c","join","tail","close","getDict","has","toLowerCase","REVIEW_REASON","unstructuredLabels","isUnstructured","text","tokens","Boolean","length","wordLike","t","reviewLine","reason","b","kind","repeat","level","p","levelOf","tuning","blocks","para","flush","texts","map","l","merged","reduce","words","flatMap","push","i","lines","line","prev","col","midY","pitch","paraGap","danglingEnd","continuationStart","joinAcrossColumns","bucket","h","run","maxB","Math","max","runTexts","junk","get"],"mappings":"AAAA,uDAAuD;;;;;;;;;;;;QA+B1CA;eAAAA;;QA0CGC;eAAAA;;QAbAC;eAAAA;;;sBA3DQ;0BAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvB,2EAA2E;AAC3E,+DAA+D;AAC/D,SAASC,WAAWC,GAAW,EAAEC,IAAY;IAC3C,IAAID,IAAIE,QAAQ,CAAC,MAAM;QACrB,IAAMC,cAAcH,IAAII,KAAK,CAAC,GAAG,CAAC;QAClC,IAAMC,MAAMF,YAAYG,EAAE,CAAC,CAAC;QAC5B,IAAID,OAAO,cAAcE,IAAI,CAACF,MAAM;gBACrBF,wBACIF,cAEJO;YAHb,IAAMC,QAAON,yBAAAA,YAAYO,KAAK,CAAC,KAAKC,GAAG,gBAA1BR,oCAAAA,yBAAgC;YAC7C,IAAMS,YAAWX,eAAAA,KAAKS,KAAK,CAAC,IAAI,CAAC,EAAE,cAAlBT,0BAAAA,eAAsB;YACvC,IAAMO,WAAW,AAAC,qBAAGI,UAAUC,MAAM,CAAC,SAACC;uBAAM,YAAYP,IAAI,CAACO;eAAIC,IAAI,CAAC;YACvE,IAAMC,QAAOR,mBAAAA,SAASE,KAAK,CAAC,IAAI,CAAC,EAAE,cAAtBF,8BAAAA,mBAA0B;YACvC,IAAMS,QAAQC,IAAAA,eAAO,IAAGC,GAAG,CAAC,AAACV,CAAAA,OAAOO,IAAG,EAAGI,WAAW;YACrD,OAAO,AAACH,CAAAA,QAAQd,cAAcH,GAAE,IAAKC;QACvC;IACF;IACA,OAAO,AAAC,GAASA,OAAPD,KAAI,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