llm-large-files 0.2.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.
- package/CHANGELOG.md +71 -0
- package/README.md +32 -6
- package/dist/extract.d.ts +13 -6
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +27 -6
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +16 -0
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +45 -11
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +34 -4
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +47 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +31 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +44 -6
- package/dist/library.js.map +1 -1
- package/dist/pdf-layout.d.ts +7 -0
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +32 -2
- package/dist/pdf-layout.js.map +1 -1
- package/dist/pdf-pages.d.ts +45 -0
- package/dist/pdf-pages.d.ts.map +1 -0
- package/dist/pdf-pages.js +336 -0
- package/dist/pdf-pages.js.map +1 -0
- package/dist/pdf-pictures.d.ts +20 -0
- package/dist/pdf-pictures.d.ts.map +1 -0
- package/dist/pdf-pictures.js +336 -0
- package/dist/pdf-pictures.js.map +1 -0
- package/dist/plan.d.ts +13 -3
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +22 -17
- package/dist/plan.js.map +1 -1
- package/dist/search.d.ts +9 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +41 -0
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +7 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +37 -5
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +145 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +57 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +39 -11
- package/docs/configuration.md +229 -5
- package/docs/getting-started.md +34 -3
- package/docs/how-it-works.md +52 -4
- package/docs/security.md +39 -4
- package/package.json +7 -2
- package/src/extract.ts +34 -8
- package/src/gemini/chat.ts +60 -13
- package/src/gemini/generate.ts +63 -9
- package/src/gemini/index.ts +3 -3
- package/src/index.ts +2 -2
- package/src/library.ts +74 -7
- package/src/pdf-layout.ts +37 -1
- package/src/pdf-pages.ts +315 -0
- package/src/pdf-pictures.ts +324 -0
- package/src/plan.ts +36 -16
- package/src/search.ts +37 -0
- package/src/stores.ts +39 -6
- package/src/tools.ts +147 -13
- package/src/types.ts +57 -3
|
@@ -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
|
+
}
|
package/src/plan.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.j
|
|
|
2
2
|
import type { SearchableDocument } from "./search.js";
|
|
3
3
|
|
|
4
4
|
/** Bytes kept free for document cards, the tool declarations, and JSON framing. */
|
|
5
|
-
const REQUEST_BYTES_MARGIN = 256 * 1024;
|
|
5
|
+
export const REQUEST_BYTES_MARGIN = 256 * 1024;
|
|
6
6
|
const CARD_HEAD_LINES = 25;
|
|
7
7
|
const CARD_OUTLINE_ENTRIES = 40;
|
|
8
8
|
|
|
@@ -55,14 +55,18 @@ export function renderInline(document: SearchableDocument): string {
|
|
|
55
55
|
return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/**
|
|
59
|
-
|
|
58
|
+
/**
|
|
59
|
+
* A compact stand-in for a document that is too large for the prompt. `viewable` adds a line
|
|
60
|
+
* saying that its pages can be looked at with `view_pages`.
|
|
61
|
+
*/
|
|
62
|
+
export function renderCard(document: SearchableDocument, viewable = false): string {
|
|
60
63
|
const { meta } = document;
|
|
61
64
|
const out = [
|
|
62
65
|
`--- Large attached file: ${meta.name} ---`,
|
|
63
66
|
`document_id: ${meta.id}`,
|
|
64
67
|
`${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
|
|
65
68
|
"This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
|
|
69
|
+
...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
|
|
66
70
|
];
|
|
67
71
|
const profile = meta.logProfile;
|
|
68
72
|
if (profile) {
|
|
@@ -83,18 +87,34 @@ export function renderCard(document: SearchableDocument): string {
|
|
|
83
87
|
return out.join("\n");
|
|
84
88
|
}
|
|
85
89
|
|
|
86
|
-
|
|
87
|
-
|
|
90
|
+
/**
|
|
91
|
+
* The tool guide for the system prompt. `searchable` are the files the model reads through the
|
|
92
|
+
* text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
|
|
93
|
+
* may be searchable, and some may have their whole text in the prompt.
|
|
94
|
+
*/
|
|
95
|
+
export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = []): string {
|
|
88
96
|
// File names come from uploads. Quoting keeps a name that reads like an instruction a name.
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
97
|
+
const named = (meta: DocumentMeta, detail = "") => `${JSON.stringify(meta.name)} (document_id ${meta.id}${detail})`;
|
|
98
|
+
const guide: string[] = [];
|
|
99
|
+
if (searchable.length > 0) {
|
|
100
|
+
guide.push(
|
|
101
|
+
`Some attached files are too large for your context: ${searchable.map((meta) => named(meta)).join("; ")}.`,
|
|
102
|
+
"You see only a summary card for each. Read them through the tools:",
|
|
103
|
+
"- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
|
|
104
|
+
"- read_document reads a line range. Read around search hits before you rely on them.",
|
|
105
|
+
"- get_document_overview returns the outline, log profile, and the start and end of a file.",
|
|
106
|
+
"- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
|
|
107
|
+
"You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
|
|
108
|
+
"Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
if (viewable.length > 0) {
|
|
112
|
+
guide.push(
|
|
113
|
+
`The text of a PDF does not show its pictures, charts or diagrams. You can look at the real pages of these PDFs with view_pages: ${viewable.map((meta) => named(meta, meta.pages ? `, ${meta.pages} ${meta.pages === 1 ? "page" : "pages"}` : "")).join("; ")}.`,
|
|
114
|
+
"- Use view_pages when the answer depends on a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or on how a page is laid out. A page is worth a look when its text says it has a picture or has no text, or mentions a figure.",
|
|
115
|
+
"- Page numbers are the N of the \"--- Page N ---\" lines in the text. Ask only for the pages you need: you have a limited number of tool turns.",
|
|
116
|
+
"- Do not use view_pages to read text, and do not describe a picture you have not looked at. If you could not look at a page, say so.",
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return guide.join("\n");
|
|
100
120
|
}
|
package/src/search.ts
CHANGED
|
@@ -21,6 +21,7 @@ export class SearchableDocument {
|
|
|
21
21
|
readonly lines: LineIndex;
|
|
22
22
|
private lowerText?: string;
|
|
23
23
|
private passageStarts?: number[];
|
|
24
|
+
private pageStarts?: number[];
|
|
24
25
|
|
|
25
26
|
constructor(document: StoredDocument) {
|
|
26
27
|
this.meta = document.meta;
|
|
@@ -70,6 +71,42 @@ export class SearchableDocument {
|
|
|
70
71
|
}
|
|
71
72
|
return low;
|
|
72
73
|
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
|
|
77
|
+
* a text without them, and for lines above the first one. Only markers that count up from 1 are
|
|
78
|
+
* used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
|
|
79
|
+
*/
|
|
80
|
+
pageOfLine(line: number): number | undefined {
|
|
81
|
+
if (!this.pageStarts) {
|
|
82
|
+
const starts: number[] = [];
|
|
83
|
+
const marker = "--- Page ";
|
|
84
|
+
for (let at = this.text.indexOf(marker); at !== -1; at = this.text.indexOf(marker, at + marker.length)) {
|
|
85
|
+
if (at > 0 && this.text[at - 1] !== "\n") continue;
|
|
86
|
+
const found = this.lines.lineAt(at);
|
|
87
|
+
if (this.lines.line(found) === `--- Page ${starts.length + 1} ---`) starts.push(found);
|
|
88
|
+
}
|
|
89
|
+
this.pageStarts = starts;
|
|
90
|
+
}
|
|
91
|
+
const starts = this.pageStarts;
|
|
92
|
+
if (starts.length === 0 || line < starts[0]!) return undefined;
|
|
93
|
+
let low = 0;
|
|
94
|
+
let high = starts.length - 1;
|
|
95
|
+
while (low < high) {
|
|
96
|
+
const middle = (low + high + 1) >> 1;
|
|
97
|
+
if (starts[middle]! <= line) low = middle;
|
|
98
|
+
else high = middle - 1;
|
|
99
|
+
}
|
|
100
|
+
return low + 1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
|
|
104
|
+
pagesOfLines(from: number, to: number): string | undefined {
|
|
105
|
+
const last = this.pageOfLine(to);
|
|
106
|
+
if (last === undefined) return undefined;
|
|
107
|
+
const first = this.pageOfLine(from) ?? 1;
|
|
108
|
+
return first === last ? String(last) : `${first}-${last}`;
|
|
109
|
+
}
|
|
73
110
|
}
|
|
74
111
|
|
|
75
112
|
export type LineMatch = { line: number; text: string; before?: string[]; after?: string[] };
|
package/src/stores.ts
CHANGED
|
@@ -11,6 +11,7 @@ function expired(meta: DocumentMeta, now = new Date()): boolean {
|
|
|
11
11
|
/** Keeps documents in process memory. Good for tests and single-process demos. */
|
|
12
12
|
export class MemoryDocumentStore implements DocumentStore {
|
|
13
13
|
private readonly documents = new Map<string, StoredDocument>();
|
|
14
|
+
private readonly originals = new Map<string, Uint8Array>();
|
|
14
15
|
private readonly now: () => Date;
|
|
15
16
|
|
|
16
17
|
constructor(options: { now?: () => Date } = {}) {
|
|
@@ -24,7 +25,7 @@ export class MemoryDocumentStore implements DocumentStore {
|
|
|
24
25
|
async get(id: string): Promise<StoredDocument | undefined> {
|
|
25
26
|
const document = this.documents.get(id);
|
|
26
27
|
if (document && expired(document.meta, this.now())) {
|
|
27
|
-
this.
|
|
28
|
+
await this.delete(id);
|
|
28
29
|
return undefined;
|
|
29
30
|
}
|
|
30
31
|
return document;
|
|
@@ -35,6 +36,7 @@ export class MemoryDocumentStore implements DocumentStore {
|
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
async delete(id: string): Promise<boolean> {
|
|
39
|
+
this.originals.delete(id);
|
|
38
40
|
return this.documents.delete(id);
|
|
39
41
|
}
|
|
40
42
|
|
|
@@ -42,17 +44,27 @@ export class MemoryDocumentStore implements DocumentStore {
|
|
|
42
44
|
let removed = 0;
|
|
43
45
|
for (const [id, document] of this.documents) {
|
|
44
46
|
if (expired(document.meta, now)) {
|
|
45
|
-
this.
|
|
47
|
+
await this.delete(id);
|
|
46
48
|
removed++;
|
|
47
49
|
}
|
|
48
50
|
}
|
|
49
51
|
return removed;
|
|
50
52
|
}
|
|
53
|
+
|
|
54
|
+
async putOriginal(id: string, bytes: Uint8Array): Promise<void> {
|
|
55
|
+
// A copy: the caller may reuse its buffer after the upload.
|
|
56
|
+
this.originals.set(id, bytes.slice());
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async getOriginal(id: string): Promise<Uint8Array | undefined> {
|
|
60
|
+
return await this.get(id) ? this.originals.get(id) : undefined;
|
|
61
|
+
}
|
|
51
62
|
}
|
|
52
63
|
|
|
53
64
|
/**
|
|
54
65
|
* Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
|
|
55
|
-
* server restart
|
|
66
|
+
* server restart, and its original file as `<id>.bin` when one is kept. Only IDs matching
|
|
67
|
+
* DOCUMENT_ID_PATTERN ever reach the file system.
|
|
56
68
|
*/
|
|
57
69
|
export class FileDocumentStore implements DocumentStore {
|
|
58
70
|
private readonly now: () => Date;
|
|
@@ -61,9 +73,10 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
61
73
|
this.now = options.now ?? (() => new Date());
|
|
62
74
|
}
|
|
63
75
|
|
|
64
|
-
private paths(id: string): { text: string; meta: string } | undefined {
|
|
76
|
+
private paths(id: string): { text: string; meta: string; original: string } | undefined {
|
|
65
77
|
if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
|
|
66
|
-
|
|
78
|
+
const file = (extension: string) => path.join(this.directory, `${id}.${extension}`);
|
|
79
|
+
return { text: file("txt"), meta: file("json"), original: file("bin") };
|
|
67
80
|
}
|
|
68
81
|
|
|
69
82
|
async put(document: StoredDocument): Promise<void> {
|
|
@@ -106,10 +119,30 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
106
119
|
const paths = this.paths(id);
|
|
107
120
|
if (!paths) return false;
|
|
108
121
|
const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
|
|
109
|
-
await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true })]);
|
|
122
|
+
await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true }), rm(paths.original, { force: true })]);
|
|
110
123
|
return existed;
|
|
111
124
|
}
|
|
112
125
|
|
|
126
|
+
async putOriginal(id: string, bytes: Uint8Array): Promise<void> {
|
|
127
|
+
const paths = this.paths(id);
|
|
128
|
+
if (!paths) throw new Error("Invalid document ID.");
|
|
129
|
+
await mkdir(this.directory, { recursive: true });
|
|
130
|
+
// Written before the metadata (see put): until that exists, the document is treated as absent.
|
|
131
|
+
await writeFile(paths.original, bytes);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async getOriginal(id: string): Promise<Uint8Array | undefined> {
|
|
135
|
+
const paths = this.paths(id);
|
|
136
|
+
// The metadata decides whether the document is still there. getMeta also removes an expired one.
|
|
137
|
+
if (!paths || !await this.getMeta(id)) return undefined;
|
|
138
|
+
try {
|
|
139
|
+
const file = await readFile(paths.original);
|
|
140
|
+
return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
|
|
141
|
+
} catch {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
113
146
|
async sweep(now = this.now()): Promise<number> {
|
|
114
147
|
let entries: string[];
|
|
115
148
|
try {
|