@shuji-bonji/pdf-reader-mcp 0.8.0 → 0.9.1
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/CHANGELOG.md +94 -0
- package/README.ja.md +37 -7
- package/README.md +41 -9
- package/dist/services/actual-text-service.d.ts +99 -0
- package/dist/services/actual-text-service.d.ts.map +1 -0
- package/dist/services/actual-text-service.js +196 -0
- package/dist/services/actual-text-service.js.map +1 -0
- package/dist/services/content-stream-service.d.ts +70 -0
- package/dist/services/content-stream-service.d.ts.map +1 -0
- package/dist/services/content-stream-service.js +524 -0
- package/dist/services/content-stream-service.js.map +1 -0
- package/dist/services/pdfjs-service.d.ts +69 -24
- package/dist/services/pdfjs-service.d.ts.map +1 -1
- package/dist/services/pdfjs-service.js +163 -177
- package/dist/services/pdfjs-service.js.map +1 -1
- package/dist/services/struct-tree-service.d.ts +21 -62
- package/dist/services/struct-tree-service.d.ts.map +1 -1
- package/dist/services/struct-tree-service.js +132 -132
- package/dist/services/struct-tree-service.js.map +1 -1
- package/dist/services/struct-tree-walker.d.ts +93 -0
- package/dist/services/struct-tree-walker.d.ts.map +1 -0
- package/dist/services/struct-tree-walker.js +177 -0
- package/dist/services/struct-tree-walker.js.map +1 -0
- package/dist/tools/tier1/read-text.d.ts.map +1 -1
- package/dist/tools/tier1/read-text.js +5 -1
- package/dist/tools/tier1/read-text.js.map +1 -1
- package/dist/tools/tier1/search-text.d.ts.map +1 -1
- package/dist/tools/tier1/search-text.js +22 -1
- package/dist/tools/tier1/search-text.js.map +1 -1
- package/dist/tools/tier2/extract-tables.d.ts.map +1 -1
- package/dist/tools/tier2/extract-tables.js +15 -9
- package/dist/tools/tier2/extract-tables.js.map +1 -1
- package/dist/types.d.ts +17 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/formatter.d.ts +12 -0
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +49 -3
- package/dist/utils/formatter.js.map +1 -1
- package/package.json +1 -1
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Centralizes all pdfjs-dist interactions for reuse across tools.
|
|
5
5
|
*/
|
|
6
|
+
import type { PDFDocument as PdfLibDocument } from 'pdf-lib';
|
|
6
7
|
import { type PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';
|
|
7
|
-
import type { AnnotationsAnalysis, ImageExtractionResult, PageText, PdfMetadata, SearchMatch,
|
|
8
|
+
import type { AnnotationsAnalysis, ImageExtractionResult, PageText, PdfMetadata, SearchMatch, TagsAnalysis } from '../types.js';
|
|
8
9
|
/**
|
|
9
10
|
* Load a PDF document from a file path.
|
|
10
11
|
*/
|
|
@@ -37,19 +38,60 @@ export interface ExtractTextOptions {
|
|
|
37
38
|
splitColumns?: number;
|
|
38
39
|
compactWhitespace?: boolean;
|
|
39
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Everything `/ActualText` resolution needs that pdfjs cannot supply (#18):
|
|
43
|
+
* a pdf-lib view of the same file, for the structure tree and the content
|
|
44
|
+
* streams. Absent when the file could not be opened with pdf-lib, in which case
|
|
45
|
+
* extraction falls back to raw glyphs.
|
|
46
|
+
*/
|
|
47
|
+
interface ActualTextResolution {
|
|
48
|
+
libDoc: PdfLibDocument;
|
|
49
|
+
structActualText: ReadonlyMap<string, string>;
|
|
50
|
+
/**
|
|
51
|
+
* The document is encrypted, so neither path can run: §7.6.2 encrypts strings
|
|
52
|
+
* and streams, and pdf-lib is loaded with `ignoreEncryption`. Recorded so the
|
|
53
|
+
* caller can say *why* nothing was resolved — "the content stream did not
|
|
54
|
+
* line up" would be a wrong and unactionable explanation here.
|
|
55
|
+
*/
|
|
56
|
+
encrypted: boolean;
|
|
57
|
+
}
|
|
40
58
|
/**
|
|
41
59
|
* Extract text from a pre-loaded PDFDocumentProxy.
|
|
42
60
|
* Does NOT destroy the document — caller is responsible for lifecycle.
|
|
43
61
|
*/
|
|
44
|
-
export declare function extractTextFromDoc(doc: PDFDocumentProxy, pages?: string, options?: ExtractTextOptions): Promise<PageText[]>;
|
|
62
|
+
export declare function extractTextFromDoc(doc: PDFDocumentProxy, pages?: string, options?: ExtractTextOptions, resolution?: ActualTextResolution): Promise<PageText[]>;
|
|
45
63
|
/**
|
|
46
64
|
* Extract text from specified pages (1-based).
|
|
65
|
+
*
|
|
66
|
+
* Resolves `/ActualText` (ISO 32000-2 §14.9.4) on both of the paths the clause
|
|
67
|
+
* defines — see `actual-text-service`. The pdf-lib load that makes this possible
|
|
68
|
+
* is best-effort: a file it cannot parse still extracts, as raw glyphs.
|
|
47
69
|
*/
|
|
48
70
|
export declare function extractText(filePath: string, pages?: string, options?: ExtractTextOptions): Promise<PageText[]>;
|
|
71
|
+
/** What `search_text` gets back: the matches, and how complete the text was. */
|
|
72
|
+
export interface SearchTextResult {
|
|
73
|
+
matches: SearchMatch[];
|
|
74
|
+
/**
|
|
75
|
+
* Pages where `/ActualText` could not be resolved (§14.9.4). A miss on one of
|
|
76
|
+
* these pages may still be a replacement the search could not see — which is
|
|
77
|
+
* what #15 warned about, now narrowed to the cases where it is actually true.
|
|
78
|
+
*/
|
|
79
|
+
unresolvedPages: number[];
|
|
80
|
+
/**
|
|
81
|
+
* Why `unresolvedPages` is non-empty. `encrypted` means the whole document is
|
|
82
|
+
* out of reach and no other tool of this server will do better; `unaligned`
|
|
83
|
+
* means the content stream of those particular pages could not be matched up
|
|
84
|
+
* with the extracted text.
|
|
85
|
+
*/
|
|
86
|
+
unresolvedReason?: 'encrypted' | 'unaligned';
|
|
87
|
+
}
|
|
49
88
|
/**
|
|
50
89
|
* Search for text across all pages.
|
|
90
|
+
*
|
|
91
|
+
* Searches the same text `read_text` returns, `/ActualText` included (#18), so
|
|
92
|
+
* the two tools can no longer disagree about whether a word is in the document.
|
|
51
93
|
*/
|
|
52
|
-
export declare function searchText(filePath: string, query: string, contextChars?: number, pages?: string): Promise<
|
|
94
|
+
export declare function searchText(filePath: string, query: string, contextChars?: number, pages?: string): Promise<SearchTextResult>;
|
|
53
95
|
/**
|
|
54
96
|
* Count images from a pre-loaded PDFDocumentProxy.
|
|
55
97
|
* Does NOT destroy the document — caller is responsible for lifecycle.
|
|
@@ -79,32 +121,21 @@ export declare function describeImageKind(kind: number | undefined): {
|
|
|
79
121
|
* Returns both extracted images and counts of detected/skipped images.
|
|
80
122
|
*/
|
|
81
123
|
export declare function extractImages(filePath: string, pages?: string): Promise<ImageExtractionResult>;
|
|
124
|
+
/**
|
|
125
|
+
* Whether the document claims to be tagged (`/MarkInfo /Marked true`).
|
|
126
|
+
*
|
|
127
|
+
* Was used by search_text to explain empty results on tagged documents (#15).
|
|
128
|
+
* Since #18 resolves `/ActualText` on both of its paths, an empty result no
|
|
129
|
+
* longer implies replacement text was missed, and the warning is keyed off the
|
|
130
|
+
* pages where resolution was actually skipped instead. Kept as a public probe:
|
|
131
|
+
* `get_metadata` reports the same flag, and the tests assert it.
|
|
132
|
+
*/
|
|
133
|
+
export declare function isTaggedPdf(filePath: string): Promise<boolean>;
|
|
82
134
|
/**
|
|
83
135
|
* Analyze Tagged PDF structure tree from a pre-loaded document.
|
|
84
136
|
* Does NOT destroy the document — caller is responsible for lifecycle.
|
|
85
137
|
*/
|
|
86
138
|
export declare function analyzeTagsFromDoc(doc: PDFDocumentProxy): Promise<TagsAnalysis>;
|
|
87
|
-
/**
|
|
88
|
-
* Extract tables from a Tagged PDF as structured rows/cells.
|
|
89
|
-
*
|
|
90
|
-
* The strategy is: for each page, walk the StructTree, identify `<Table>`
|
|
91
|
-
* subtrees, then walk down `<THead>/<TBody>/<TFoot>` → `<TR>` → `<TH>/<TD>`.
|
|
92
|
-
* Cell text is reconstructed by mapping each Span/P/Lbl/LBody leaf node's
|
|
93
|
-
* `id` (e.g. `p715R_mc4`) onto the corresponding `beginMarkedContentProps`
|
|
94
|
-
* boundary in `getTextContent({ includeMarkedContent: true })`.
|
|
95
|
-
*
|
|
96
|
-
* Untagged PDFs return `isTagged: false`, an empty `tables` array, and a
|
|
97
|
-
* `note` recommending the column-aware extraction (planned in a future
|
|
98
|
-
* release) as the fallback for two-column layouts without a structure tree.
|
|
99
|
-
*
|
|
100
|
-
* Cell text is post-processed:
|
|
101
|
-
* - Newlines (`hasEOL`) become single spaces.
|
|
102
|
-
* - Repeated whitespace runs (including U+3000 fullwidth space) collapse to one.
|
|
103
|
-
* - Per-character kerning spaces (e.g. `"消 費 税 法"`) are folded
|
|
104
|
-
* by removing single ASCII spaces between two CJK characters.
|
|
105
|
-
*/
|
|
106
|
-
export declare function extractTablesFromDoc(doc: PDFDocumentProxy, pages?: string): Promise<TablesExtractionResult>;
|
|
107
|
-
export declare function extractTables(filePath: string, pages?: string): Promise<TablesExtractionResult>;
|
|
108
139
|
/** A `getTextContent({ includeMarkedContent: true })` item. */
|
|
109
140
|
export interface TextContentItemLike {
|
|
110
141
|
type?: string;
|
|
@@ -166,6 +197,19 @@ export declare function resolveLineBreaks(text: string): string;
|
|
|
166
197
|
* (`p7R_mc0`) — so merging the per-page maps is safe.
|
|
167
198
|
*/
|
|
168
199
|
export declare function buildDocumentIdToTextMap(doc: PDFDocumentProxy): Promise<Map<string, string>>;
|
|
200
|
+
/**
|
|
201
|
+
* Normalise raw cell text:
|
|
202
|
+
* 0. Resolve line breaks (CJK-aware) — a break between two CJK characters is
|
|
203
|
+
* not a space. Must precede step 1, which would otherwise turn the break
|
|
204
|
+
* into a space that the step-2 fold cannot remove (it needs 2+ repeats).
|
|
205
|
+
* 1. Collapse any whitespace run (`\s` + U+3000) to a single ASCII space.
|
|
206
|
+
* 2. Fold per-character kerning runs between CJK characters
|
|
207
|
+
* (e.g. "消 費 税 法" → "消費税法") — but only when at least three
|
|
208
|
+
* single CJK chars are separated by single spaces in a row, so that
|
|
209
|
+
* natural inter-word spacing like "事業者 法人番号" is preserved.
|
|
210
|
+
* 3. Trim and Markdown-escape pipes / newlines.
|
|
211
|
+
*/
|
|
212
|
+
export declare function compactCellText(s: string): string;
|
|
169
213
|
/**
|
|
170
214
|
* Report whether an annotation subtype is a markup annotation
|
|
171
215
|
* (ISO 32000-2 Table 171, "Markup" column).
|
|
@@ -175,4 +219,5 @@ export declare function isMarkupAnnotation(subtype: string): boolean;
|
|
|
175
219
|
* Analyze annotations across all pages.
|
|
176
220
|
*/
|
|
177
221
|
export declare function analyzeAnnotations(filePath: string, pages?: string): Promise<AnnotationsAnalysis>;
|
|
222
|
+
export {};
|
|
178
223
|
//# sourceMappingURL=pdfjs-service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pdfjs-service.d.ts","sourceRoot":"","sources":["../../src/services/pdfjs-service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAIL,KAAK,gBAAgB,EAEtB,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"pdfjs-service.d.ts","sourceRoot":"","sources":["../../src/services/pdfjs-service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAIL,KAAK,gBAAgB,EAEtB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,KAAK,EAEV,mBAAmB,EAEnB,qBAAqB,EACrB,QAAQ,EACR,WAAW,EACX,WAAW,EAEX,YAAY,EACb,MAAM,aAAa,CAAC;AAyBrB;;GAEG;AACH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAI9E;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAGtF;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAOxE;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,gBAAgB,EACrB,QAAQ,EAAE,MAAM,GACf,OAAO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M,CAAC,CAAC,CAc9B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAcjD;AA4CD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,MAAM,EAChB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,mBAAmB,CAAC,CAgF9B"}
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
import { getDocument, ImageKind, OPS, } from 'pdfjs-dist/legacy/build/pdf.mjs';
|
|
7
7
|
import { DEFAULT_SEARCH_CONTEXT } from '../constants.js';
|
|
8
8
|
import { getFileSize, readPdfFile, resolvePageNumbers } from '../utils/pdf-helpers.js';
|
|
9
|
-
import {
|
|
9
|
+
import { buildSpanActualTextMap, buildStructActualTextMap, foldActualText, } from './actual-text-service.js';
|
|
10
|
+
import { detectEncryption, loadWithPdfLib } from './pdflib-service.js';
|
|
10
11
|
/**
|
|
11
12
|
* pdfjs-dist verbosity level: ERRORS only (suppress warnings from stdout).
|
|
12
13
|
* pdfjs-dist's warn() uses console.log internally, which pollutes the
|
|
@@ -78,27 +79,54 @@ export async function getMetadataFromDoc(doc, filePath) {
|
|
|
78
79
|
fileSize,
|
|
79
80
|
};
|
|
80
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Open the same file with pdf-lib so `/ActualText` can be resolved.
|
|
84
|
+
*
|
|
85
|
+
* Returns `undefined` rather than throwing: a file pdf-lib cannot parse is
|
|
86
|
+
* still readable by pdfjs, and the pre-#18 behaviour (raw glyphs) is a valid
|
|
87
|
+
* fallback. Callers report the degradation instead of failing.
|
|
88
|
+
*/
|
|
89
|
+
async function loadActualTextResolution(filePath) {
|
|
90
|
+
try {
|
|
91
|
+
const libDoc = await loadWithPdfLib(filePath);
|
|
92
|
+
return {
|
|
93
|
+
libDoc,
|
|
94
|
+
structActualText: buildStructActualTextMap(libDoc),
|
|
95
|
+
encrypted: libDoc.isEncrypted,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
81
102
|
/**
|
|
82
103
|
* Extract text from a pre-loaded PDFDocumentProxy.
|
|
83
104
|
* Does NOT destroy the document — caller is responsible for lifecycle.
|
|
84
105
|
*/
|
|
85
|
-
export async function extractTextFromDoc(doc, pages, options = {}) {
|
|
106
|
+
export async function extractTextFromDoc(doc, pages, options = {}, resolution) {
|
|
86
107
|
const pageNumbers = resolvePageNumbers(pages, doc.numPages);
|
|
87
108
|
// 全ページを並列に処理(pdfjs-dist は並列ページアクセスが安全)
|
|
88
109
|
const results = await Promise.all(pageNumbers.map(async (pageNum) => {
|
|
89
110
|
const page = await doc.getPage(pageNum);
|
|
90
|
-
const text = await extractPageText(page, options);
|
|
111
|
+
const { text } = await extractPageText(page, options, resolution);
|
|
91
112
|
return { page: pageNum, text };
|
|
92
113
|
}));
|
|
93
114
|
return results;
|
|
94
115
|
}
|
|
95
116
|
/**
|
|
96
117
|
* Extract text from specified pages (1-based).
|
|
118
|
+
*
|
|
119
|
+
* Resolves `/ActualText` (ISO 32000-2 §14.9.4) on both of the paths the clause
|
|
120
|
+
* defines — see `actual-text-service`. The pdf-lib load that makes this possible
|
|
121
|
+
* is best-effort: a file it cannot parse still extracts, as raw glyphs.
|
|
97
122
|
*/
|
|
98
123
|
export async function extractText(filePath, pages, options = {}) {
|
|
99
|
-
const doc = await
|
|
124
|
+
const [doc, resolution] = await Promise.all([
|
|
125
|
+
loadDocument(filePath),
|
|
126
|
+
loadActualTextResolution(filePath),
|
|
127
|
+
]);
|
|
100
128
|
try {
|
|
101
|
-
return await extractTextFromDoc(doc, pages, options);
|
|
129
|
+
return await extractTextFromDoc(doc, pages, options, resolution);
|
|
102
130
|
}
|
|
103
131
|
finally {
|
|
104
132
|
await doc.destroy();
|
|
@@ -106,18 +134,32 @@ export async function extractText(filePath, pages, options = {}) {
|
|
|
106
134
|
}
|
|
107
135
|
/**
|
|
108
136
|
* Search for text across all pages.
|
|
137
|
+
*
|
|
138
|
+
* Searches the same text `read_text` returns, `/ActualText` included (#18), so
|
|
139
|
+
* the two tools can no longer disagree about whether a word is in the document.
|
|
109
140
|
*/
|
|
110
141
|
export async function searchText(filePath, query, contextChars = DEFAULT_SEARCH_CONTEXT, pages) {
|
|
111
|
-
const doc = await
|
|
142
|
+
const [doc, resolution] = await Promise.all([
|
|
143
|
+
loadDocument(filePath),
|
|
144
|
+
loadActualTextResolution(filePath),
|
|
145
|
+
]);
|
|
112
146
|
const lowerQuery = query.toLowerCase();
|
|
113
147
|
try {
|
|
114
148
|
const pageNumbers = resolvePageNumbers(pages, doc.numPages);
|
|
115
149
|
// 全ページのテキストを並列に抽出
|
|
116
150
|
const pageTexts = await Promise.all(pageNumbers.map(async (pageNum) => {
|
|
117
151
|
const page = await doc.getPage(pageNum);
|
|
118
|
-
const fullText = await extractPageText(page);
|
|
119
|
-
return { pageNum, fullText };
|
|
152
|
+
const { text: fullText, markedContentResolved } = await extractPageText(page, {}, resolution);
|
|
153
|
+
return { pageNum, fullText, markedContentResolved };
|
|
120
154
|
}));
|
|
155
|
+
const unresolvedPages = pageTexts.filter((p) => !p.markedContentResolved).map((p) => p.pageNum);
|
|
156
|
+
// Encryption disables both paths for the whole document, so it outranks the
|
|
157
|
+
// per-page alignment explanation whenever it applies.
|
|
158
|
+
const unresolvedReason = unresolvedPages.length === 0
|
|
159
|
+
? undefined
|
|
160
|
+
: resolution?.encrypted
|
|
161
|
+
? 'encrypted'
|
|
162
|
+
: 'unaligned';
|
|
121
163
|
// 抽出済みテキストからマッチを検索(CPU処理のみ、同期で十分)
|
|
122
164
|
const matches = [];
|
|
123
165
|
for (const { pageNum, fullText } of pageTexts) {
|
|
@@ -144,7 +186,7 @@ export async function searchText(filePath, query, contextChars = DEFAULT_SEARCH_
|
|
|
144
186
|
}
|
|
145
187
|
}
|
|
146
188
|
}
|
|
147
|
-
return matches;
|
|
189
|
+
return { matches, unresolvedPages, unresolvedReason };
|
|
148
190
|
}
|
|
149
191
|
finally {
|
|
150
192
|
await doc.destroy();
|
|
@@ -311,11 +353,26 @@ export async function extractImages(filePath, pages) {
|
|
|
311
353
|
* (typical of older 新旧対照表 PDFs); Tagged PDFs with proper `<Table>`
|
|
312
354
|
* markup should use `extract_tables` instead.
|
|
313
355
|
*/
|
|
314
|
-
async function extractPageText(page, options = {}) {
|
|
315
|
-
|
|
316
|
-
|
|
356
|
+
async function extractPageText(page, options = {}, resolution) {
|
|
357
|
+
// `includeMarkedContent` is what makes /ActualText resolution possible (#18):
|
|
358
|
+
// the markers say where each marked-content sequence starts and ends, which is
|
|
359
|
+
// what both replacement paths key off. The text items themselves are
|
|
360
|
+
// unaffected by the flag.
|
|
361
|
+
const content = await page.getTextContent({ includeMarkedContent: true });
|
|
362
|
+
const rawItems = content.items;
|
|
363
|
+
const beginCount = rawItems.filter((item) => item.type === 'beginMarkedContent' || item.type === 'beginMarkedContentProps').length;
|
|
364
|
+
let spanActualText;
|
|
365
|
+
let markedContentResolved = true;
|
|
366
|
+
if (resolution?.libDoc) {
|
|
367
|
+
spanActualText = buildSpanActualTextMap(resolution.libDoc, page.pageNumber - 1, beginCount);
|
|
368
|
+
markedContentResolved = spanActualText !== undefined;
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
markedContentResolved = beginCount === 0;
|
|
372
|
+
}
|
|
373
|
+
const items = foldActualText(rawItems, resolution?.structActualText ?? EMPTY_ACTUAL_TEXT, spanActualText);
|
|
317
374
|
if (items.length === 0)
|
|
318
|
-
return '';
|
|
375
|
+
return { text: '', markedContentResolved };
|
|
319
376
|
const splitColumns = options.splitColumns ?? 1;
|
|
320
377
|
if (splitColumns >= 2) {
|
|
321
378
|
// pdfjs-dist returns each page's `view` as [x1, y1, x2, y2] in user space.
|
|
@@ -330,10 +387,15 @@ async function extractPageText(page, options = {}) {
|
|
|
330
387
|
buckets[colIdx].push(item);
|
|
331
388
|
}
|
|
332
389
|
const columnTexts = buckets.map((bucket) => itemsToText(bucket, options));
|
|
333
|
-
return
|
|
390
|
+
return {
|
|
391
|
+
text: columnTexts.filter((s) => s.length > 0).join('\n\n'),
|
|
392
|
+
markedContentResolved,
|
|
393
|
+
};
|
|
334
394
|
}
|
|
335
|
-
return itemsToText(items, options);
|
|
395
|
+
return { text: itemsToText(items, options), markedContentResolved };
|
|
336
396
|
}
|
|
397
|
+
/** No structure-element replacements — shared so the empty case allocates nothing. */
|
|
398
|
+
const EMPTY_ACTUAL_TEXT = new Map();
|
|
337
399
|
/**
|
|
338
400
|
* Reorder a flat list of TextItems by Y descending, then X ascending,
|
|
339
401
|
* grouping into lines by Y proximity. Extracted from `extractPageText` so
|
|
@@ -360,21 +422,73 @@ function itemsToText(items, options = {}) {
|
|
|
360
422
|
let lastY = sorted[0].transform[5];
|
|
361
423
|
for (const item of sorted) {
|
|
362
424
|
const y = item.transform[5];
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
425
|
+
// ISO 32000-2 §14.9.4: consecutive sequences that each carry /ActualText
|
|
426
|
+
// "shall be treated as if no word break is present between them" — and a
|
|
427
|
+
// line break is a word break. This is the hyphenation case the clause's
|
|
428
|
+
// EXAMPLE is about, where the two halves are on different lines by
|
|
429
|
+
// construction, so the Y grouping has to yield to the requirement.
|
|
430
|
+
const weldToPrevious = item.replacement?.adjacentToPrevious === true &&
|
|
431
|
+
currentLine.at(-1)?.replacement !== undefined;
|
|
432
|
+
if (!weldToPrevious && Math.abs(y - lastY) > 2 && currentLine.length > 0) {
|
|
433
|
+
lines.push(currentLine);
|
|
434
|
+
currentLine = [];
|
|
368
435
|
}
|
|
369
|
-
currentLine.push(item
|
|
370
|
-
|
|
436
|
+
currentLine.push(item);
|
|
437
|
+
if (!weldToPrevious)
|
|
438
|
+
lastY = y;
|
|
371
439
|
}
|
|
372
|
-
if (currentLine.length > 0)
|
|
373
|
-
lines.push(currentLine
|
|
374
|
-
|
|
375
|
-
const text = lines.join('\n');
|
|
440
|
+
if (currentLine.length > 0)
|
|
441
|
+
lines.push(currentLine);
|
|
442
|
+
const text = lines.map(joinLine).join('\n');
|
|
376
443
|
return options.compactWhitespace ? compactRuns(text) : text;
|
|
377
444
|
}
|
|
445
|
+
/** Join one line's items, deciding each boundary with `separatorBefore`. */
|
|
446
|
+
function joinLine(line) {
|
|
447
|
+
let out = '';
|
|
448
|
+
for (let i = 0; i < line.length; i++) {
|
|
449
|
+
if (i > 0)
|
|
450
|
+
out += separatorBefore(line[i - 1], line[i]);
|
|
451
|
+
out += line[i].str;
|
|
452
|
+
}
|
|
453
|
+
return out;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Decide what goes between two items of the same line.
|
|
457
|
+
*
|
|
458
|
+
* The default is a space, which is what this extractor has always done: pdfjs
|
|
459
|
+
* splits a line into items at every state change, and for ordinary prose those
|
|
460
|
+
* boundaries usually are word boundaries.
|
|
461
|
+
*
|
|
462
|
+
* `/ActualText` is the exception, and §14.9.4 says why: the value "is a
|
|
463
|
+
* **character** substitution for the content enclosed", not a word or phrase
|
|
464
|
+
* substitution (NOTE 2 draws exactly this contrast with `Alt`). A `BDC` … `EMC`
|
|
465
|
+
* pair forces pdfjs to flush the current item, so a replacement is *always*
|
|
466
|
+
* split from its neighbours even mid-word — the clause's own EXAMPLE, `(Dru) Tj
|
|
467
|
+
* /Span <</ActualText (c)>> BDC (k-) Tj EMC (ker) Tj`, is three items that must
|
|
468
|
+
* read `Drucker`. A space there would be one this extractor invented.
|
|
469
|
+
*
|
|
470
|
+
* So a boundary involving a replacement drops the space when the two items are
|
|
471
|
+
* geometrically flush, and two consecutive replacements drop it unconditionally
|
|
472
|
+
* (that is the "no word break" requirement, which does not depend on geometry).
|
|
473
|
+
*/
|
|
474
|
+
function separatorBefore(previous, current) {
|
|
475
|
+
if (current.replacement?.adjacentToPrevious && previous.replacement)
|
|
476
|
+
return '';
|
|
477
|
+
if ((previous.replacement || current.replacement) && isFlush(previous, current))
|
|
478
|
+
return '';
|
|
479
|
+
return ' ';
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Whether `current` starts where `previous` ends, within a quarter of the line
|
|
483
|
+
* height. The tolerance absorbs kerning and the rounding in the item widths
|
|
484
|
+
* pdfjs reports; a real inter-word space is far wider.
|
|
485
|
+
*/
|
|
486
|
+
function isFlush(previous, current) {
|
|
487
|
+
const end = previous.transform[4] + previous.width;
|
|
488
|
+
const start = current.transform[4];
|
|
489
|
+
const tolerance = 0.25 * Math.max(previous.height, current.height, 1);
|
|
490
|
+
return start >= previous.transform[4] && start - end <= tolerance;
|
|
491
|
+
}
|
|
378
492
|
/**
|
|
379
493
|
* Issue #4: collapse whitespace runs (incl. fullwidth U+3000) to one ASCII
|
|
380
494
|
* space, trim each line, and drop lines that become empty after trimming.
|
|
@@ -391,6 +505,28 @@ function compactRuns(text) {
|
|
|
391
505
|
.filter((line) => line.length > 0)
|
|
392
506
|
.join('\n');
|
|
393
507
|
}
|
|
508
|
+
/**
|
|
509
|
+
* Whether the document claims to be tagged (`/MarkInfo /Marked true`).
|
|
510
|
+
*
|
|
511
|
+
* Was used by search_text to explain empty results on tagged documents (#15).
|
|
512
|
+
* Since #18 resolves `/ActualText` on both of its paths, an empty result no
|
|
513
|
+
* longer implies replacement text was missed, and the warning is keyed off the
|
|
514
|
+
* pages where resolution was actually skipped instead. Kept as a public probe:
|
|
515
|
+
* `get_metadata` reports the same flag, and the tests assert it.
|
|
516
|
+
*/
|
|
517
|
+
export async function isTaggedPdf(filePath) {
|
|
518
|
+
const doc = await loadDocument(filePath);
|
|
519
|
+
try {
|
|
520
|
+
const markInfo = await getMarkInfo(doc);
|
|
521
|
+
return markInfo?.Marked === true;
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
return false;
|
|
525
|
+
}
|
|
526
|
+
finally {
|
|
527
|
+
await doc.destroy();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
394
530
|
/**
|
|
395
531
|
* Get MarkInfo dictionary from the catalog.
|
|
396
532
|
*/
|
|
@@ -497,80 +633,6 @@ export async function analyzeTagsFromDoc(doc) {
|
|
|
497
633
|
roleCounts,
|
|
498
634
|
};
|
|
499
635
|
}
|
|
500
|
-
// Note: inspect_tags no longer uses a pdfjs per-page walk. It builds its tree
|
|
501
|
-
// from the document's StructTreeRoot (`analyzeTags` in struct-tree-service.ts)
|
|
502
|
-
// so that page-spanning elements stay whole — see that file's C-1 note.
|
|
503
|
-
// `analyzeTagsFromDoc` below is retained only for the deprecated validate_tagged.
|
|
504
|
-
// ─── extract_tables ────────────────────────────────────────────────────────
|
|
505
|
-
/**
|
|
506
|
-
* Extract tables from a Tagged PDF as structured rows/cells.
|
|
507
|
-
*
|
|
508
|
-
* The strategy is: for each page, walk the StructTree, identify `<Table>`
|
|
509
|
-
* subtrees, then walk down `<THead>/<TBody>/<TFoot>` → `<TR>` → `<TH>/<TD>`.
|
|
510
|
-
* Cell text is reconstructed by mapping each Span/P/Lbl/LBody leaf node's
|
|
511
|
-
* `id` (e.g. `p715R_mc4`) onto the corresponding `beginMarkedContentProps`
|
|
512
|
-
* boundary in `getTextContent({ includeMarkedContent: true })`.
|
|
513
|
-
*
|
|
514
|
-
* Untagged PDFs return `isTagged: false`, an empty `tables` array, and a
|
|
515
|
-
* `note` recommending the column-aware extraction (planned in a future
|
|
516
|
-
* release) as the fallback for two-column layouts without a structure tree.
|
|
517
|
-
*
|
|
518
|
-
* Cell text is post-processed:
|
|
519
|
-
* - Newlines (`hasEOL`) become single spaces.
|
|
520
|
-
* - Repeated whitespace runs (including U+3000 fullwidth space) collapse to one.
|
|
521
|
-
* - Per-character kerning spaces (e.g. `"消 費 税 法"`) are folded
|
|
522
|
-
* by removing single ASCII spaces between two CJK characters.
|
|
523
|
-
*/
|
|
524
|
-
export async function extractTablesFromDoc(doc, pages) {
|
|
525
|
-
const markInfo = await getMarkInfo(doc);
|
|
526
|
-
const isTagged = markInfo?.Marked === true;
|
|
527
|
-
if (!isTagged) {
|
|
528
|
-
return {
|
|
529
|
-
isTagged: false,
|
|
530
|
-
tables: [],
|
|
531
|
-
totalTables: 0,
|
|
532
|
-
pagesScanned: 0,
|
|
533
|
-
note: 'Document is not tagged. extract_tables relies on /MarkInfo /Marked true ' +
|
|
534
|
-
'and a StructTree. For untagged two-column PDFs, fall back to a ' +
|
|
535
|
-
'column-aware reading strategy (see pdf-reader-mcp Issue #3).',
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
|
-
const pageNumbers = resolvePageNumbers(pages, doc.numPages);
|
|
539
|
-
const perPage = await Promise.all(pageNumbers.map(async (pageNum) => {
|
|
540
|
-
const page = await doc.getPage(pageNum);
|
|
541
|
-
try {
|
|
542
|
-
const [tree, textContent] = await Promise.all([
|
|
543
|
-
page.getStructTree(),
|
|
544
|
-
page.getTextContent({ includeMarkedContent: true }),
|
|
545
|
-
]);
|
|
546
|
-
if (!tree)
|
|
547
|
-
return [];
|
|
548
|
-
const idToText = buildIdToTextMap(textContent.items);
|
|
549
|
-
const tables = [];
|
|
550
|
-
collectTables(tree, pageNum, idToText, tables);
|
|
551
|
-
return tables;
|
|
552
|
-
}
|
|
553
|
-
catch {
|
|
554
|
-
return [];
|
|
555
|
-
}
|
|
556
|
-
}));
|
|
557
|
-
const tables = perPage.flat();
|
|
558
|
-
return {
|
|
559
|
-
isTagged: true,
|
|
560
|
-
tables,
|
|
561
|
-
totalTables: tables.length,
|
|
562
|
-
pagesScanned: pageNumbers.length,
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
export async function extractTables(filePath, pages) {
|
|
566
|
-
const doc = await loadDocument(filePath);
|
|
567
|
-
try {
|
|
568
|
-
return await extractTablesFromDoc(doc, pages);
|
|
569
|
-
}
|
|
570
|
-
finally {
|
|
571
|
-
await doc.destroy();
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
636
|
/**
|
|
575
637
|
* Build a map from a marked-content `id` (e.g. `p715R_mc4`) to the concatenated
|
|
576
638
|
* raw text inside the corresponding `beginMarkedContentProps`/`endMarkedContent`
|
|
@@ -700,82 +762,6 @@ export async function buildDocumentIdToTextMap(doc) {
|
|
|
700
762
|
}
|
|
701
763
|
return merged;
|
|
702
764
|
}
|
|
703
|
-
/** Walk the StructTree and append every `<Table>` subtree as an ExtractedTable. */
|
|
704
|
-
function collectTables(node, pageNum, idToText, out) {
|
|
705
|
-
if (node.type === 'content')
|
|
706
|
-
return;
|
|
707
|
-
if (node.role === 'Table') {
|
|
708
|
-
const headerRows = [];
|
|
709
|
-
const bodyRows = [];
|
|
710
|
-
const footerRows = [];
|
|
711
|
-
for (const child of node.children ?? []) {
|
|
712
|
-
if (child.type === 'content')
|
|
713
|
-
continue;
|
|
714
|
-
if (child.role === 'THead') {
|
|
715
|
-
appendTableRowsFromSection(child, idToText, headerRows);
|
|
716
|
-
}
|
|
717
|
-
else if (child.role === 'TBody') {
|
|
718
|
-
appendTableRowsFromSection(child, idToText, bodyRows);
|
|
719
|
-
}
|
|
720
|
-
else if (child.role === 'TFoot') {
|
|
721
|
-
appendTableRowsFromSection(child, idToText, footerRows);
|
|
722
|
-
}
|
|
723
|
-
else if (child.role === 'TR') {
|
|
724
|
-
// Tables sometimes omit THead/TBody and place TRs directly under <Table>.
|
|
725
|
-
const row = buildRowFromTR(child, idToText);
|
|
726
|
-
if (row)
|
|
727
|
-
bodyRows.push(row);
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
// `out` is a per-page accumulator passed in by the caller, so
|
|
731
|
-
// `out.length + 1` is the next index within this page (1-based).
|
|
732
|
-
out.push({
|
|
733
|
-
page: pageNum,
|
|
734
|
-
index: out.length + 1,
|
|
735
|
-
headerRows,
|
|
736
|
-
bodyRows,
|
|
737
|
-
footerRows,
|
|
738
|
-
});
|
|
739
|
-
return; // Don't recurse into a Table — nested tables are uncommon and
|
|
740
|
-
// would confuse the per-page index. (Add nested-table support later.)
|
|
741
|
-
}
|
|
742
|
-
for (const child of node.children ?? []) {
|
|
743
|
-
collectTables(child, pageNum, idToText, out);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
function appendTableRowsFromSection(section, idToText, out) {
|
|
747
|
-
for (const child of section.children ?? []) {
|
|
748
|
-
if (child.type === 'content')
|
|
749
|
-
continue;
|
|
750
|
-
if (child.role === 'TR') {
|
|
751
|
-
const row = buildRowFromTR(child, idToText);
|
|
752
|
-
if (row)
|
|
753
|
-
out.push(row);
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
function buildRowFromTR(tr, idToText) {
|
|
758
|
-
const cells = [];
|
|
759
|
-
for (const child of tr.children ?? []) {
|
|
760
|
-
if (child.type === 'content')
|
|
761
|
-
continue;
|
|
762
|
-
if (child.role === 'TH' || child.role === 'TD') {
|
|
763
|
-
const text = compactCellText(collectTextUnder(child, idToText));
|
|
764
|
-
cells.push({ text, isHeader: child.role === 'TH' });
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
return cells.length === 0 ? null : { cells };
|
|
768
|
-
}
|
|
769
|
-
function collectTextUnder(node, idToText) {
|
|
770
|
-
if (node.type === 'content') {
|
|
771
|
-
return node.id ? (idToText.get(node.id) ?? '') : '';
|
|
772
|
-
}
|
|
773
|
-
const parts = [];
|
|
774
|
-
for (const child of node.children ?? []) {
|
|
775
|
-
parts.push(collectTextUnder(child, idToText));
|
|
776
|
-
}
|
|
777
|
-
return parts.join(' ');
|
|
778
|
-
}
|
|
779
765
|
/**
|
|
780
766
|
* Normalise raw cell text:
|
|
781
767
|
* 0. Resolve line breaks (CJK-aware) — a break between two CJK characters is
|
|
@@ -788,7 +774,7 @@ function collectTextUnder(node, idToText) {
|
|
|
788
774
|
* natural inter-word spacing like "事業者 法人番号" is preserved.
|
|
789
775
|
* 3. Trim and Markdown-escape pipes / newlines.
|
|
790
776
|
*/
|
|
791
|
-
function compactCellText(s) {
|
|
777
|
+
export function compactCellText(s) {
|
|
792
778
|
if (!s)
|
|
793
779
|
return '';
|
|
794
780
|
// Step 0: CJK-aware line-break resolution (see resolveLineBreaks). idToText now
|