llm-large-files 0.5.0 → 0.8.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 +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- 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/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
package/src/text.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { TimeSlicer } from "./pause.js";
|
|
2
|
+
|
|
1
3
|
/** Lines longer than this are split so line-based tools always return bounded output. */
|
|
2
4
|
export const MAX_LINE_CHARACTERS = 2_000;
|
|
3
5
|
|
|
@@ -7,49 +9,436 @@ export const MAX_LINE_CHARACTERS = 2_000;
|
|
|
7
9
|
* ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
|
|
8
10
|
* not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
|
|
9
11
|
* or two bytes in a logged user agent, would take every line after it.
|
|
12
|
+
* U+009B, the one-character form of "ESC [", starts a sequence only with a parameter ("\x9b31m"),
|
|
13
|
+
* and not right after U+0080-U+00FF: there it is the end of a letter of UTF-8 read as Latin-1
|
|
14
|
+
* ("ś" is C5 9B, so "Coś? Tak" holds "\xc5\x9b? Tak"), and what follows it is text. `INVISIBLE`
|
|
15
|
+
* removes the U+009B alone then.
|
|
16
|
+
*/
|
|
17
|
+
// eslint-disable-next-line no-control-regex
|
|
18
|
+
const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])|(?<![\x80-\xff])\x9b[0-?]+[ -\/]*[@-~]/g;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Characters that show nothing, that no script needs, and that can hide text from a person who
|
|
22
|
+
* reads the file while a model reads it:
|
|
23
|
+
* - control characters other than tab and line breaks: C0 (U+0000-U+001F, U+007F) and C1
|
|
24
|
+
* (U+0080-U+009F);
|
|
25
|
+
* - Unicode tag characters (U+E0000-U+E007F). Each spells out one ASCII character, which a model
|
|
26
|
+
* reads and a person does not see. The three flags written with them (England, Scotland,
|
|
27
|
+
* Wales) are kept;
|
|
28
|
+
* - the text-direction controls that change the order a person sees: embeddings and overrides
|
|
29
|
+
* (U+202A-U+202E) and isolates (U+2066-U+2069). The marks that right-to-left text needs
|
|
30
|
+
* (U+200E, U+200F, U+061C) are kept;
|
|
31
|
+
* - the zero-width space (U+200B), the word joiner and invisible operators (U+2060-U+2064), the
|
|
32
|
+
* deprecated format characters (U+206A-U+206F), a byte order mark inside the text (U+FEFF), and
|
|
33
|
+
* the soft hyphen (U+00AD), but not one before a line break: there it shows, as a hyphen.
|
|
34
|
+
* Zero-width joiners and non-joiners (U+200C, U+200D) are kept: emoji and some scripts need them.
|
|
35
|
+
* Tab, "\n" and "\r" are not among them, so removing them moves no line. U+0085 goes with the other
|
|
36
|
+
* C1 characters, except where it ends lines (see `NEXT_LINE`).
|
|
10
37
|
*/
|
|
11
38
|
// eslint-disable-next-line no-control-regex
|
|
12
|
-
const
|
|
39
|
+
const INVISIBLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]+|\xAD(?!\n)|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|(?:\uDB40[\uDC00-\uDC7F])+/g;
|
|
40
|
+
/** A flag written with tag characters starts with U+1F3F4, whose first half is this. */
|
|
41
|
+
const FLAG_START = 0xd83c;
|
|
42
|
+
/**
|
|
43
|
+
* U+0085 (next line) ends each record of a mainframe file converted to UTF-8, which has no other
|
|
44
|
+
* line break: in such a text it becomes a line break (see `breaksAtNextLine`). Not one right after
|
|
45
|
+
* U+0080-U+00FF: there it is the last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and a
|
|
46
|
+
* line break would split the word. `INVISIBLE` removes that one, and those of other texts.
|
|
47
|
+
*/
|
|
48
|
+
const NEXT_LINE = /(?<![\x80-\xFF])\x85/g;
|
|
49
|
+
/** A run of U+0085, to go past it in one step. */
|
|
50
|
+
const NEXT_LINE_RUN = /\x85+/y;
|
|
51
|
+
|
|
52
|
+
/** `text` without the characters of `INVISIBLE`. */
|
|
53
|
+
export function removeInvisible(text: string): string {
|
|
54
|
+
return text.replace(INVISIBLE, (found) => (found.charCodeAt(0) === FLAG_START ? found : ""));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A word for a count: "line" for 1, "lines" for any other. */
|
|
58
|
+
export const plural = (count: number, word: string): string => (count === 1 ? word : `${word}s`);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether the U+0085 of `text` end lines: only when it has no other line break, one at its very end
|
|
62
|
+
* aside. A mainframe file converted to UTF-8 has none. In a text that has them, a U+0085 is more
|
|
63
|
+
* often in a JSON string or a CSV field, or a windows-1252 "…" read as Latin-1, and a line break
|
|
64
|
+
* there would split a record and move every line after it.
|
|
65
|
+
*/
|
|
66
|
+
export function breaksAtNextLine(text: string): boolean {
|
|
67
|
+
let end = text.length;
|
|
68
|
+
if (text.charCodeAt(end - 1) === 10) end--;
|
|
69
|
+
if (text.charCodeAt(end - 1) === 13) end--;
|
|
70
|
+
const lineFeed = text.indexOf("\n");
|
|
71
|
+
if (lineFeed !== -1 && lineFeed < end) return false;
|
|
72
|
+
const carriageReturn = text.indexOf("\r");
|
|
73
|
+
return carriageReturn === -1 || carriageReturn >= end;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`; then `composed`. */
|
|
77
|
+
function cleanLines(text: string, nextLines: boolean): string {
|
|
78
|
+
return composed(removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A character that Unicode normalization (NFC) may change: nothing below U+0300 does. */
|
|
82
|
+
const MAY_COMPOSE = /[^\x00-\u02ff]/;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* `text` in Unicode's composed form (NFC): "e" followed by a combining acute accent becomes one
|
|
86
|
+
* "é", as a model writes it in a query. Text exported from macOS, from some PDF and Word files, and
|
|
87
|
+
* Vietnamese, often comes decomposed, and a search for the composed word found nothing in it. Text
|
|
88
|
+
* with no character from U+0300 on is returned as it is, without the cost of normalizing it.
|
|
89
|
+
* Hebrew and Arabic points are not composed by NFC: they stay as they are.
|
|
90
|
+
*/
|
|
91
|
+
export function composed(text: string): string {
|
|
92
|
+
const first = text.search(MAY_COMPOSE);
|
|
93
|
+
if (first === -1) return text;
|
|
94
|
+
return streamSafe(text, first).text.normalize("NFC");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* More marks in a row than any script writes on one letter. NFC orders the marks of a run by
|
|
99
|
+
* their class, in time that grows with the square of the run: 600 KB of marks of two classes in
|
|
100
|
+
* turn held the server 80 seconds. Unicode's stream-safe form (UAX #15) bounds the run instead.
|
|
101
|
+
*/
|
|
102
|
+
const MAX_MARKS = 30;
|
|
103
|
+
/** A mark (\p{M}): a character that NFC may order with the marks next to it. */
|
|
104
|
+
const MARK = /\p{M}/u;
|
|
105
|
+
const MARK_RUNS = /\p{M}+/gu;
|
|
106
|
+
/** The combining grapheme joiner: a mark that is a starter, so NFC orders no marks across it. */
|
|
107
|
+
const GRAPHEME_JOINER = 0x034f;
|
|
108
|
+
/** Code points below this are looked up in `marks`; the few marks above it, with `MARK`. */
|
|
109
|
+
const TABLE_END = 0x20000;
|
|
110
|
+
/** Which code points below `TABLE_END` are marks, filled in a block of 4,096 the first time a character of the block is looked up. */
|
|
111
|
+
const marks = new Uint8Array(TABLE_END);
|
|
112
|
+
const markBlocks = new Uint8Array(TABLE_END >> 12);
|
|
113
|
+
|
|
114
|
+
/** Whether code point `point` is a mark. A look at a table: far quicker than a regex test. */
|
|
115
|
+
function isMark(point: number): boolean {
|
|
116
|
+
if (point >= TABLE_END) return MARK.test(String.fromCodePoint(point));
|
|
117
|
+
const block = point >> 12;
|
|
118
|
+
if (markBlocks[block] === 0) {
|
|
119
|
+
markBlocks[block] = 1;
|
|
120
|
+
const points: number[] = [];
|
|
121
|
+
for (let at = block << 12; at < (block + 1) << 12; at++) if (at < 0xd800 || at > 0xdfff) points.push(at);
|
|
122
|
+
for (const [run] of String.fromCodePoint(...points).matchAll(MARK_RUNS)) for (const character of run) marks[character.codePointAt(0)!] = 1;
|
|
123
|
+
}
|
|
124
|
+
return marks[point] === 1;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* `text` in the stream-safe form: a combining grapheme joiner (U+034F, which shows nothing and is
|
|
129
|
+
* a starter) after every 30 marks of a run, so no run NFC orders is longer than that. `first` is
|
|
130
|
+
* where the first character from U+0300 on is: nothing before it is a mark. `carried`: the marks
|
|
131
|
+
* that end the text before this one, for a text worked on in pieces; `run` is those that end this
|
|
132
|
+
* one. One pass, a look at a table for each character: a regex for long runs tried a match at each
|
|
133
|
+
* mark of a run, and took 1.3 microseconds a mark on runs of 30, more than NFC itself; on a run of
|
|
134
|
+
* millions of marks its greedy repeat ran out of stack, and the upload was refused with the
|
|
135
|
+
* engine's "Maximum call stack size exceeded".
|
|
136
|
+
*/
|
|
137
|
+
function streamSafe(text: string, first: number, carried = 0): { text: string; run: number } {
|
|
138
|
+
let pieces: string[] | undefined;
|
|
139
|
+
let copied = 0;
|
|
140
|
+
let run = first === 0 ? carried : 0;
|
|
141
|
+
const length = text.length;
|
|
142
|
+
for (let at = first; at < length; at++) {
|
|
143
|
+
const code = text.charCodeAt(at);
|
|
144
|
+
if (code < 0x0300) {
|
|
145
|
+
run = 0;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
// A pair of surrogates is one character, outside the basic plane.
|
|
149
|
+
const low = code >= 0xd800 && code <= 0xdbff ? text.charCodeAt(at + 1) : 0;
|
|
150
|
+
const pair = low >= 0xdc00 && low <= 0xdfff;
|
|
151
|
+
if (pair ? !isMark(((code - 0xd800) << 10) + (low - 0xdc00) + 0x10000) : code === GRAPHEME_JOINER || !isMark(code)) {
|
|
152
|
+
run = 0;
|
|
153
|
+
if (pair) at++;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
// These four become two marks each under NFC (UAX #15 counts the marks of the decomposition):
|
|
157
|
+
// counted as one, a run of 30 grew past 30 once composed, and composing it again changed it.
|
|
158
|
+
const weight = code === 0x0344 || code === 0x0f73 || code === 0x0f75 || code === 0x0f81 ? 2 : 1;
|
|
159
|
+
if (run + weight > MAX_MARKS) {
|
|
160
|
+
(pieces ??= []).push(text.slice(copied, at), "\u034f");
|
|
161
|
+
copied = at;
|
|
162
|
+
run = 0;
|
|
163
|
+
}
|
|
164
|
+
run += weight;
|
|
165
|
+
if (pair) at++;
|
|
166
|
+
}
|
|
167
|
+
if (!pieces) return { text, run };
|
|
168
|
+
pieces.push(text.slice(copied));
|
|
169
|
+
return { text: pieces.join(""), run };
|
|
170
|
+
}
|
|
13
171
|
|
|
14
172
|
/**
|
|
15
|
-
* Strips a BOM, unifies line endings, and removes terminal escape sequences
|
|
16
|
-
* other than tab and newline
|
|
173
|
+
* Strips a BOM, unifies line endings, and removes terminal escape sequences, control characters
|
|
174
|
+
* other than tab and newline, and the invisible characters of `INVISIBLE`. In a text with no other
|
|
175
|
+
* line break, a U+0085 becomes one (see `NEXT_LINE`).
|
|
17
176
|
*/
|
|
18
177
|
export function normalizeText(raw: string): string {
|
|
19
|
-
|
|
178
|
+
const text = raw.replace(/^/, "");
|
|
179
|
+
return normalizeLines(text, breaksAtNextLine(text));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `normalizeText` without the BOM: the same on a whole text as on pieces of it cut after line
|
|
184
|
+
* breaks, given `breaksAtNextLine` of the whole text as `nextLines`.
|
|
185
|
+
*/
|
|
186
|
+
function normalizeLines(raw: string, nextLines: boolean): string {
|
|
187
|
+
return cleanLines(withoutEscapes(raw.replace(/\r\n?/g, "\n")), nextLines);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** `text` without terminal escape sequences. */
|
|
191
|
+
function withoutEscapes(text: string): string {
|
|
20
192
|
// Remove whole sequences first. Dropping only the ESC byte would leave "[31mERROR[0m" behind.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
193
|
+
// U+009B is the one-character form of "ESC [".
|
|
194
|
+
return text.includes("\x1b") || text.includes("\x9b") ? text.replace(ANSI_ESCAPE, "") : text;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* `withoutEscapes`, with a pause after each `piece` characters or so. The sequences are found one
|
|
199
|
+
* after the other, as `replace` finds them, so the result is the same.
|
|
200
|
+
*/
|
|
201
|
+
async function withoutEscapesInPieces(text: string, slicer: TimeSlicer, piece: number): Promise<string> {
|
|
202
|
+
if (!text.includes("\x1b") && !text.includes("\x9b")) return text;
|
|
203
|
+
// A copy of its own: during a pause, another ingest may use `ANSI_ESCAPE`, which moves its lastIndex.
|
|
204
|
+
const escape = new RegExp(ANSI_ESCAPE.source, "g");
|
|
205
|
+
const done: string[] = [];
|
|
206
|
+
let parts: string[] = [];
|
|
207
|
+
// Where the text after the last sequence starts, and where the last pause was.
|
|
208
|
+
let kept = 0;
|
|
209
|
+
let paused = 0;
|
|
210
|
+
for (let found = escape.exec(text); found !== null; found = escape.exec(text)) {
|
|
211
|
+
parts.push(text.slice(kept, found.index));
|
|
212
|
+
kept = escape.lastIndex;
|
|
213
|
+
if (kept - paused >= piece) {
|
|
214
|
+
done.push(parts.join(""));
|
|
215
|
+
parts = [];
|
|
216
|
+
paused = kept;
|
|
217
|
+
await slicer.maybePause();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
parts.push(text.slice(kept));
|
|
221
|
+
done.push(parts.join(""));
|
|
222
|
+
return done.length === 1 ? done[0]! : done.join("");
|
|
24
223
|
}
|
|
25
224
|
|
|
225
|
+
/**
|
|
226
|
+
* `normalizeLines`, a piece of about `piece` characters at a time, with a pause between pieces. A
|
|
227
|
+
* line with no break for megabytes can hold millions of characters or escape sequences to remove,
|
|
228
|
+
* which take seconds in one go. The steps of `cleanLines` are taken on each piece in turn, so the
|
|
229
|
+
* result is the same as in one go: the escape sequences are found in order; the invisible
|
|
230
|
+
* characters are removed from pieces that end where `removesCleanly` says; the stream-safe form
|
|
231
|
+
* counts the marks of a run across pieces; and the text is composed up to the last place where
|
|
232
|
+
* NFC joins nothing across (`composesCleanly`), the rest with the next piece. A run of millions of
|
|
233
|
+
* marks has such a place after every 30 marks, where the stream-safe form puts a grapheme joiner:
|
|
234
|
+
* composed in one go, it held the server for seconds.
|
|
235
|
+
*/
|
|
236
|
+
export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLines: boolean, piece = SLICE_CHARACTERS): Promise<string> {
|
|
237
|
+
const text = await withoutEscapesInPieces(raw.replace(/\r\n?/g, "\n"), slicer, piece);
|
|
238
|
+
const parts: string[] = [];
|
|
239
|
+
// The marks in a row that end the text cleaned so far, and the end of that text, not yet composed.
|
|
240
|
+
let run = 0;
|
|
241
|
+
let tail = "";
|
|
242
|
+
for (let from = 0; from < text.length;) {
|
|
243
|
+
let to = Math.min(text.length, from + piece);
|
|
244
|
+
// Where the next piece starts.
|
|
245
|
+
let next = to;
|
|
246
|
+
while (to < text.length && !removesCleanly(text, to)) {
|
|
247
|
+
if (text.charCodeAt(to) === 0x85) {
|
|
248
|
+
// A run of U+0085 after U+0080-U+00FF, which no place may cut. `cleanLines` removes all of
|
|
249
|
+
// it, and gives the same on the text before it and after it alone: the run is left out.
|
|
250
|
+
NEXT_LINE_RUN.lastIndex = to;
|
|
251
|
+
NEXT_LINE_RUN.test(text);
|
|
252
|
+
next = NEXT_LINE_RUN.lastIndex;
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
next = ++to;
|
|
256
|
+
}
|
|
257
|
+
const slice = text.slice(from, to);
|
|
258
|
+
const safe = streamSafe(removeInvisible(nextLines && slice.includes("\x85") ? slice.replace(NEXT_LINE, "\n") : slice), 0, run);
|
|
259
|
+
run = safe.run;
|
|
260
|
+
const cleaned = tail + safe.text;
|
|
261
|
+
// The last piece is composed whole; another, up to a place where what follows joins nothing
|
|
262
|
+
// before it. Its very end is not one: the next piece may start with a mark.
|
|
263
|
+
let cut = cleaned.length;
|
|
264
|
+
if (next < text.length) {
|
|
265
|
+
cut = Math.max(0, cut - 1);
|
|
266
|
+
while (cut > 0 && !composesCleanly(cleaned, cut)) cut--;
|
|
267
|
+
}
|
|
268
|
+
const done = cleaned.slice(0, cut);
|
|
269
|
+
parts.push(MAY_COMPOSE.test(done) ? done.normalize("NFC") : done);
|
|
270
|
+
tail = cleaned.slice(cut);
|
|
271
|
+
from = next;
|
|
272
|
+
await slicer.maybePause();
|
|
273
|
+
}
|
|
274
|
+
return parts.length === 1 ? parts[0]! : parts.join("");
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Whether `removeInvisible`, after U+0085 is made a line break where it ends a line, gives the same
|
|
279
|
+
* result on `text` cut before `at` as on it whole. It does unless the cut is between the two halves
|
|
280
|
+
* of a character outside the basic plane, inside a flag, between a soft hyphen and a line break,
|
|
281
|
+
* or before a U+0085 right after U+0080-U+00FF. Only these places are kept whole: a rule that
|
|
282
|
+
* never cut after a soft hyphen or half of a pair would never cut a line of soft hyphens, or of
|
|
283
|
+
* tag characters and emoji in turn, and such a line would be cleaned in one go again.
|
|
284
|
+
*/
|
|
285
|
+
function removesCleanly(text: string, at: number): boolean {
|
|
286
|
+
const before = text.charCodeAt(at - 1);
|
|
287
|
+
const after = text.charCodeAt(at);
|
|
288
|
+
if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
|
|
289
|
+
if (before === 0xad && after === 0x0a) return false;
|
|
290
|
+
if (after === 0x85 && before >= 0x80 && before <= 0xff) return false;
|
|
291
|
+
// A flag is 14 units: U+1F3F4, then tag characters, each a pair that starts with U+DB40.
|
|
292
|
+
if (after === 0xdb40 && text.slice(Math.max(0, at - 12), at).includes("\uD83C\uDFF4")) return false;
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Whether NFC gives the same result on a text in the stream-safe form cut before `at` as on it
|
|
298
|
+
* whole: the cut is not inside a character, and NFC joins nothing across it. It joins a mark to the
|
|
299
|
+
* letter before it, and orders the marks of a run, but neither across a grapheme joiner, which is
|
|
300
|
+
* a starter and joins with nothing. It joins a Hangul vowel to an initial consonant, and a final
|
|
301
|
+
* consonant to a syllable of the two, or to a vowel that will join the consonant before it.
|
|
302
|
+
*/
|
|
303
|
+
function composesCleanly(text: string, at: number): boolean {
|
|
304
|
+
const before = text.charCodeAt(at - 1);
|
|
305
|
+
const after = text.charCodeAt(at);
|
|
306
|
+
if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
|
|
307
|
+
if (after < 0x0300 || before === GRAPHEME_JOINER) return true;
|
|
308
|
+
if (after >= 0x1161 && after <= 0x1175) return !(before >= 0x1100 && before <= 0x1112);
|
|
309
|
+
if (after >= 0x11a8 && after <= 0x11c2) return !((before >= 0x1161 && before <= 0x1175) || (before >= 0xac00 && before <= 0xd7a3 && (before - 0xac00) % 28 === 0));
|
|
310
|
+
const low = isHighSurrogate(after) ? text.charCodeAt(at + 1) : 0;
|
|
311
|
+
return !isMark(isLowSurrogate(low) ? ((after - 0xd800) << 10) + (low - 0xdc00) + 0x10000 : after);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Characters that are written several ways for one meaning, each folded to the plain one for a
|
|
316
|
+
* search that ignores case: curly quotes and primes to `'` and `"`, Hebrew geresh (׳) and gershayim
|
|
317
|
+
* (״) too, which keyboards replace by them ("צה״ל", "צה\"ל"); hyphens, dashes, the minus sign and the
|
|
318
|
+
* Hebrew maqaf (־) to "-"; no-break, thin and other fixed-width spaces to a space; and the
|
|
319
|
+
* full-width forms of ASCII (A, 1) to ASCII. Each is one UTF-16 unit for one, so offsets keep.
|
|
320
|
+
*/
|
|
321
|
+
const SEARCH_FOLDS: Record<string, string> = {
|
|
322
|
+
"\u2018": "'", "\u2019": "'", "\u201a": "'", "\u201b": "'", "\u2032": "'", "\u05f3": "'", "\u02bc": "'",
|
|
323
|
+
"\u201c": "\"", "\u201d": "\"", "\u201e": "\"", "\u201f": "\"", "\u2033": "\"", "\u05f4": "\"",
|
|
324
|
+
"\u2010": "-", "\u2011": "-", "\u2012": "-", "\u2013": "-", "\u2014": "-", "\u2015": "-", "\u2212": "-", "\u05be": "-",
|
|
325
|
+
"\u00a0": " ", "\u2007": " ", "\u2009": " ", "\u200a": " ", "\u202f": " ", "\u2002": " ", "\u2003": " ",
|
|
326
|
+
"\u03c2": "\u03c3",
|
|
327
|
+
};
|
|
328
|
+
const SEARCH_FOLD = /[\u2018\u2019\u201a\u201b\u2032\u05f3\u02bc\u201c\u201d\u201e\u201f\u2033\u05f4\u2010-\u2015\u2212\u05be\u00a0\u2007\u2009\u200a\u202f\u2002\u2003\u03c2\uff01-\uff5e]/g;
|
|
329
|
+
|
|
26
330
|
/**
|
|
27
331
|
* Lowercases for case-insensitive search without changing the string's length, so an offset in the
|
|
28
332
|
* result points at the same character in the original. "İ" (U+0130) is the one character whose
|
|
29
|
-
* lowercase form is longer; it is folded to "i".
|
|
333
|
+
* lowercase form is longer; it is folded to "i". Greek final sigma (ς) is folded to σ, as an upper
|
|
334
|
+
* case Σ is lowered to either depending on where it stands. Then the characters of `SEARCH_FOLDS`
|
|
335
|
+
* are folded, and the full-width forms of ASCII: a search for "don't" finds "don’t".
|
|
30
336
|
*/
|
|
31
337
|
export function foldCase(text: string): string {
|
|
32
|
-
|
|
33
|
-
if (lower.length
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
338
|
+
let lower = (text.includes("\u0130") ? text.replaceAll("\u0130", "i") : text).toLowerCase();
|
|
339
|
+
if (lower.length !== text.length) {
|
|
340
|
+
// Not expected with today's Unicode data. Fold unit by unit and keep any unit that would grow.
|
|
341
|
+
let out = "";
|
|
342
|
+
for (let index = 0; index < text.length; index++) {
|
|
343
|
+
const unit = text[index]!;
|
|
344
|
+
const folded = unit.toLowerCase();
|
|
345
|
+
out += folded.length === 1 ? folded : unit;
|
|
346
|
+
}
|
|
347
|
+
lower = out;
|
|
348
|
+
}
|
|
349
|
+
SEARCH_FOLD.lastIndex = 0;
|
|
350
|
+
if (!SEARCH_FOLD.test(lower)) return lower;
|
|
351
|
+
// One pass over the character codes, with a table: a replace with a callback for each character
|
|
352
|
+
// took seconds on a text full of curly quotes and dashes, which counted against a search's time.
|
|
353
|
+
const codes = new Uint16Array(lower.length);
|
|
354
|
+
for (let index = 0; index < lower.length; index++) {
|
|
355
|
+
const code = lower.charCodeAt(index);
|
|
356
|
+
codes[index] = FOLDED[code] || code;
|
|
40
357
|
}
|
|
41
|
-
|
|
358
|
+
// From the codes a block at a time: a decoder would make a lone half of a surrogate pair U+FFFD.
|
|
359
|
+
const parts: string[] = [];
|
|
360
|
+
for (let at = 0; at < codes.length; at += 8_192) parts.push(String.fromCharCode(...codes.subarray(at, at + 8_192)));
|
|
361
|
+
return parts.join("");
|
|
42
362
|
}
|
|
43
363
|
|
|
364
|
+
/** For each UTF-16 unit, the unit `foldCase` makes of it, or 0 when it keeps it. */
|
|
365
|
+
const FOLDED = (() => {
|
|
366
|
+
const table = new Uint16Array(0x10000);
|
|
367
|
+
for (const [from, to] of Object.entries(SEARCH_FOLDS)) table[from.charCodeAt(0)] = to.charCodeAt(0);
|
|
368
|
+
for (let code = 0xff01; code <= 0xff5e; code++) table[code] = code - 0xfee0;
|
|
369
|
+
return table;
|
|
370
|
+
})();
|
|
371
|
+
|
|
44
372
|
/** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
|
|
45
373
|
const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
|
|
46
374
|
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
|
|
47
375
|
|
|
376
|
+
/**
|
|
377
|
+
* The first `end` UTF-16 units of `text`, one fewer when the last of them would be the first half
|
|
378
|
+
* of a character outside the basic plane (an emoji). Half of one is not text: JSON writes it as
|
|
379
|
+
* `\ud83d`, and an API that checks its input (Claude's) refuses the request.
|
|
380
|
+
*/
|
|
381
|
+
export function sliceWhole(text: string, end: number): string {
|
|
382
|
+
const at = Math.max(0, Math.min(text.length, Math.trunc(end)));
|
|
383
|
+
return at > 0 && at < text.length && isHighSurrogate(text.charCodeAt(at - 1)) ? text.slice(0, at - 1) : text.slice(0, at);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Half of a character outside the basic plane, on its own. */
|
|
387
|
+
const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* `text` with each half of a character that is on its own (an emoji cut in two) made a replacement
|
|
391
|
+
* character, as `String.prototype.toWellFormed` does. 0.5.0 cut some strings that way, and kept them:
|
|
392
|
+
* log templates in the metadata, and search windows in tool rounds. Claude's API refuses a request
|
|
393
|
+
* that holds one. Text that is whole comes back as it is.
|
|
394
|
+
*/
|
|
395
|
+
export function wellFormed(text: string): string {
|
|
396
|
+
return /[\ud800-\udfff]/.test(text) ? text.replace(LONE_SURROGATE, "\ufffd") : text;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* A JSON value with `wellFormed` applied to every string in it, keys included. The same value, not
|
|
401
|
+
* a copy, when nothing in it needed that.
|
|
402
|
+
*/
|
|
403
|
+
export function wellFormedJson<T>(value: T): T {
|
|
404
|
+
if (typeof value === "string") return wellFormed(value) as T;
|
|
405
|
+
if (Array.isArray(value)) {
|
|
406
|
+
let changed = false;
|
|
407
|
+
const items = value.map((item: unknown) => {
|
|
408
|
+
const fixed = wellFormedJson(item);
|
|
409
|
+
if (fixed !== item) changed = true;
|
|
410
|
+
return fixed;
|
|
411
|
+
});
|
|
412
|
+
return (changed ? items : value) as T;
|
|
413
|
+
}
|
|
414
|
+
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
|
|
415
|
+
let changed = false;
|
|
416
|
+
const entries = Object.entries(value).map(([key, item]): [string, unknown] => {
|
|
417
|
+
const fixedKey = wellFormed(key);
|
|
418
|
+
const fixed = wellFormedJson(item);
|
|
419
|
+
if (fixedKey !== key || fixed !== item) changed = true;
|
|
420
|
+
return [fixedKey, fixed];
|
|
421
|
+
});
|
|
422
|
+
return (changed ? Object.fromEntries(entries) : value) as T;
|
|
423
|
+
}
|
|
424
|
+
return value;
|
|
425
|
+
}
|
|
426
|
+
|
|
48
427
|
/**
|
|
49
428
|
* Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
|
|
50
429
|
* end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
|
|
51
430
|
*/
|
|
52
431
|
export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text: string; wrapped: number } {
|
|
432
|
+
// Most files have no long line: then the text is used as it is, without splitting and joining it.
|
|
433
|
+
let longest = 0;
|
|
434
|
+
let start = 0;
|
|
435
|
+
for (let end = text.indexOf("\n"); ; end = text.indexOf("\n", start)) {
|
|
436
|
+
const stop = end === -1 ? text.length : end;
|
|
437
|
+
if (stop - start > longest) longest = stop - start;
|
|
438
|
+
if (end === -1 || longest > limit) break;
|
|
439
|
+
start = end + 1;
|
|
440
|
+
}
|
|
441
|
+
if (longest <= limit) return { text, wrapped: 0 };
|
|
53
442
|
let wrapped = 0;
|
|
54
443
|
const lines = text.split("\n");
|
|
55
444
|
const out: string[] = [];
|
|
@@ -90,6 +479,7 @@ const PUNCTUATION = 0.85; // The first of a run of ASCII punctuation; the rest o
|
|
|
90
479
|
const NEWLINE = 2.2;
|
|
91
480
|
const TAB = 1;
|
|
92
481
|
const LOOSE_SPACE = 0.2; // A space before anything but a letter. A space before a word is free.
|
|
482
|
+
const SPACE_RUN = 16; // A run of spaces costs a token for each this many after its first.
|
|
93
483
|
const LATIN_EXTENDED = 0.6; // é, ü, ß
|
|
94
484
|
const GREEK = 0.4;
|
|
95
485
|
const CYRILLIC = 0.3;
|
|
@@ -113,14 +503,23 @@ const SYMBOL = 1; // Dashes, quotes, arrows, box drawing, and anything unclassif
|
|
|
113
503
|
* of random letters in a single case with no digits (about 70% of the real count).
|
|
114
504
|
*/
|
|
115
505
|
export function estimateTokens(text: string): number {
|
|
116
|
-
|
|
506
|
+
return Math.ceil(tokensIn(text, 0, text.length, 0));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* The tokens of `text` from `from` to `to`, added to `tokens`. Every count starts again after a line
|
|
511
|
+
* break, so a text cut after line breaks gives, piece by piece, the sum it gives whole.
|
|
512
|
+
*/
|
|
513
|
+
function tokensIn(text: string, from: number, to: number, tokens: number): number {
|
|
117
514
|
// The current run of ASCII letters: its length since the last case change, and its casing.
|
|
118
515
|
let piece = 0;
|
|
119
516
|
let capitalsInARow = 0;
|
|
120
517
|
let previousWasLower = false;
|
|
121
518
|
let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
|
|
122
|
-
|
|
519
|
+
let spaces = 0; // the length of the current run of spaces
|
|
520
|
+
for (let index = from; index < to; index++) {
|
|
123
521
|
const code = text.charCodeAt(index);
|
|
522
|
+
if (code !== 32) spaces = 0;
|
|
124
523
|
if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
|
|
125
524
|
const capital = code <= 90;
|
|
126
525
|
if (piece === 0) tokens += WORD;
|
|
@@ -140,6 +539,10 @@ export function estimateTokens(text: string): number {
|
|
|
140
539
|
capitalsInARow = 0;
|
|
141
540
|
previousWasLower = false;
|
|
142
541
|
if (code === 32) {
|
|
542
|
+
// Tokenizers have tokens for runs of spaces up to a length: a long run costs about one token
|
|
543
|
+
// for every SPACE_RUN spaces after the first. Fixed-width reports and padded tables were
|
|
544
|
+
// planned at almost nothing, then refused by the provider.
|
|
545
|
+
if (++spaces > 1 && (spaces - 1) % SPACE_RUN === 0) tokens += 1;
|
|
143
546
|
previous = 1;
|
|
144
547
|
continue;
|
|
145
548
|
}
|
|
@@ -176,7 +579,7 @@ export function estimateTokens(text: string): number {
|
|
|
176
579
|
else if (code < 0xff00) tokens += OTHER_SCRIPT;
|
|
177
580
|
else tokens += KANA;
|
|
178
581
|
}
|
|
179
|
-
return
|
|
582
|
+
return tokens;
|
|
180
583
|
}
|
|
181
584
|
|
|
182
585
|
/**
|
|
@@ -187,9 +590,15 @@ export function estimateTokens(text: string): number {
|
|
|
187
590
|
* quarter or more, a novel by a hundredth.
|
|
188
591
|
*/
|
|
189
592
|
export function textSizes(text: string): { utf8: number; json: number } {
|
|
593
|
+
const { utf8, escapes } = sizesIn(text, 0, text.length);
|
|
594
|
+
return { utf8, json: utf8 + escapes + 2 };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** UTF-8 bytes and JSON escapes of `text` from `from` to `to`, which must not split a surrogate pair. */
|
|
598
|
+
function sizesIn(text: string, from: number, to: number): { utf8: number; escapes: number } {
|
|
190
599
|
let utf8 = 0;
|
|
191
600
|
let escapes = 0;
|
|
192
|
-
for (let index =
|
|
601
|
+
for (let index = from; index < to; index++) {
|
|
193
602
|
const code = text.charCodeAt(index);
|
|
194
603
|
if (code < 0x80) {
|
|
195
604
|
utf8 += 1;
|
|
@@ -197,7 +606,7 @@ export function textSizes(text: string): { utf8: number; json: number } {
|
|
|
197
606
|
else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
|
|
198
607
|
} else if (code < 0x800) {
|
|
199
608
|
utf8 += 2;
|
|
200
|
-
} else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
|
|
609
|
+
} else if (isHighSurrogate(code) && index + 1 < to && isLowSurrogate(text.charCodeAt(index + 1))) {
|
|
201
610
|
utf8 += 4;
|
|
202
611
|
index++;
|
|
203
612
|
} else {
|
|
@@ -206,7 +615,85 @@ export function textSizes(text: string): { utf8: number; json: number } {
|
|
|
206
615
|
if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
|
|
207
616
|
}
|
|
208
617
|
}
|
|
209
|
-
return { utf8,
|
|
618
|
+
return { utf8, escapes };
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Characters worked on between two looks at the clock while ingesting. */
|
|
622
|
+
const SLICE_CHARACTERS = 1 << 18;
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* The text cut into slices of about 256K characters, each ending after a line break (the last
|
|
626
|
+
* one at the end of the text), as `[from, to)` offsets.
|
|
627
|
+
*/
|
|
628
|
+
function* lineSlices(text: string): Generator<[number, number]> {
|
|
629
|
+
for (let from = 0; from < text.length;) {
|
|
630
|
+
let to = Math.min(text.length, from + SLICE_CHARACTERS);
|
|
631
|
+
if (to < text.length) {
|
|
632
|
+
const newline = text.indexOf("\n", to - 1);
|
|
633
|
+
to = newline === -1 ? text.length : newline + 1;
|
|
634
|
+
}
|
|
635
|
+
yield [from, to];
|
|
636
|
+
from = to;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* `estimateTokens` and `textSizes` of a text, the same numbers, worked out a slice at a time so
|
|
642
|
+
* that other requests get a turn while a large upload is measured. Slices end after a line break.
|
|
643
|
+
*/
|
|
644
|
+
export async function measureText(text: string, slicer: TimeSlicer): Promise<{ tokens: number; utf8: number; json: number }> {
|
|
645
|
+
let tokens = 0;
|
|
646
|
+
let utf8 = 0;
|
|
647
|
+
let escapes = 0;
|
|
648
|
+
for (const [from, to] of lineSlices(text)) {
|
|
649
|
+
tokens = tokensIn(text, from, to, tokens);
|
|
650
|
+
const sizes = sizesIn(text, from, to);
|
|
651
|
+
utf8 += sizes.utf8;
|
|
652
|
+
escapes += sizes.escapes;
|
|
653
|
+
await slicer.maybePause();
|
|
654
|
+
}
|
|
655
|
+
return { tokens: Math.ceil(tokens), utf8, json: utf8 + escapes + 2 };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* What ingest makes of extracted text, a slice at a time: `normalizeText`, then `wrapLongLines`,
|
|
660
|
+
* then the lines (a line break at the very end does not start another line). The same results as
|
|
661
|
+
* doing each in one go: no step of `normalizeText` reaches across a line break, and whether a U+0085
|
|
662
|
+
* ends lines is decided once, for the whole text. A slice that runs far past its size holds a long
|
|
663
|
+
* line: it is cleaned in pieces too. `onProgress` is told the characters of `raw` cleaned so far,
|
|
664
|
+
* after each slice; splitting the lines after that is quick, and is not counted.
|
|
665
|
+
*/
|
|
666
|
+
export async function prepareText(
|
|
667
|
+
raw: string,
|
|
668
|
+
slicer: TimeSlicer,
|
|
669
|
+
onProgress?: (done: number, total: number) => void,
|
|
670
|
+
): Promise<{ text: string; wrapped: number; lines: string[] }> {
|
|
671
|
+
const start = raw.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
672
|
+
const body = start === 1 ? raw.slice(1) : raw;
|
|
673
|
+
const nextLines = breaksAtNextLine(body);
|
|
674
|
+
const parts: string[] = [];
|
|
675
|
+
// A clean text (most logs) comes back as it is: joining its slices would copy all of it.
|
|
676
|
+
let changed = false;
|
|
677
|
+
for (const [from, to] of lineSlices(body)) {
|
|
678
|
+
const slice = body.slice(from, to);
|
|
679
|
+
const normalized = slice.length > 2 * SLICE_CHARACTERS ? await normalizeInPieces(slice, slicer, nextLines) : normalizeLines(slice, nextLines);
|
|
680
|
+
if (normalized !== slice) changed = true;
|
|
681
|
+
parts.push(normalized);
|
|
682
|
+
onProgress?.(start + to, raw.length);
|
|
683
|
+
await slicer.maybePause();
|
|
684
|
+
}
|
|
685
|
+
const { text, wrapped } = wrapLongLines(!changed ? body : parts.length === 1 ? parts[0]! : parts.join(""));
|
|
686
|
+
parts.length = 0;
|
|
687
|
+
await slicer.maybePause();
|
|
688
|
+
const lines: string[] = [];
|
|
689
|
+
for (const [from, to] of lineSlices(text)) {
|
|
690
|
+
const piece = text.slice(from, to).split("\n");
|
|
691
|
+
// A slice that ends with a line break splits into one empty string too many.
|
|
692
|
+
if (text.charCodeAt(to - 1) === 10) piece.pop();
|
|
693
|
+
for (const line of piece) lines.push(line);
|
|
694
|
+
await slicer.maybePause();
|
|
695
|
+
}
|
|
696
|
+
return { text, wrapped, lines };
|
|
210
697
|
}
|
|
211
698
|
|
|
212
699
|
/** UTF-8 byte length without allocating an encoded copy. */
|
|
@@ -271,6 +758,20 @@ export class LineIndex {
|
|
|
271
758
|
return this.text.slice(this.startOf(line), this.endOf(line));
|
|
272
759
|
}
|
|
273
760
|
|
|
761
|
+
/**
|
|
762
|
+
* Lines `first` to `last`, which must exist, as a text of their own with its index: their text,
|
|
763
|
+
* with the line break after the last one when there is one, as a document read by range gives
|
|
764
|
+
* a piece of itself. Offsets in it are counted from `startOf(first)`.
|
|
765
|
+
*/
|
|
766
|
+
piece(first: number, last: number): { text: string; lines: LineIndex } {
|
|
767
|
+
const start = this.startOf(first);
|
|
768
|
+
const end = last < this.lineCount ? this.starts[last]! : this.text.length;
|
|
769
|
+
const starts = new Uint32Array(last - first + 1);
|
|
770
|
+
for (let line = 0; line < starts.length; line++) starts[line] = this.starts[first - 1 + line]! - start;
|
|
771
|
+
const text = this.text.slice(start, end);
|
|
772
|
+
return { text, lines: new LineIndex(text, starts) };
|
|
773
|
+
}
|
|
774
|
+
|
|
274
775
|
/** Lines `from`..`to` inclusive, each prefixed with its number. */
|
|
275
776
|
numbered(from: number, to: number): string {
|
|
276
777
|
const out: string[] = [];
|