llm-large-files 0.8.2 → 0.10.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 +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +35 -5
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +4 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +19 -4
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The outline of a PDF from the size of its type (0.10.0).
|
|
3
|
+
*
|
|
4
|
+
* The text rules of the outline (analyze.ts) rarely fire on a PDF: pdf.js gives no blank line
|
|
5
|
+
* between paragraphs, and Hebrew has no capitals, so an unnumbered Hebrew PDF had no outline at
|
|
6
|
+
* all. Its headings are set in larger type than its body, and pdf.js gives the size of each piece
|
|
7
|
+
* of text. The PDF extractor collects the lines set larger than the body (`PdfHeadingFinder`) and
|
|
8
|
+
* returns them with their page (`ExtractedText.headings`). Ingest finds each one among the lines of
|
|
9
|
+
* its page in the stored text, and uses them when the text rules found fewer than 3 headings and 3
|
|
10
|
+
* or more of these are found (`pdfOutline`): a PDF whose text has an outline keeps it as it was, and
|
|
11
|
+
* so does one with a title alone.
|
|
12
|
+
*
|
|
13
|
+
* pdf.js does not say which text is bold (its text content names a generic family, such as
|
|
14
|
+
* "sans-serif", and no weight), so a heading in bold type of the body's size is not found.
|
|
15
|
+
*/
|
|
16
|
+
import { pickOutline } from "./analyze.js";
|
|
17
|
+
import type { TimeSlicer } from "./pause.js";
|
|
18
|
+
import type { PdfTextItem } from "./pdf-layout.js";
|
|
19
|
+
import { composed, removeInvisible } from "./text.js";
|
|
20
|
+
import type { ExtractedText, OutlineEntry } from "./types.js";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A heading of a PDF, as the extractor returns it: its page, from 1; its level, from 1; its text;
|
|
24
|
+
* and, when lines above it on its page read the same (spaces aside: a contents list, a running
|
|
25
|
+
* header), how many, so that ingest passes over them.
|
|
26
|
+
*/
|
|
27
|
+
export type PdfHeading = { page: number; level: number; title: string; skip?: number };
|
|
28
|
+
|
|
29
|
+
/** Sizes are compared in steps of half a unit: Word's 10.56 and 10.5 are one size. */
|
|
30
|
+
const SIZE_STEP = 0.5;
|
|
31
|
+
/**
|
|
32
|
+
* A heading is set at least this much larger than the body: Word's Heading 2 (13 pt over 11),
|
|
33
|
+
* HTML's h3 (1.17 em), LibreOffice's Heading 2 (115%). Word's Heading 3 (12 pt over 11) is not: a
|
|
34
|
+
* lower ratio takes body text set a point larger, a quotation or a note, for headings.
|
|
35
|
+
*/
|
|
36
|
+
const HEADING_RATIO = 1.15;
|
|
37
|
+
/** Of a line's characters, at least this share are of its size: a line that opens with a large word is body text. */
|
|
38
|
+
const UNIFORM_SHARE = 0.75;
|
|
39
|
+
/** When more of the text than this is set larger than the body, its sizes do not mark headings. */
|
|
40
|
+
const MAX_LARGE_SHARE = 0.3;
|
|
41
|
+
/** A heading has at least 3 letters, and no more digits than letters: "12,500", "2026" and "- 3 -" are not headings. */
|
|
42
|
+
const MIN_LETTERS = 3;
|
|
43
|
+
/** The longest heading, as for the text rules. */
|
|
44
|
+
const MAX_TITLE_CHARACTERS = 120;
|
|
45
|
+
/** Levels come from the rank of the sizes: the largest is 1, the third and smaller are 3. */
|
|
46
|
+
const MAX_LEVELS = 3;
|
|
47
|
+
/** Lines kept while the pages are read, before the size of the body is known: past this, the smallest size kept goes. */
|
|
48
|
+
const MAX_KEPT_LINES = 20_000;
|
|
49
|
+
/** Sizes kept while the pages are read: past this, the smallest goes. A document uses a few dozen; the bound keeps each line's work small. */
|
|
50
|
+
const MAX_KEPT_SIZES = 64;
|
|
51
|
+
/**
|
|
52
|
+
* A gap wider than this many times the size of the type, between two pieces of one line, is between
|
|
53
|
+
* two cells: the line is a table row. The tab after a heading's number is at most half an inch,
|
|
54
|
+
* less than 3 times the size of a heading.
|
|
55
|
+
*/
|
|
56
|
+
const CELL_GAP = 3;
|
|
57
|
+
/** An outline has at least this many headings, from the text rules or the sizes: one or two are seldom an outline. */
|
|
58
|
+
export const MIN_TEXT_HEADINGS = 3;
|
|
59
|
+
/** The most headings `ingest` reads from an extractor. */
|
|
60
|
+
const MAX_GIVEN_HEADINGS = 10_000;
|
|
61
|
+
/** A stored line longer than this is not looked at: a heading is at most 120 characters, with a space between its words. */
|
|
62
|
+
const MAX_LINE_CHARACTERS = 2 * MAX_TITLE_CHARACTERS;
|
|
63
|
+
|
|
64
|
+
type Line = { page: number; order: number; size: number; title: string; skip: number };
|
|
65
|
+
|
|
66
|
+
/** The size of a piece of text, in steps of `SIZE_STEP`, or undefined when it has none. */
|
|
67
|
+
function sizeOf(item: PdfTextItem): number | undefined {
|
|
68
|
+
const matrix: unknown = item.transform;
|
|
69
|
+
// pdf.js gives the height of horizontal text; vertical text has none, and its matrix gives the size.
|
|
70
|
+
const raw = item.height > 0 ? item.height : Array.isArray(matrix) ? Math.hypot(Number(matrix[0]), Number(matrix[1])) : Number.NaN;
|
|
71
|
+
const size = Math.round(raw / SIZE_STEP) * SIZE_STEP;
|
|
72
|
+
return Number.isFinite(size) && size > 0 ? size : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Where a piece of text starts along its line (it ends `width` further), or NaN when that cannot be told. */
|
|
76
|
+
function startOf(item: PdfTextItem): number {
|
|
77
|
+
const matrix: unknown = item.transform;
|
|
78
|
+
if (!Array.isArray(matrix) || !(item.width > 0)) return Number.NaN;
|
|
79
|
+
const a = Number(matrix[0]);
|
|
80
|
+
const b = Number(matrix[1]);
|
|
81
|
+
return (Number(matrix[4]) * a + Number(matrix[5]) * b) / Math.hypot(a, b);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether a line's text can be a heading: not too long, not a table row, and words rather than a number. */
|
|
85
|
+
function mayBeHeading(title: string): boolean {
|
|
86
|
+
if (title.length > MAX_TITLE_CHARACTERS || title.startsWith("|")) return false;
|
|
87
|
+
const letters = title.match(/\p{L}/gu)?.length ?? 0;
|
|
88
|
+
const digits = title.match(/\p{Nd}/gu)?.length ?? 0;
|
|
89
|
+
return letters >= MIN_LETTERS && letters >= digits;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** A text as it is compared with a heading: cleaned and composed as ingest stores text, without its spaces. */
|
|
93
|
+
const compared = (text: string) => composed(removeInvisible(text)).replace(/\s+/g, "");
|
|
94
|
+
/** A line's text with each number written "#", or undefined when it has none: "Page 3 of 10" is the same on every page. */
|
|
95
|
+
const numberless = (title: string) => (/\p{Nd}/u.test(title) ? title.replace(/\s+/g, "").replace(/\p{Nd}+/gu, "#") : undefined);
|
|
96
|
+
|
|
97
|
+
/** Adds `page` to the pages of `key`. */
|
|
98
|
+
function seenOn(pages: Map<string, Set<number>>, key: string, page: number): void {
|
|
99
|
+
const set = pages.get(key);
|
|
100
|
+
if (set) set.add(page);
|
|
101
|
+
else pages.set(key, new Set([page]));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Finds the headings of a PDF from the size of its type, page by page as pdf.js reads them. A line
|
|
106
|
+
* is the text up to the end of a line (`hasEOL`), as the extractor writes it, and its size is the
|
|
107
|
+
* size most of its characters have. A line with a gap of more than 3 times its size between two
|
|
108
|
+
* pieces is a table row (cells, or a label and its value): it counts for neither the body nor the
|
|
109
|
+
* headings. Once every page is read, `headings()` gives the lines set at least 15% larger than the
|
|
110
|
+
* body, the commonest size of the other lines, but for:
|
|
111
|
+
* - lines over 120 characters, with fewer than 3 letters, with more digits than letters, or that
|
|
112
|
+
* start with "|";
|
|
113
|
+
* - lines with less than three quarters of their characters at their size;
|
|
114
|
+
* - running headers and footers: the same line on 3 pages or more, or on 2 pages and half the
|
|
115
|
+
* pages; or a page number (`pageNumbered`);
|
|
116
|
+
* - the lines after the first of a heading set on several lines in a row, at one size;
|
|
117
|
+
* - all of them, when more than 30% of the text is set larger than the body (sizes then mark
|
|
118
|
+
* something else).
|
|
119
|
+
*
|
|
120
|
+
* Levels follow the sizes of several headings: the largest is level 1, the next 2, the others 3. A
|
|
121
|
+
* size of one heading, larger than all of those (a title, the lines of a cover), is level 1, and the
|
|
122
|
+
* others then start at 2. At most 400 headings, picked as the text rules' outline is. The work is
|
|
123
|
+
* linear in the text: at most 20,000 lines in 64 sizes are kept until the end.
|
|
124
|
+
*/
|
|
125
|
+
export class PdfHeadingFinder {
|
|
126
|
+
/** The characters of each size, over all the text. */
|
|
127
|
+
private readonly characters = new Map<number, number>();
|
|
128
|
+
/** The lines that may be headings, by size. */
|
|
129
|
+
private readonly kept = new Map<number, Line[]>();
|
|
130
|
+
private keptLines = 0;
|
|
131
|
+
/** Lines of this size or smaller are no longer kept: there were too many. */
|
|
132
|
+
private floor = 0;
|
|
133
|
+
private pages = 0;
|
|
134
|
+
/** The lines of the page being read, by their text without spaces: how many so far. */
|
|
135
|
+
private readonly onPage = new Map<string, number>();
|
|
136
|
+
|
|
137
|
+
/** Adds the text of page `page` (from 1): `page.getTextContent().items`. */
|
|
138
|
+
addPage(page: number, items: readonly PdfTextItem[]): void {
|
|
139
|
+
this.pages++;
|
|
140
|
+
this.onPage.clear();
|
|
141
|
+
let order = 0;
|
|
142
|
+
let start = 0;
|
|
143
|
+
for (let index = 0; index <= items.length; index++) {
|
|
144
|
+
if (index < items.length && !items[index]!.hasEOL) continue;
|
|
145
|
+
if (this.addLine(page, order, items.slice(start, index + 1))) order++;
|
|
146
|
+
start = index + 1;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Adds one line; false when it has no visible character. */
|
|
151
|
+
private addLine(page: number, order: number, items: readonly PdfTextItem[]): boolean {
|
|
152
|
+
let text = "";
|
|
153
|
+
let total = 0;
|
|
154
|
+
let row = false;
|
|
155
|
+
/** The last piece with text: where it starts and ends along the line, and its size (NaN when not known). */
|
|
156
|
+
let lastStart = Number.NaN;
|
|
157
|
+
let lastEnd = Number.NaN;
|
|
158
|
+
let lastSize = 0;
|
|
159
|
+
const bySize = new Map<number, number>();
|
|
160
|
+
for (const item of items) {
|
|
161
|
+
if (typeof item.str !== "string") continue;
|
|
162
|
+
text += item.str;
|
|
163
|
+
const count = item.str.replace(/\s+/g, "").length;
|
|
164
|
+
const size = count > 0 ? sizeOf(item) : undefined;
|
|
165
|
+
if (size === undefined) continue;
|
|
166
|
+
bySize.set(size, (bySize.get(size) ?? 0) + count);
|
|
167
|
+
total += count;
|
|
168
|
+
// Right-to-left text runs the other way: the gap is the space between the two pieces either way.
|
|
169
|
+
const start = startOf(item);
|
|
170
|
+
const end = start + item.width;
|
|
171
|
+
if (Math.max(start - lastEnd, lastStart - end) > CELL_GAP * Math.max(size, lastSize)) row = true;
|
|
172
|
+
lastStart = start;
|
|
173
|
+
lastEnd = end;
|
|
174
|
+
lastSize = size;
|
|
175
|
+
}
|
|
176
|
+
if (total === 0) return false;
|
|
177
|
+
const title = text.replace(/\s+/g, " ").trim();
|
|
178
|
+
// A heading is the line after those above it on its page that read the same (a contents list).
|
|
179
|
+
const key = title.length <= MAX_LINE_CHARACTERS ? title.replace(/ /g, "") : "";
|
|
180
|
+
const skip = this.onPage.get(key) ?? 0;
|
|
181
|
+
if (key) this.onPage.set(key, skip + 1);
|
|
182
|
+
if (row) return true;
|
|
183
|
+
let size = 0;
|
|
184
|
+
let most = 0;
|
|
185
|
+
for (const [each, count] of bySize) {
|
|
186
|
+
this.characters.set(each, (this.characters.get(each) ?? 0) + count);
|
|
187
|
+
if (count > most || (count === most && each < size)) {
|
|
188
|
+
size = each;
|
|
189
|
+
most = count;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (most >= UNIFORM_SHARE * total && size > this.floor && mayBeHeading(title)) this.keep({ page, order, size, title, skip });
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private keep(line: Line): void {
|
|
197
|
+
const lines = this.kept.get(line.size);
|
|
198
|
+
if (lines) lines.push(line);
|
|
199
|
+
else this.kept.set(line.size, [line]);
|
|
200
|
+
this.keptLines++;
|
|
201
|
+
// Headings are larger than the body, so the smallest size goes first, and is not kept again.
|
|
202
|
+
// Each size goes at most once, and there are at most 65 to look through.
|
|
203
|
+
while (this.keptLines > MAX_KEPT_LINES || this.kept.size > MAX_KEPT_SIZES) {
|
|
204
|
+
const smallest = Math.min(...this.kept.keys());
|
|
205
|
+
this.keptLines -= this.kept.get(smallest)!.length;
|
|
206
|
+
this.kept.delete(smallest);
|
|
207
|
+
this.floor = smallest;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The headings found, in the order of the text. Empty when the sizes mark none. */
|
|
212
|
+
headings(): PdfHeading[] {
|
|
213
|
+
// The body: the size with the most characters, the smaller of two with as many.
|
|
214
|
+
let body = 0;
|
|
215
|
+
let most = 0;
|
|
216
|
+
let all = 0;
|
|
217
|
+
for (const [size, count] of this.characters) {
|
|
218
|
+
all += count;
|
|
219
|
+
if (count > most || (count === most && size < body)) {
|
|
220
|
+
body = size;
|
|
221
|
+
most = count;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const least = body * HEADING_RATIO;
|
|
225
|
+
let large = 0;
|
|
226
|
+
for (const [size, count] of this.characters) if (size >= least) large += count;
|
|
227
|
+
// No larger type; too much of it; or lines of a heading's size were let go (over 20,000 of them).
|
|
228
|
+
if (large === 0 || large > MAX_LARGE_SHARE * all || this.floor >= least) return [];
|
|
229
|
+
const lines = [...this.kept].flatMap(([size, kept]) => (size >= least ? kept : []));
|
|
230
|
+
lines.sort((left, right) => left.page - right.page || left.order - right.order);
|
|
231
|
+
// Running headers and footers: the same line on many pages, or a page number.
|
|
232
|
+
const exactly = new Map<string, Set<number>>();
|
|
233
|
+
const numbered = new Map<string, Line[]>();
|
|
234
|
+
for (const line of lines) {
|
|
235
|
+
seenOn(exactly, line.title.replace(/\s+/g, ""), line.page);
|
|
236
|
+
const key = numberless(line.title);
|
|
237
|
+
if (key === undefined) continue;
|
|
238
|
+
const alike = numbered.get(key);
|
|
239
|
+
if (alike) alike.push(line);
|
|
240
|
+
else numbered.set(key, [line]);
|
|
241
|
+
}
|
|
242
|
+
const paged = new Set([...numbered].flatMap(([key, alike]) => (pageNumbered(alike, this.pages) ? [key] : [])));
|
|
243
|
+
const running = (line: Line) => {
|
|
244
|
+
const same = exactly.get(line.title.replace(/\s+/g, ""))!.size;
|
|
245
|
+
const key = numberless(line.title);
|
|
246
|
+
return same >= 3 || (same >= 2 && same * 2 >= this.pages) || (key !== undefined && paged.has(key));
|
|
247
|
+
};
|
|
248
|
+
const found: Line[] = [];
|
|
249
|
+
let previous: Line | undefined;
|
|
250
|
+
for (const line of lines) {
|
|
251
|
+
if (running(line)) continue;
|
|
252
|
+
const continues = previous !== undefined && previous.page === line.page && previous.order + 1 === line.order && previous.size === line.size;
|
|
253
|
+
previous = line;
|
|
254
|
+
if (!continues) found.push(line);
|
|
255
|
+
}
|
|
256
|
+
const levelOf = levels(found.map((line) => line.size));
|
|
257
|
+
return pickOutline(found.map((line) => ({ page: line.page, level: levelOf.get(line.size)!, title: line.title, ...(line.skip > 0 ? { skip: line.skip } : {}) })));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The numbers of a line, in its order. */
|
|
262
|
+
const numbersOf = (title: string) => (title.match(/\p{Nd}+/gu) ?? []).map(Number);
|
|
263
|
+
|
|
264
|
+
/** Whether `after` is `before` with one of its numbers 1 more and the others the same. */
|
|
265
|
+
function oneMore(before: number[], after: number[]): boolean {
|
|
266
|
+
let more = 0;
|
|
267
|
+
for (const [index, number] of before.entries()) {
|
|
268
|
+
if (after[index] === number + 1) more++;
|
|
269
|
+
else if (after[index] !== number) return false;
|
|
270
|
+
}
|
|
271
|
+
return more === 1;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Whether lines that differ only by their numbers, in the order of the text, are a page number, a
|
|
276
|
+
* running header or footer ("עמוד 3 מתוך 10", "Annual Report page 7"): on 2 pages or more and at
|
|
277
|
+
* least half the pages, never counting up on one page (the same number in a page's header and its
|
|
278
|
+
* footer is one page number), and not counting as section numbers do. Section
|
|
279
|
+
* numbers count headings: each is the one before with one number 1 more, with pages without one
|
|
280
|
+
* between some of them ("פרק 1" to "פרק 5" on the odd pages). A page number counts pages: it skips
|
|
281
|
+
* the pages it is missing from ("page 1", "page 3" on the odd pages). Several on one page ("Article
|
|
282
|
+
* 1" to "Article 18", 3 to a page) are headings. On pages in a row, counting by one, the two read
|
|
283
|
+
* the same, and are taken for a page number: chapters one to a page on pages in a row, half the
|
|
284
|
+
* pages or more, are lost.
|
|
285
|
+
*/
|
|
286
|
+
function pageNumbered(alike: Line[], pages: number): boolean {
|
|
287
|
+
const on = new Set(alike.map((line) => line.page)).size;
|
|
288
|
+
if (on < 2 || on * 2 < pages) return false;
|
|
289
|
+
let counts = true;
|
|
290
|
+
let skips = false;
|
|
291
|
+
for (let index = 1; index < alike.length; index++) {
|
|
292
|
+
const before = alike[index - 1]!;
|
|
293
|
+
const line = alike[index]!;
|
|
294
|
+
if (line.page === before.page) {
|
|
295
|
+
// Several on one page that count up are headings ("Article 1" to "Article 3"); the same
|
|
296
|
+
// number twice on a page is a page number in the header and the footer.
|
|
297
|
+
if (oneMore(numbersOf(before.title), numbersOf(line.title))) return false;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
skips ||= line.page > before.page + 1;
|
|
301
|
+
counts &&= oneMore(numbersOf(before.title), numbersOf(line.title));
|
|
302
|
+
}
|
|
303
|
+
return !(counts && skips);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* The level of each size of `sizes`, those of the headings found: the sizes of several headings rank
|
|
308
|
+
* from the largest, 1 to 3; a size of one heading, larger than all of those (a title, the lines of a
|
|
309
|
+
* cover), is level 1, and the ranks then start at 2, so that a cover does not take the levels of
|
|
310
|
+
* the body's headings. When every size is of one heading, they all rank.
|
|
311
|
+
*/
|
|
312
|
+
function levels(sizes: number[]): Map<number, number> {
|
|
313
|
+
const uses = new Map<number, number>();
|
|
314
|
+
for (const size of sizes) uses.set(size, (uses.get(size) ?? 0) + 1);
|
|
315
|
+
const all = [...uses.keys()].sort((left, right) => right - left);
|
|
316
|
+
const ranked = all.filter((size) => uses.get(size)! >= 2);
|
|
317
|
+
const top = ranked[0];
|
|
318
|
+
if (top === undefined) return new Map(all.map((size, rank) => [size, Math.min(rank + 1, MAX_LEVELS)]));
|
|
319
|
+
const first = all[0]! > top ? 2 : 1;
|
|
320
|
+
return new Map(all.map((size) => [size, size > top ? 1 : Math.min(first + ranked.filter((each) => each > size).length, MAX_LEVELS)]));
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* The headings an extractor returned (`ExtractedText.headings`): the first 10,000 entries, those of
|
|
325
|
+
* the right shape (a page and a level that are whole numbers from 1, the level up to 6, a title of
|
|
326
|
+
* 1 to 1,000 characters, and a `skip` that is a whole number from 0, or none). Undefined when there
|
|
327
|
+
* are none.
|
|
328
|
+
*/
|
|
329
|
+
export function headingsOf(extracted: ExtractedText): PdfHeading[] | undefined {
|
|
330
|
+
const given: unknown = extracted.headings;
|
|
331
|
+
if (!Array.isArray(given)) return undefined;
|
|
332
|
+
const headings: PdfHeading[] = [];
|
|
333
|
+
for (const entry of given.slice(0, MAX_GIVEN_HEADINGS) as unknown[]) {
|
|
334
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
335
|
+
const { page, level, title, skip } = entry as { page?: unknown; level?: unknown; title?: unknown; skip?: unknown };
|
|
336
|
+
if (!Number.isSafeInteger(page) || (page as number) < 1 || !Number.isSafeInteger(level) || (level as number) < 1 || (level as number) > 6) continue;
|
|
337
|
+
if (typeof title !== "string" || !title.trim() || title.length > 1_000) continue;
|
|
338
|
+
if (skip !== undefined && (!Number.isSafeInteger(skip) || (skip as number) < 0)) continue;
|
|
339
|
+
headings.push({ page: page as number, level: level as number, title, ...(skip ? { skip: skip as number } : {}) });
|
|
340
|
+
}
|
|
341
|
+
return headings.length > 0 ? headings : undefined;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* The outline of the stored text from the headings of the extractor: each heading is the line of its
|
|
346
|
+
* page, after the one taken for the heading before it, with the same text once spaces are left out
|
|
347
|
+
* (pdf.js gives Hebrew words without the space between them, and the extractor adds it), past the
|
|
348
|
+
* `skip` lines above it that read the same. Pages start at the lines `--- Page N ---`, from 1, each
|
|
349
|
+
* continuing the count. A heading that is not found is left out; the title is the line as it is stored.
|
|
350
|
+
*/
|
|
351
|
+
async function placeHeadings(lines: string[], headings: PdfHeading[], slicer: TimeSlicer): Promise<OutlineEntry[]> {
|
|
352
|
+
const byPage = new Map<number, Map<string, PdfHeading[]>>();
|
|
353
|
+
for (const heading of headings) {
|
|
354
|
+
const key = compared(heading.title);
|
|
355
|
+
if (!key) continue;
|
|
356
|
+
let page = byPage.get(heading.page);
|
|
357
|
+
if (!page) byPage.set(heading.page, (page = new Map()));
|
|
358
|
+
const same = page.get(key);
|
|
359
|
+
if (same) same.push(heading);
|
|
360
|
+
else page.set(key, [heading]);
|
|
361
|
+
}
|
|
362
|
+
const outline: OutlineEntry[] = [];
|
|
363
|
+
let next = 1;
|
|
364
|
+
let marker = "--- Page 1 ---";
|
|
365
|
+
let page: Map<string, PdfHeading[]> | undefined;
|
|
366
|
+
/** The lines of the page so far, by their text without spaces: how many. */
|
|
367
|
+
const seen = new Map<string, number>();
|
|
368
|
+
for (let index = 0; index < lines.length; index++) {
|
|
369
|
+
if ((index & 4095) === 4095) await slicer.maybePause();
|
|
370
|
+
const line = lines[index]!;
|
|
371
|
+
if (line === marker) {
|
|
372
|
+
page = byPage.get(next++);
|
|
373
|
+
marker = `--- Page ${next} ---`;
|
|
374
|
+
seen.clear();
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (!page || line.length > MAX_LINE_CHARACTERS) continue;
|
|
378
|
+
const key = line.replace(/\s+/g, "");
|
|
379
|
+
const waiting = page.get(key);
|
|
380
|
+
if (!waiting?.length) continue;
|
|
381
|
+
const above = seen.get(key) ?? 0;
|
|
382
|
+
seen.set(key, above + 1);
|
|
383
|
+
if ((waiting[0]!.skip ?? 0) > above) continue;
|
|
384
|
+
const heading = waiting.shift()!;
|
|
385
|
+
outline.push({ line: index + 1, level: heading.level, title: line.trim() });
|
|
386
|
+
}
|
|
387
|
+
return outline;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The outline of a PDF: `outline`, from the text rules, when it has 3 headings or more, or when
|
|
392
|
+
* fewer than 3 of the extractor's headings are found in the stored text (one or two are seldom an
|
|
393
|
+
* outline: a title alone tells nothing); otherwise those found, at most 400, picked as the text
|
|
394
|
+
* rules' are.
|
|
395
|
+
*/
|
|
396
|
+
export async function pdfOutline(outline: OutlineEntry[], lines: string[], headings: PdfHeading[] | undefined, slicer: TimeSlicer): Promise<OutlineEntry[]> {
|
|
397
|
+
if (!headings || outline.length >= MIN_TEXT_HEADINGS) return outline;
|
|
398
|
+
const placed = await placeHeadings(lines, headings, slicer);
|
|
399
|
+
return placed.length >= MIN_TEXT_HEADINGS ? pickOutline(placed) : outline;
|
|
400
|
+
}
|