llm-large-files 0.1.0 → 0.3.0

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.
Files changed (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Cuts pages out of a PDF into a small PDF of their own, so a model can be shown the real pages.
3
+ * Needs the optional dependency "@cantoo/pdf-lib".
4
+ *
5
+ * Copying pages the way a PDF library offers it is not enough. A link to another page takes that
6
+ * page's content along, and a resource dictionary that pages share takes along every image it
7
+ * lists: the contents page of a report came out at 89% of its file. So, before copying:
8
+ * - every page that is not wanted is replaced by an empty one, so a reference to it costs nothing;
9
+ * - a wanted page gets its own resource dictionary, without the images it does not paint.
10
+ */
11
+ import { getHeapStatistics } from "node:v8";
12
+ import type { PDFContext, PDFDict, PDFObject, PDFPage, PDFPageLeaf } from "@cantoo/pdf-lib";
13
+ import { formatBytes } from "./plan.js";
14
+
15
+ type PdfLibrary = typeof import("@cantoo/pdf-lib");
16
+
17
+ export type PageCut = {
18
+ /** A PDF with pages `from` to `to` of the original. */
19
+ bytes: Uint8Array;
20
+ from: number;
21
+ /** The last page in the cut. Lower than the page asked for when the pages did not all fit. */
22
+ to: number;
23
+ /** How many pages the original has. */
24
+ pageCount: number;
25
+ };
26
+
27
+ /** Objects parsed between two pauses that let other work on the server run. */
28
+ const OBJECTS_PER_TICK = 4_000;
29
+ /** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
30
+ const BYTES_PER_OBJECT = 1_700;
31
+ /** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
32
+ const MAX_OBJECTS = 1_000_000;
33
+ /** Content streams larger than this are not read to find out which images a page paints. */
34
+ const MAX_CONTENT_BYTES = 4 * 1024 * 1024;
35
+ /** Not needed to show a page, and able to hold a lot: editor data, article threads, actions, a thumbnail. */
36
+ const DROPPED_PAGE_ENTRIES = ["PieceInfo", "B", "AA", "Thumb"];
37
+ const UNREADABLE = "This PDF could not be read to cut pages from it. It may be damaged.";
38
+
39
+ /** Bytes as a string of the same length: each byte becomes the character with that code. */
40
+ export function latin1(bytes: Uint8Array): string {
41
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
42
+ }
43
+
44
+ export async function loadPdfLibrary(): Promise<PdfLibrary> {
45
+ try {
46
+ return await import("@cantoo/pdf-lib");
47
+ } catch {
48
+ throw new Error("Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The content of a stream as text, one character per byte, or undefined when it cannot be had:
54
+ * the stream is larger than `maxBytes`, uses a filter the library does not undo, or is damaged.
55
+ */
56
+ export function decodeContent(library: PdfLibrary, context: PDFContext, stream: PDFObject | undefined, maxBytes: number): string | undefined {
57
+ const { PDFArray, PDFDict, PDFName, PDFRawStream, decodePDFRawStream } = library;
58
+ if (!(stream instanceof PDFRawStream) || stream.contents.length > maxBytes) return undefined;
59
+ // The library does not undo a predictor, and would hand back bytes that are not the content.
60
+ const parameters = stream.dict.lookup(PDFName.of("DecodeParms"));
61
+ const list = parameters instanceof PDFArray ? parameters.asArray().map((entry) => context.lookup(entry)) : [parameters];
62
+ if (list.some((entry) => entry instanceof PDFDict && entry.has(PDFName.of("Predictor")))) return undefined;
63
+ try {
64
+ return latin1(decodePDFRawStream(stream).decode());
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * How many objects the file says it has: the largest /Size in its trailer or in its
72
+ * cross-reference stream. Undefined when neither is found where a well-formed file has it.
73
+ */
74
+ export function declaredObjectCount(bytes: Uint8Array): number | undefined {
75
+ const text = (start: number, end: number) => latin1(bytes.subarray(Math.max(0, start), Math.min(bytes.length, end)));
76
+ let found = 0;
77
+ const read = (chunk: string) => {
78
+ for (const match of chunk.matchAll(/\/Size[\s\0]+(\d{1,12})/g)) found = Math.max(found, Number(match[1]));
79
+ };
80
+ const tail = text(bytes.length - 2048, bytes.length);
81
+ read(tail);
82
+ // A cross-reference stream keeps /Size in its own dictionary, which can be far from the end.
83
+ const start = [...tail.matchAll(/startxref[\s\0]+(\d{1,15})/g)].at(-1);
84
+ if (start) {
85
+ const offset = Number(start[1]);
86
+ if (offset < bytes.length) read(text(offset, offset + 2048));
87
+ }
88
+ return found > 0 ? found : undefined;
89
+ }
90
+
91
+ /**
92
+ * The library reads the whole file into objects before anything can be done with a page. The
93
+ * number of objects a file declares, when that is more than `most` or more than this process can
94
+ * hold; undefined when the file can be read.
95
+ */
96
+ export function tooManyObjects(original: Uint8Array, most = MAX_OBJECTS): number | undefined {
97
+ const objects = declaredObjectCount(original);
98
+ if (objects === undefined) return undefined;
99
+ const heap = getHeapStatistics();
100
+ const free = heap.heap_size_limit - heap.used_heap_size;
101
+ return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
102
+ }
103
+
104
+ /** A PDF name as the characters it stands for, so that "#20" and a space are the same name. */
105
+ export function canonicalName(raw: string): string {
106
+ let name = raw;
107
+ // Until nothing changes: a library may keep an escape it did not decode as literal characters.
108
+ for (;;) {
109
+ const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
110
+ if (next === name) return name;
111
+ name = next;
112
+ }
113
+ }
114
+
115
+ const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
116
+ /** `/Name Do`: the operator that paints an image or a form. */
117
+ const PAINTED = new RegExp(`/(${REGULAR_CHARACTER}*)[\\x00\\t\\n\\f\\r ]+Do(?!${REGULAR_CHARACTER})`, "g");
118
+
119
+ /**
120
+ * Gives a page its own resource dictionary without the images it does not paint. FPDF, TCPDF,
121
+ * jsPDF and others list every image of the file in one dictionary that all pages share.
122
+ *
123
+ * It only keeps more than is needed, never less: a name found anywhere in the content counts as
124
+ * painted, and nothing is dropped unless every stream that can name an image of this dictionary
125
+ * was read.
126
+ */
127
+ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPageLeaf): void {
128
+ const { PDFArray, PDFDict, PDFName, PDFStream } = library;
129
+ const key = (value: string) => PDFName.of(value);
130
+ const resources = page.Resources();
131
+ if (!resources) return;
132
+ const xobjects = resources.lookup(key("XObject"));
133
+ if (!(xobjects instanceof PDFDict)) return;
134
+ const entries = xobjects.entries();
135
+ if (entries.length < 2) return;
136
+ const byName = new Map(entries.map(([name, value]) => [canonicalName(name.asString().slice(1)), value]));
137
+
138
+ let readable = true;
139
+ /** Names found in content that looks them up in this page's dictionary, still to be followed. */
140
+ const found: string[] = [];
141
+ const decode = (stream: PDFObject | undefined) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
142
+ const read = (text: string) => {
143
+ for (const match of text.matchAll(PAINTED)) found.push(canonicalName(match[1]!));
144
+ };
145
+ const readStream = (stream: PDFObject | undefined) => {
146
+ const text = decode(stream);
147
+ if (text === undefined) readable = false;
148
+ else read(text);
149
+ };
150
+ // A form, a pattern, a Type 3 glyph or an annotation's appearance that has no resource dictionary
151
+ // of its own (old PDFs allow that), or has this page's, takes its names from this page's
152
+ // dictionary: read it. One with its own dictionary is independent, but can hold more content of
153
+ // the first kind: look inside.
154
+ const seen = new Set<PDFDict>();
155
+ const content = (object: PDFObject | undefined) => {
156
+ if (!(object instanceof PDFStream)) return;
157
+ const own = object.dict.lookup(key("Resources"));
158
+ if (own instanceof PDFDict && own !== resources) inside(own);
159
+ else readStream(object);
160
+ };
161
+ const patternsAndFonts = (dictionary: PDFDict) => {
162
+ const patterns = dictionary.lookup(key("Pattern"));
163
+ if (patterns instanceof PDFDict) for (const [, value] of patterns.entries()) content(context.lookup(value));
164
+ const fonts = dictionary.lookup(key("Font"));
165
+ if (!(fonts instanceof PDFDict)) return;
166
+ for (const [, value] of fonts.entries()) {
167
+ const font = context.lookup(value);
168
+ if (!(font instanceof PDFDict) || font.lookup(key("Subtype")) !== key("Type3")) continue;
169
+ const own = font.lookup(key("Resources"));
170
+ if (own instanceof PDFDict && own !== resources) {
171
+ inside(own);
172
+ continue;
173
+ }
174
+ const glyphs = font.lookup(key("CharProcs"));
175
+ if (glyphs instanceof PDFDict) for (const [, glyph] of glyphs.entries()) readStream(context.lookup(glyph));
176
+ }
177
+ };
178
+ const inside = (dictionary: PDFDict) => {
179
+ if (seen.has(dictionary)) return;
180
+ seen.add(dictionary);
181
+ const forms = dictionary.lookup(key("XObject"));
182
+ if (forms instanceof PDFDict) {
183
+ for (const [, value] of forms.entries()) {
184
+ const object = context.lookup(value);
185
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
186
+ }
187
+ }
188
+ patternsAndFonts(dictionary);
189
+ };
190
+
191
+ // 1. The page's own content. Split over several streams it is still one text: "/Im1" may end one
192
+ // stream and "Do" start the next.
193
+ const contents = page.Contents();
194
+ const streams = contents instanceof PDFArray ? contents.asArray().map((entry) => context.lookup(entry)) : contents ? [contents] : [];
195
+ const parts = streams.map(decode);
196
+ if (parts.includes(undefined)) readable = false;
197
+ else read(parts.join(" "));
198
+ // 2. The page's patterns and Type 3 fonts, and what its annotations show. Which of them the page
199
+ // uses is not worked out: all count.
200
+ patternsAndFonts(resources);
201
+ const annotations = page.Annots();
202
+ if (annotations) {
203
+ for (const entry of annotations.asArray()) {
204
+ const annotation = context.lookup(entry);
205
+ const appearances = annotation instanceof PDFDict ? annotation.lookup(key("AP")) : undefined;
206
+ if (!(appearances instanceof PDFDict)) continue;
207
+ for (const [, value] of appearances.entries()) {
208
+ const appearance = context.lookup(value);
209
+ if (appearance instanceof PDFStream) content(appearance);
210
+ else if (appearance instanceof PDFDict) for (const [, state] of appearance.entries()) content(context.lookup(state));
211
+ }
212
+ }
213
+ }
214
+ // 3. Follow what is painted: a form that is painted paints more.
215
+ const painted = new Set<string>();
216
+ while (found.length > 0) {
217
+ const next = found.pop()!;
218
+ if (painted.has(next)) continue;
219
+ painted.add(next);
220
+ const value = byName.get(next);
221
+ const object = value ? context.lookup(value) : undefined;
222
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
223
+ }
224
+ if (!readable) return;
225
+
226
+ const kept = entries.filter(([name]) => painted.has(canonicalName(name.asString().slice(1))));
227
+ if (kept.length === entries.length) return;
228
+ const fewer = context.obj({});
229
+ for (const [name, value] of kept) fewer.set(name, value);
230
+ const own = resources.clone(context);
231
+ own.set(key("XObject"), fewer);
232
+ page.set(key("Resources"), own);
233
+ }
234
+
235
+ /** A PDF with pages `from` to `last` of `source`. Changes `source`: use it only for smaller cuts afterwards. */
236
+ async function copyPages(library: PdfLibrary, source: import("@cantoo/pdf-lib").PDFDocument, pages: PDFPage[], from: number, last: number): Promise<Uint8Array> {
237
+ const { PDFDocument, PDFName, PDFNull, PDFObjectCopier, PDFPage: Page, PDFPageLeaf: Leaf } = library;
238
+ const { context } = source;
239
+ const wanted = pages.slice(from - 1, last);
240
+ const wantedReferences = new Set(wanted.map((page) => page.ref));
241
+ // Every other page becomes nothing, so a link, a form field or a thread that leads to it copies
242
+ // a few bytes and not the page. (Null, not an empty page: the cut must not hold objects that
243
+ // call themselves pages and are not among its pages.)
244
+ for (const page of pages) {
245
+ if (!wantedReferences.has(page.ref)) context.assign(page.ref, PDFNull);
246
+ }
247
+ for (const page of wanted) {
248
+ for (const entry of DROPPED_PAGE_ENTRIES) page.node.delete(PDFName.of(entry));
249
+ try {
250
+ dropUnusedImages(library, context, page.node);
251
+ } catch {
252
+ // An unusual resource dictionary: the page is copied with everything it lists.
253
+ }
254
+ }
255
+ const target = await PDFDocument.create({ updateMetadata: false });
256
+ // One copier for everything, and each page copied through its reference: an annotation's /P then
257
+ // points at the copied page, and the layer settings below name the layers the pages use.
258
+ const copier = PDFObjectCopier.for(context, target.context);
259
+ for (const page of wanted) {
260
+ const reference = copier.copy(page.ref);
261
+ const node = target.context.lookup(reference);
262
+ if (!(node instanceof Leaf)) throw new Error("A page of this PDF is not a page object.");
263
+ target.addPage(Page.of(node, reference, target));
264
+ }
265
+ // Without these, a layer that the file hides would be shown.
266
+ const layers = source.catalog.get(PDFName.of("OCProperties"));
267
+ if (layers) target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
268
+ return target.save();
269
+ }
270
+
271
+ /**
272
+ * Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
273
+ * `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
274
+ * Throws an Error whose message can be shown to a model: for a file that cannot be opened, a page
275
+ * that does not exist, and a first page that does not fit by itself.
276
+ *
277
+ * `expectedPages` is the page count the text of the file was extracted with. The text came from
278
+ * another PDF reader; if the two do not count the same pages, a page number may not mean the same
279
+ * page in both, and showing the wrong page is worse than showing none.
280
+ */
281
+ export async function cutPdfPages(original: Uint8Array, from: number, to: number, maxBytes: number, expectedPages?: number): Promise<PageCut> {
282
+ const library = await loadPdfLibrary();
283
+ // Refuse a file that says it has more objects than this process can hold, instead of running out of memory.
284
+ const objects = tooManyObjects(original);
285
+ if (objects !== undefined) throw new Error(`This PDF has ${objects.toLocaleString("en-US")} objects, too many to cut pages from it in memory.`);
286
+ let source: import("@cantoo/pdf-lib").PDFDocument;
287
+ let pages: PDFPage[];
288
+ try {
289
+ // An empty password opens the many PDFs that are encrypted only to restrict printing or copying.
290
+ source = await library.PDFDocument.load(original, { updateMetadata: false, parseSpeed: OBJECTS_PER_TICK, password: "" });
291
+ pages = source.getPages();
292
+ } catch (error) {
293
+ const needsPassword = /password/i.test(error instanceof Error ? error.message : String(error));
294
+ throw new Error(needsPassword ? "This PDF needs a password to open, so its pages cannot be shown." : UNREADABLE);
295
+ }
296
+ const pageCount = pages.length;
297
+ // A damaged file can be read as a file without pages: the library skips what it cannot parse.
298
+ if (pageCount === 0) throw new Error(UNREADABLE);
299
+ if (expectedPages !== undefined && pageCount !== expectedPages) {
300
+ throw new Error(`The pages of this PDF could not be matched to its text (${pageCount} pages against ${expectedPages}), so they cannot be shown.`);
301
+ }
302
+ if (from < 1 || from > pageCount) throw new Error(`There is no page ${from}: the file has ${pageCount} ${pageCount === 1 ? "page" : "pages"}.`);
303
+ let smallest = 0;
304
+ for (let last = Math.min(Math.max(to, from), pageCount); last >= from; last--) {
305
+ let bytes: Uint8Array;
306
+ try {
307
+ bytes = await copyPages(library, source, pages, from, last);
308
+ } catch {
309
+ throw new Error("The pages could not be cut out of this PDF. It may be damaged.");
310
+ }
311
+ if (bytes.length <= maxBytes) return { bytes, from, to: last, pageCount };
312
+ smallest = bytes.length;
313
+ }
314
+ throw new Error(`Page ${from} is ${formatBytes(smallest)} as a file, more than the ${formatBytes(Math.max(0, maxBytes))} that fit in this request.`);
315
+ }
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Finds the pages of a PDF that show a picture or a drawing, so their text can say so.
3
+ *
4
+ * It reads the structure of the file and decodes no image. Each page's content is a small program:
5
+ * this follows its transformation matrix, and notes every image it paints with the box it is
6
+ * painted in, and every shape it fills with its colour. Asking a PDF renderer for the same costs
7
+ * 60 to 180 ms a photo, because the renderer decodes each one: 13 seconds for 72 photos that this
8
+ * goes through in a tenth of a second.
9
+ *
10
+ * Needs the optional dependency "@cantoo/pdf-lib". Without it, no page is marked.
11
+ */
12
+ import type { PDFContext, PDFDict, PDFObject } from "@cantoo/pdf-lib";
13
+ import { decodeContent, loadPdfLibrary, tooManyObjects } from "./pdf-pages.js";
14
+
15
+ type PdfLibrary = typeof import("@cantoo/pdf-lib");
16
+ /** `[x0, y0, x1, y1]` with x0 <= x1 and y0 <= y1. */
17
+ export type Box = [number, number, number, number];
18
+ /** `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. */
19
+ type Matrix = readonly number[];
20
+
21
+ /** What the text extractor knows about a page, in the units of the page itself. */
22
+ export type PageGeometry = {
23
+ /** The visible part of the page: `page.view` in pdf.js. */
24
+ view: readonly number[];
25
+ /** From page units to the coordinates `tables` are in: `page.getViewport({ scale: 1 }).transform`. */
26
+ transform: readonly number[];
27
+ /** The tables found on the page. A table's borders and shading are drawings too, and are not pictures. */
28
+ tables: readonly Box[];
29
+ };
30
+
31
+ /** A file with more objects than this takes over two seconds to read into objects. */
32
+ const MAX_OBJECTS = 150_000;
33
+ /** Time for everything after the file is read into objects. Past it, no page is marked. */
34
+ const TIME_LIMIT_MS = 5_000;
35
+ /** A content stream past this size (compressed) is not text or a table: it is a drawing. */
36
+ const MAX_CONTENT_BYTES = 2 * 1024 * 1024;
37
+ /** Images must cover this share of the page together. A logo covers about 1%, a small figure 4%. */
38
+ const PICTURE_SHARE = 0.03;
39
+ /** An image on this share of the pages (and on three at least) is a logo, a background, a watermark. */
40
+ const FURNITURE_SHARE = 0.3;
41
+ /** A chart or a diagram fills shapes in several colours. A table shades its cells in one or two. */
42
+ const DRAWING_COLOURS = 3;
43
+ const MAX_SHAPES = 20_000;
44
+ const MAX_FORM_DEPTH = 4;
45
+
46
+ type Image = { id: number; box: Box };
47
+ type Shape = { box: Box; fill: string };
48
+ type Graphics = { images: Image[]; shapes: Shape[]; tooLarge: boolean };
49
+
50
+ const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
51
+ /** Applies `first`, then `second`. */
52
+ function multiply(first: Matrix, second: Matrix): number[] {
53
+ return [
54
+ first[0]! * second[0]! + first[1]! * second[2]!, first[0]! * second[1]! + first[1]! * second[3]!,
55
+ first[2]! * second[0]! + first[3]! * second[2]!, first[2]! * second[1]! + first[3]! * second[3]!,
56
+ first[4]! * second[0]! + first[5]! * second[2]! + second[4]!, first[4]! * second[1]! + first[5]! * second[3]! + second[5]!,
57
+ ];
58
+ }
59
+ const mapX = (matrix: Matrix, x: number, y: number) => matrix[0]! * x + matrix[2]! * y + matrix[4]!;
60
+ const mapY = (matrix: Matrix, x: number, y: number) => matrix[1]! * x + matrix[3]! * y + matrix[5]!;
61
+
62
+ // Character codes of PDF syntax.
63
+ const isWhite = (code: number) => code === 32 || code === 10 || code === 13 || code === 9 || code === 12 || code === 0;
64
+ const isDelimiter = (code: number) => code === 40 || code === 41 || code === 60 || code === 62 || code === 91 || code === 93 || code === 123 || code === 125 || code === 47 || code === 37;
65
+ /** The end of the data of an inline image: "EI" between white space. */
66
+ const INLINE_IMAGE_END = /[\x00\t\n\f\r ]EI(?![^\x00\t\n\f\r /\[\]<>(){}%])/g;
67
+
68
+ /**
69
+ * Runs the content of a page, or of a form it paints, and adds what it draws to `found`.
70
+ * It understands just enough: the matrix (q, Q, cm), paths and how they are painted, the fill
71
+ * colour, and Do. Text, clipping and everything else pass through unread.
72
+ */
73
+ function run(library: PdfLibrary, context: PDFContext, content: string, resources: PDFDict | undefined, matrix: Matrix, found: Graphics, depth: number, open: Set<PDFObject>): void {
74
+ const { PDFArray, PDFDict, PDFName, PDFNumber, PDFRef, PDFStream } = library;
75
+ const saved: Array<{ ctm: Matrix; fill: string }> = [];
76
+ let ctm = matrix;
77
+ let fill = "g:0";
78
+ let numbers: number[] = [];
79
+ let name: string | undefined;
80
+ /** The path under construction, in page units. */
81
+ let path: Box | undefined;
82
+ const point = (x: number, y: number) => {
83
+ const px = mapX(ctm, x, y);
84
+ const py = mapY(ctm, x, y);
85
+ if (!path) path = [px, py, px, py];
86
+ else {
87
+ if (px < path[0]) path[0] = px;
88
+ if (py < path[1]) path[1] = py;
89
+ if (px > path[2]) path[2] = px;
90
+ if (py > path[3]) path[3] = py;
91
+ }
92
+ };
93
+ const points = (count: number) => {
94
+ if (numbers.length < count * 2) return;
95
+ for (let index = numbers.length - count * 2; index < numbers.length; index += 2) point(numbers[index]!, numbers[index + 1]!);
96
+ };
97
+
98
+ const length = content.length;
99
+ let at = 0;
100
+ while (at < length) {
101
+ let code = content.charCodeAt(at);
102
+ if (isWhite(code)) {
103
+ at++;
104
+ continue;
105
+ }
106
+ if (code === 37) { // % a comment, to the end of the line
107
+ while (at < length && content.charCodeAt(at) !== 10 && content.charCodeAt(at) !== 13) at++;
108
+ continue;
109
+ }
110
+ if (code === 40) { // ( a string ), which may hold anything, balanced parentheses included
111
+ let nesting = 1;
112
+ at++;
113
+ while (at < length && nesting > 0) {
114
+ code = content.charCodeAt(at);
115
+ if (code === 92) at++;
116
+ else if (code === 40) nesting++;
117
+ else if (code === 41) nesting--;
118
+ at++;
119
+ }
120
+ continue;
121
+ }
122
+ if (code === 60) { // << a dictionary, or <a hex string>
123
+ if (content.charCodeAt(at + 1) === 60) at += 2;
124
+ else {
125
+ const end = content.indexOf(">", at);
126
+ at = end === -1 ? length : end + 1;
127
+ }
128
+ continue;
129
+ }
130
+ if (code === 62 || code === 91 || code === 93 || code === 123 || code === 125) { // > [ ] { }
131
+ at++;
132
+ continue;
133
+ }
134
+ const start = at++;
135
+ while (at < length && !isWhite(code = content.charCodeAt(at)) && !isDelimiter(code)) at++;
136
+ const token = content.slice(start, at);
137
+ const first = token.charCodeAt(0);
138
+ if (first === 47) { // /Name
139
+ name = token.slice(1);
140
+ continue;
141
+ }
142
+ if ((first >= 48 && first <= 57) || first === 45 || first === 43 || first === 46) {
143
+ const number = Number(token);
144
+ if (!Number.isNaN(number)) {
145
+ numbers.push(number);
146
+ continue;
147
+ }
148
+ }
149
+ switch (token) {
150
+ case "q":
151
+ saved.push({ ctm, fill });
152
+ break;
153
+ case "Q": {
154
+ const state = saved.pop();
155
+ if (state) ({ ctm, fill } = state);
156
+ break;
157
+ }
158
+ case "cm":
159
+ if (numbers.length >= 6) ctm = multiply(numbers.slice(-6), ctm);
160
+ break;
161
+ case "re":
162
+ if (numbers.length >= 4) {
163
+ const [x, y, width, height] = numbers.slice(-4) as [number, number, number, number];
164
+ point(x, y);
165
+ point(x + width, y);
166
+ point(x, y + height);
167
+ point(x + width, y + height);
168
+ }
169
+ break;
170
+ case "m": case "l":
171
+ points(1);
172
+ break;
173
+ case "c":
174
+ points(3);
175
+ break;
176
+ case "v": case "y":
177
+ points(2);
178
+ break;
179
+ case "f": case "F": case "f*": case "B": case "B*": case "b": case "b*":
180
+ if (path && found.shapes.length < MAX_SHAPES) found.shapes.push({ box: path, fill });
181
+ path = undefined;
182
+ break;
183
+ case "S": case "s": case "n":
184
+ path = undefined;
185
+ break;
186
+ case "g":
187
+ if (numbers.length >= 1) fill = `g:${numbers.at(-1)}`;
188
+ break;
189
+ case "rg":
190
+ if (numbers.length >= 3) fill = `rgb:${numbers.slice(-3).join(",")}`;
191
+ break;
192
+ case "k":
193
+ if (numbers.length >= 4) fill = `cmyk:${numbers.slice(-4).join(",")}`;
194
+ break;
195
+ case "sc": case "scn":
196
+ // The colour space is not followed: three numbers are read as red, green and blue.
197
+ fill = numbers.length === 1 ? `g:${numbers[0]}` : numbers.length === 3 ? `rgb:${numbers.join(",")}` : numbers.length === 4 ? `cmyk:${numbers.join(",")}` : "other";
198
+ break;
199
+ case "ID": { // the data of an inline image: bytes that are not content
200
+ INLINE_IMAGE_END.lastIndex = at;
201
+ at = INLINE_IMAGE_END.exec(content) ? INLINE_IMAGE_END.lastIndex : length;
202
+ break;
203
+ }
204
+ case "Do": {
205
+ const group = resources?.lookup(PDFName.of("XObject"));
206
+ const value = group instanceof PDFDict && name !== undefined ? group.get(PDFName.of(name)) : undefined;
207
+ const object = value ? context.lookup(value) : undefined;
208
+ if (!(object instanceof PDFStream)) break;
209
+ const subtype = object.dict.lookup(PDFName.of("Subtype"));
210
+ if (subtype === PDFName.of("Image")) {
211
+ // An image fills the unit square of the space it is painted in.
212
+ const xs = [mapX(ctm, 0, 0), mapX(ctm, 1, 0), mapX(ctm, 0, 1), mapX(ctm, 1, 1)];
213
+ const ys = [mapY(ctm, 0, 0), mapY(ctm, 1, 0), mapY(ctm, 0, 1), mapY(ctm, 1, 1)];
214
+ found.images.push({ id: value instanceof PDFRef ? value.objectNumber : -1, box: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)] });
215
+ } else if (subtype === PDFName.of("Form") && depth < MAX_FORM_DEPTH && !open.has(object)) {
216
+ const inner = decodeContent(library, context, object, MAX_CONTENT_BYTES);
217
+ if (inner === undefined) break;
218
+ const own = object.dict.lookup(PDFName.of("Resources"));
219
+ const formMatrix = object.dict.lookup(PDFName.of("Matrix"));
220
+ const values = formMatrix instanceof PDFArray ? formMatrix.asArray().map((entry) => (entry instanceof PDFNumber ? entry.asNumber() : Number.NaN)) : [];
221
+ open.add(object);
222
+ // A form without resources of its own uses those of the content that paints it.
223
+ run(library, context, inner, own instanceof PDFDict ? own : resources, values.length === 6 && values.every(Number.isFinite) ? multiply(values, ctm) : ctm, found, depth + 1, open);
224
+ open.delete(object);
225
+ }
226
+ break;
227
+ }
228
+ default:
229
+ break;
230
+ }
231
+ numbers = [];
232
+ name = undefined;
233
+ }
234
+ }
235
+
236
+ /** Red, green and blue between 0 and 1 for a fill colour, or undefined when it cannot be told. */
237
+ function rgb(fill: string): [number, number, number] | undefined {
238
+ const [kind, list = ""] = fill.split(":");
239
+ const values = list.split(",").map(Number);
240
+ if (values.some((value) => !Number.isFinite(value))) return undefined;
241
+ if (kind === "g" && values.length === 1) return [values[0]!, values[0]!, values[0]!];
242
+ if (kind === "rgb" && values.length === 3) return [values[0]!, values[1]!, values[2]!];
243
+ if (kind === "cmyk" && values.length === 4) return [(1 - values[0]!) * (1 - values[3]!), (1 - values[1]!) * (1 - values[3]!), (1 - values[2]!) * (1 - values[3]!)];
244
+ return undefined;
245
+ }
246
+
247
+ /** Whether a page shows a picture or a drawing, from what its content draws. */
248
+ function showsPicture(graphics: Graphics, geometry: PageGeometry, furniture: ReadonlySet<number>): boolean {
249
+ if (graphics.tooLarge) return true;
250
+ const [x0, y0, x1, y1] = geometry.view as [number, number, number, number];
251
+ const pageArea = Math.max(1, (x1 - x0) * (y1 - y0));
252
+ /** The part of a box that is on the page, as a share of the page. */
253
+ const share = (box: Box) => Math.max(0, Math.min(box[2], x1) - Math.max(box[0], x0)) * Math.max(0, Math.min(box[3], y1) - Math.max(box[1], y0)) / pageArea;
254
+
255
+ let images = 0;
256
+ for (const image of graphics.images) if (!furniture.has(image.id)) images += share(image.box);
257
+ if (images >= PICTURE_SHARE) return true;
258
+
259
+ const colours = new Set<string>();
260
+ for (const shape of graphics.shapes) {
261
+ const size = share(shape.box);
262
+ // Not a rule or a border, not a dot, not the background of the page.
263
+ if (size < 0.0002 || size > 0.85 || Math.min(shape.box[2] - shape.box[0], shape.box[3] - shape.box[1]) < 1.5) continue;
264
+ const colour = rgb(shape.fill);
265
+ // Black, white and greys are what text, rules and plain shading use.
266
+ if (!colour || Math.max(...colour) - Math.min(...colour) < 0.15) continue;
267
+ // The shading of a table's cells belongs to the table.
268
+ const centreX = (shape.box[0] + shape.box[2]) / 2;
269
+ const centreY = (shape.box[1] + shape.box[3]) / 2;
270
+ const x = mapX(geometry.transform, centreX, centreY);
271
+ const y = mapY(geometry.transform, centreX, centreY);
272
+ if (geometry.tables.some((table) => x >= table[0] && x <= table[2] && y >= table[1] && y <= table[3])) continue;
273
+ colours.add(colour.map((value) => Math.round(value * 10)).join(","));
274
+ if (colours.size >= DRAWING_COLOURS) return true;
275
+ }
276
+ return false;
277
+ }
278
+
279
+ /**
280
+ * For each page, whether it shows a picture (images that cover a real share of the page, other
281
+ * than one repeated on many pages) or a drawing (shapes filled in several colours, outside the
282
+ * tables). Undefined when that could not be worked out: the library is not installed, the file has
283
+ * too many objects or took too long, or it does not have the pages the text was extracted from.
284
+ * It never throws.
285
+ */
286
+ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGeometry[]): Promise<boolean[] | undefined> {
287
+ try {
288
+ if (tooManyObjects(bytes, MAX_OBJECTS) !== undefined) return undefined;
289
+ const library = await loadPdfLibrary();
290
+ const { PDFArray, PDFDocument, PDFRawStream } = library;
291
+ const document = await PDFDocument.load(bytes, { updateMetadata: false, parseSpeed: 4_000, password: "" });
292
+ const leaves = document.getPages();
293
+ if (leaves.length !== pages.length) return undefined;
294
+ const { context } = document;
295
+ const deadline = performance.now() + TIME_LIMIT_MS;
296
+ const graphics: Graphics[] = [];
297
+ for (const leaf of leaves) {
298
+ if (performance.now() > deadline) return undefined;
299
+ const found: Graphics = { images: [], shapes: [], tooLarge: false };
300
+ graphics.push(found);
301
+ try {
302
+ const contents = leaf.node.Contents();
303
+ const streams = contents instanceof PDFArray ? contents.asArray().map((entry) => context.lookup(entry)) : contents ? [contents] : [];
304
+ if (streams.some((stream) => stream instanceof PDFRawStream && stream.contents.length > MAX_CONTENT_BYTES)) {
305
+ found.tooLarge = true;
306
+ continue;
307
+ }
308
+ const parts = streams.map((stream) => decodeContent(library, context, stream, MAX_CONTENT_BYTES));
309
+ // Content that cannot be read is not guessed at: the page stays unmarked.
310
+ if (!parts.includes(undefined)) run(library, context, parts.join(" "), leaf.node.Resources(), IDENTITY, found, 0, new Set());
311
+ } catch {
312
+ // An unusual page: unmarked.
313
+ }
314
+ }
315
+ // An image painted on many pages is part of the page design, whatever its size.
316
+ const pagesWith = new Map<number, number>();
317
+ for (const found of graphics) for (const id of new Set(found.images.map((image) => image.id))) pagesWith.set(id, (pagesWith.get(id) ?? 0) + 1);
318
+ const repeated = Math.max(3, Math.ceil(pages.length * FURNITURE_SHARE));
319
+ const furniture = new Set([...pagesWith].filter(([, count]) => count >= repeated).map(([id]) => id));
320
+ return graphics.map((found, index) => showsPicture(found, pages[index]!, furniture));
321
+ } catch {
322
+ return undefined;
323
+ }
324
+ }