llm-large-files 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +370 -1
  2. package/README.md +12 -8
  3. package/dist/aggregate.d.ts +103 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +651 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/analyze.d.ts +3 -1
  8. package/dist/analyze.d.ts.map +1 -1
  9. package/dist/analyze.js +109 -14
  10. package/dist/analyze.js.map +1 -1
  11. package/dist/anthropic/adapter.d.ts.map +1 -1
  12. package/dist/anthropic/adapter.js +4 -1
  13. package/dist/anthropic/adapter.js.map +1 -1
  14. package/dist/ask.d.ts +3 -3
  15. package/dist/ask.d.ts.map +1 -1
  16. package/dist/ask.js +72 -17
  17. package/dist/ask.js.map +1 -1
  18. package/dist/decode.d.ts +19 -0
  19. package/dist/decode.d.ts.map +1 -0
  20. package/dist/decode.js +97 -0
  21. package/dist/decode.js.map +1 -0
  22. package/dist/errors.d.ts +55 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js +65 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/events.d.ts +6 -0
  27. package/dist/events.d.ts.map +1 -1
  28. package/dist/events.js +5 -1
  29. package/dist/events.js.map +1 -1
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +23 -0
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +12 -18
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +82 -746
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts.map +1 -1
  38. package/dist/gemini/adapter.js +9 -5
  39. package/dist/gemini/adapter.js.map +1 -1
  40. package/dist/gemini/endpoints.d.ts +5 -1
  41. package/dist/gemini/endpoints.d.ts.map +1 -1
  42. package/dist/gemini/endpoints.js +11 -2
  43. package/dist/gemini/endpoints.js.map +1 -1
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +20 -3
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/groups.d.ts +54 -0
  48. package/dist/groups.d.ts.map +1 -0
  49. package/dist/groups.js +136 -0
  50. package/dist/groups.js.map +1 -0
  51. package/dist/html.d.ts +11 -0
  52. package/dist/html.d.ts.map +1 -0
  53. package/dist/html.js +1112 -0
  54. package/dist/html.js.map +1 -0
  55. package/dist/index.d.ts +2 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/library.d.ts.map +1 -1
  60. package/dist/library.js +57 -14
  61. package/dist/library.js.map +1 -1
  62. package/dist/limiter.d.ts +2 -1
  63. package/dist/limiter.d.ts.map +1 -1
  64. package/dist/limiter.js +3 -2
  65. package/dist/limiter.js.map +1 -1
  66. package/dist/model.d.ts.map +1 -1
  67. package/dist/model.js +8 -1
  68. package/dist/model.js.map +1 -1
  69. package/dist/node/handlers.d.ts.map +1 -1
  70. package/dist/node/handlers.js +69 -15
  71. package/dist/node/handlers.js.map +1 -1
  72. package/dist/node/index.d.ts +2 -0
  73. package/dist/node/index.d.ts.map +1 -1
  74. package/dist/node/index.js +1 -0
  75. package/dist/node/index.js.map +1 -1
  76. package/dist/node/ingest-child.d.ts +38 -0
  77. package/dist/node/ingest-child.d.ts.map +1 -0
  78. package/dist/node/ingest-child.js +42 -0
  79. package/dist/node/ingest-child.js.map +1 -0
  80. package/dist/node/isolated.d.ts +88 -0
  81. package/dist/node/isolated.d.ts.map +1 -0
  82. package/dist/node/isolated.js +381 -0
  83. package/dist/node/isolated.js.map +1 -0
  84. package/dist/office.d.ts +105 -0
  85. package/dist/office.d.ts.map +1 -0
  86. package/dist/office.js +1092 -0
  87. package/dist/office.js.map +1 -0
  88. package/dist/openai/adapter.d.ts.map +1 -1
  89. package/dist/openai/adapter.js +15 -1
  90. package/dist/openai/adapter.js.map +1 -1
  91. package/dist/pdf-pages.d.ts.map +1 -1
  92. package/dist/pdf-pages.js +2 -6
  93. package/dist/pdf-pages.js.map +1 -1
  94. package/dist/peers.d.ts +8 -0
  95. package/dist/peers.d.ts.map +1 -0
  96. package/dist/peers.js +32 -0
  97. package/dist/peers.js.map +1 -0
  98. package/dist/plan.d.ts +3 -1
  99. package/dist/plan.d.ts.map +1 -1
  100. package/dist/plan.js +17 -1
  101. package/dist/plan.js.map +1 -1
  102. package/dist/quality.d.ts +16 -0
  103. package/dist/quality.d.ts.map +1 -0
  104. package/dist/quality.js +157 -0
  105. package/dist/quality.js.map +1 -0
  106. package/dist/ranged.d.ts.map +1 -1
  107. package/dist/ranged.js +4 -2
  108. package/dist/ranged.js.map +1 -1
  109. package/dist/search.d.ts +99 -22
  110. package/dist/search.d.ts.map +1 -1
  111. package/dist/search.js +744 -140
  112. package/dist/search.js.map +1 -1
  113. package/dist/text-index.d.ts +3 -1
  114. package/dist/text-index.d.ts.map +1 -1
  115. package/dist/text-index.js +3 -1
  116. package/dist/text-index.js.map +1 -1
  117. package/dist/text.d.ts +27 -3
  118. package/dist/text.d.ts.map +1 -1
  119. package/dist/text.js +225 -23
  120. package/dist/text.js.map +1 -1
  121. package/dist/tools.d.ts +9 -0
  122. package/dist/tools.d.ts.map +1 -1
  123. package/dist/tools.js +457 -16
  124. package/dist/tools.js.map +1 -1
  125. package/dist/types.d.ts +23 -3
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/word-styles.d.ts +102 -0
  128. package/dist/word-styles.d.ts.map +1 -0
  129. package/dist/word-styles.js +419 -0
  130. package/dist/word-styles.js.map +1 -0
  131. package/dist/xlsx.d.ts +23 -0
  132. package/dist/xlsx.d.ts.map +1 -0
  133. package/dist/xlsx.js +511 -0
  134. package/dist/xlsx.js.map +1 -0
  135. package/dist/xml-stream.d.ts +55 -0
  136. package/dist/xml-stream.d.ts.map +1 -0
  137. package/dist/xml-stream.js +235 -0
  138. package/dist/xml-stream.js.map +1 -0
  139. package/docs/README.md +8 -8
  140. package/docs/getting-started.md +1 -1
  141. package/docs/guides/costs-and-limits.md +7 -5
  142. package/docs/guides/deployment.md +95 -29
  143. package/docs/guides/errors-and-reliability.md +23 -10
  144. package/docs/guides/pdfs.md +127 -74
  145. package/docs/guides/storage.md +1 -1
  146. package/docs/guides/testing.md +5 -1
  147. package/docs/guides/web-app.md +10 -9
  148. package/docs/how-it-works.md +80 -50
  149. package/docs/reference/ask.md +26 -8
  150. package/docs/reference/errors-and-retries.md +5 -3
  151. package/docs/reference/events.md +14 -6
  152. package/docs/reference/gemini.md +6 -2
  153. package/docs/reference/library.md +221 -79
  154. package/docs/reference/node.md +201 -23
  155. package/docs/reference/openai.md +1 -1
  156. package/docs/reference/tools.md +269 -23
  157. package/docs/security.md +114 -69
  158. package/docs/troubleshooting.md +40 -20
  159. package/package.json +6 -2
  160. package/src/aggregate.ts +674 -0
  161. package/src/analyze.ts +117 -13
  162. package/src/anthropic/adapter.ts +4 -1
  163. package/src/ask.ts +73 -17
  164. package/src/decode.ts +89 -0
  165. package/src/errors.ts +108 -0
  166. package/src/events.ts +10 -1
  167. package/src/evidence.ts +23 -0
  168. package/src/extract.ts +79 -701
  169. package/src/gemini/adapter.ts +9 -5
  170. package/src/gemini/endpoints.ts +12 -2
  171. package/src/gemini/generate.ts +19 -3
  172. package/src/groups.ts +162 -0
  173. package/src/html.ts +1071 -0
  174. package/src/index.ts +2 -1
  175. package/src/library.ts +52 -14
  176. package/src/limiter.ts +6 -1
  177. package/src/model.ts +8 -1
  178. package/src/node/handlers.ts +66 -16
  179. package/src/node/index.ts +2 -0
  180. package/src/node/ingest-child.ts +61 -0
  181. package/src/node/isolated.ts +464 -0
  182. package/src/office.ts +1047 -0
  183. package/src/openai/adapter.ts +14 -1
  184. package/src/pdf-pages.ts +2 -5
  185. package/src/peers.ts +29 -0
  186. package/src/plan.ts +19 -1
  187. package/src/quality.ts +146 -0
  188. package/src/ranged.ts +4 -2
  189. package/src/search.ts +738 -146
  190. package/src/text-index.ts +4 -2
  191. package/src/text.ts +214 -23
  192. package/src/tools.ts +440 -16
  193. package/src/types.ts +20 -3
  194. package/src/word-styles.ts +420 -0
  195. package/src/xlsx.ts +478 -0
  196. package/src/xml-stream.ts +224 -0
@@ -209,7 +209,13 @@ function detailText(detail: unknown): string | undefined {
209
209
  return detail.map((problem) => (typeof (problem as Json | null)?.msg === "string" ? (problem as Json).msg as string : "")).filter(Boolean).join("; ") || undefined;
210
210
  }
211
211
 
212
- /** An error event inside a stream that began with 200, with the server's own word for it. */
212
+ /** The error a reply that came with 200 holds instead of choices, when it holds one. */
213
+ function bodyError(data: unknown): unknown {
214
+ const body = (Array.isArray(data) ? data[0] : data) as Json | null | undefined;
215
+ return body && typeof body === "object" && body.error ? body.error : undefined;
216
+ }
217
+
218
+ /** An error event inside a stream, or a body, that began with 200, with the server's own word for it. */
213
219
  function streamFailure(failed: unknown): OpenAiRequestError {
214
220
  const named = failed && typeof failed === "object" ? failed as Json : {};
215
221
  return new OpenAiRequestError(typeof failed === "string" ? failed : String(named.message ?? "The model reported an error."), streamErrorStatus(failed), {
@@ -404,6 +410,10 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
404
410
  response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
405
411
  }
406
412
  const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
413
+ // An error in a body that came with 200 (OpenRouter, once generation has started): thrown as
414
+ // a stream's error is, with its status, so that a 502 is sent again rather than read as no text.
415
+ const failed = bodyError(data);
416
+ if (failed) throw streamFailure(failed);
407
417
  const used = usageOf(data.usage);
408
418
  onUsage?.(used);
409
419
  const choice = data.choices?.[0];
@@ -548,6 +558,9 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
548
558
  } else {
549
559
  // In one piece: no streaming was asked for, or the server answered without it.
550
560
  const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notJson);
561
+ // An error in a body that came with 200, as a stream may send one: not an empty reply.
562
+ const failed = bodyError(data);
563
+ if (failed) throw streamFailure(failed);
551
564
  const choice = data.choices?.[0] as Json | undefined;
552
565
  message = (choice?.message ?? { role: "assistant", content: null }) as Json;
553
566
  finish = choice?.finish_reason;
package/src/pdf-pages.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  * - a wanted page gets its own resource dictionary, without the images it does not paint.
10
10
  */
11
11
  import { getHeapStatistics } from "node:v8";
12
+ import { importPeer } from "./peers.js";
12
13
  import type { PDFContext, PDFDict, PDFObject, PDFObjectCopier, PDFPage, PDFPageLeaf, PDFRef } from "@cantoo/pdf-lib";
13
14
  import { TimeSlicer } from "./pause.js";
14
15
  import { formatBytes } from "./plan.js";
@@ -208,11 +209,7 @@ export function latin1(bytes: Uint8Array): string {
208
209
  }
209
210
 
210
211
  export async function loadPdfLibrary(): Promise<PdfLibrary> {
211
- try {
212
- return await import("@cantoo/pdf-lib");
213
- } catch {
214
- throw new Error("Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
215
- }
212
+ return importPeer("@cantoo/pdf-lib", () => import("@cantoo/pdf-lib"), "Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
216
213
  }
217
214
 
218
215
  /**
package/src/peers.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Loads an optional dependency. When it is not installed, the error says so in `missing`, words for
3
+ * a user ("Reading PDF files needs the optional dependency \"unpdf\"."). When it is installed but
4
+ * fails to load (a version this Node cannot run, a broken install), the error says that, with the
5
+ * reason, and keeps the failure as its cause: it was reported as missing before 0.8.0.
6
+ */
7
+ export async function importPeer<T>(name: string, load: () => Promise<T>, missing: string): Promise<T> {
8
+ try {
9
+ return await load();
10
+ } catch (error) {
11
+ if (notFound(error, name)) throw new Error(missing, { cause: error });
12
+ const reason = error instanceof Error ? error.message : String(error);
13
+ throw new Error(`The optional dependency "${name}" is installed but could not be loaded (${reason.split("\n")[0]}). Reinstall it, or install a version this Node can run.`, { cause: error });
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Whether an import failed because the package is not installed: Node's code, or the words of Node
19
+ * and of bundlers that give none, about this package and not one it needs. A loader that wraps the
20
+ * failure (a test runner's mock) keeps it as a cause, looked at too.
21
+ */
22
+ function notFound(error: unknown, name: string): boolean {
23
+ for (let current = error, depth = 0; current && depth < 4; current = (current as { cause?: unknown }).cause, depth++) {
24
+ const { code, message } = current as { code?: unknown; message?: unknown };
25
+ if (typeof message === "string" && message.includes(name)
26
+ && (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || /Cannot find (?:package|module)/.test(message))) return true;
27
+ }
28
+ return false;
29
+ }
package/src/plan.ts CHANGED
@@ -1,5 +1,9 @@
1
+ import { pageList } from "./quality.js";
1
2
  import { plural, sliceWhole, wellFormed } from "./text.js";
2
- import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
3
+ import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
4
+
5
+ /** Formats whose documents may hold a table that `aggregate_table` reads. */
6
+ export const TABLE_FORMATS: ReadonlySet<DocumentFormat> = new Set<DocumentFormat>(["csv", "xlsx", "docx", "pptx", "pdf", "html", "markdown"]);
3
7
 
4
8
  /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
9
  export const REQUEST_BYTES_MARGIN = 256 * 1024;
@@ -159,6 +163,7 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
159
163
  HOW_TO_READ[wholeRead],
160
164
  ...(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."] : []),
161
165
  ...(note ? [note] : []),
166
+ ...qualityLines(meta, viewable),
162
167
  ];
163
168
  const profile = meta.logProfile;
164
169
  if (profile) {
@@ -180,6 +185,16 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
180
185
  return out.join("\n");
181
186
  }
182
187
 
188
+ /** What the card says of the quality of a document's text (see `measureQuality`). */
189
+ function qualityLines(meta: DocumentMeta, viewable: boolean): string[] {
190
+ const out: string[] = [];
191
+ const look = viewable ? " Look at them with view_pages." : "";
192
+ if (meta.pagesWithoutText?.length) out.push(`Pages without text (scans, photos or charts, whose content is not in the text): ${pageList(meta.pagesWithoutText)}.${look}`);
193
+ if (meta.garbledPages?.length) out.push(`Pages whose text looks garbled, not to be relied on: ${pageList(meta.garbledPages)}.${look}`);
194
+ if (meta.scripts?.length) out.push(`Written in: ${meta.scripts.map((share) => `${share.script} ${share.percent}%`).join(", ")}. Search in the language of the text.`);
195
+ return out;
196
+ }
197
+
183
198
  /**
184
199
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
185
200
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
@@ -197,6 +212,9 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
197
212
  "You see only a summary card for each. Read them through the tools:",
198
213
  "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
199
214
  "- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
215
+ "- To count per group (per hour or day, per error code or ID with a regex group, per message shape), pass group_by: one call gives every count. For more matches than a result shows, search again from its next_from_line, or with order \"last\" for the last ones.",
216
+ "- Search for the bare form of a word: a search matches inside longer words, so \"timeout\" also finds \"timeouts\", and a Hebrew word without its prefix letters (חוזה, not בחוזה) finds every form of it.",
217
+ ...(searchable.some((meta) => TABLE_FORMATS.has(meta.format)) ? ["- To add up, average, count or group the rows of a table (a CSV, an Excel sheet, a | cell | table), use aggregate_table: it reads every row, and its numbers are exact. Do not add numbers up from rows you read."] : []),
200
218
  "- read_document reads a line range. Read around search hits before you rely on them.",
201
219
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
202
220
  ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),
package/src/quality.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { TimeSlicer } from "./pause.js";
2
+ import type { DocumentFormat, DocumentMeta } from "./types.js";
3
+
4
+ /**
5
+ * Signs of the quality of a document's text, worked out at ingest and shown on its card, so the
6
+ * model knows where the text cannot be trusted before it relies on it:
7
+ * - the pages of a PDF that have no text (a scan, a photo), and those whose text layer looks
8
+ * garbled (fonts without a Unicode map give "ÞÞÞ" or "�����");
9
+ * - the scripts the text is written in, when it is not Latin alone: a Hebrew file is searched in
10
+ * Hebrew.
11
+ */
12
+ export type TextQuality = Pick<DocumentMeta, "pagesWithoutText" | "garbledPages" | "scripts">;
13
+
14
+ /** Page numbers kept in a list, at most. */
15
+ const MAX_LISTED_PAGES = 200;
16
+ /** Characters of the text the script shares are counted over. */
17
+ const SCRIPT_SAMPLE = 2 * 1024 * 1024;
18
+ /** Letters needed before shares are given. */
19
+ const MIN_LETTERS = 200;
20
+ /** A script is named when it has at least this share of the letters, in percent. */
21
+ const MIN_SHARE = 5;
22
+ /** A page is judged garbled only with at least this many characters that are not white space. */
23
+ const MIN_PAGE_CHARACTERS = 40;
24
+
25
+ const PAGE_LINE = /^--- Page (\d+) ---$/;
26
+ const NO_TEXT_LINE = "[No text on this page. It may be a scan, a photo, or a chart.]";
27
+ const PICTURE_LINE = "[Picture on this page. This text cannot show it.]";
28
+
29
+ /**
30
+ * The script of the letter at `at`, or undefined when it is not a letter. The common scripts are
31
+ * known by their code points, with no regular expression; only rarer blocks are tested.
32
+ */
33
+ function letterScript(text: string, at: number): string | undefined {
34
+ const code = text.charCodeAt(at);
35
+ if (code < 0x80) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) ? "Latin" : undefined;
36
+ if (code >= 0x5d0 && code <= 0x5f2) return code <= 0x5ea || code >= 0x5f0 ? "Hebrew" : undefined;
37
+ if (code >= 0x591 && code <= 0x5cf) return undefined; // Hebrew points and marks
38
+ if (code >= 0xc0 && code <= 0x24f) return code === 0xd7 || code === 0xf7 ? undefined : "Latin";
39
+ if ((code >= 0x620 && code <= 0x64a) || (code >= 0x671 && code <= 0x6d3)) return "Arabic";
40
+ if (code >= 0x410 && code <= 0x44f) return "Cyrillic";
41
+ if (code >= 0x4e00 && code <= 0x9fff) return "CJK";
42
+ if (code >= 0xdc00 && code <= 0xdfff) return undefined;
43
+ const character = code >= 0xd800 && code <= 0xdbff ? text.slice(at, at + 2) : text[at]!;
44
+ return LETTER.test(character) ? scriptOf(character.codePointAt(0)!) : undefined;
45
+ }
46
+
47
+ /** The script of a letter, by its code point. */
48
+ function scriptOf(code: number): string {
49
+ if (code < 0x250) return "Latin";
50
+ if (code >= 0x370 && code < 0x400) return "Greek";
51
+ if (code >= 0x400 && code < 0x530) return "Cyrillic";
52
+ if (code >= 0x590 && code < 0x600) return "Hebrew";
53
+ if ((code >= 0x600 && code < 0x780) || (code >= 0xfb50 && code < 0xfe00) || (code >= 0xfe70 && code < 0xff00)) return "Arabic";
54
+ if (code >= 0xfb1d && code < 0xfb50) return "Hebrew";
55
+ if (code >= 0x900 && code < 0x980) return "Devanagari";
56
+ if (code >= 0xe00 && code < 0xe80) return "Thai";
57
+ if ((code >= 0x3040 && code < 0x3100) || (code >= 0x3400 && code < 0xa000) || (code >= 0xac00 && code < 0xd7b0) || (code >= 0x1100 && code < 0x1200)) return "CJK";
58
+ if (code >= 0x1e00 && code < 0x1f00) return "Latin";
59
+ return "other";
60
+ }
61
+
62
+ const LETTER = /\p{L}/u;
63
+
64
+ /** The text quality of a document, from its lines (see `TextQuality`). */
65
+ export async function measureQuality(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<TextQuality> {
66
+ const empty: number[] = [];
67
+ const garbled: number[] = [];
68
+ let emptyCount = 0;
69
+ let garbledCount = 0;
70
+ // The page being read: its number, its characters that are not white space, its letters and
71
+ // digits, its replacement characters, and whether it said it has no text.
72
+ let page = 0;
73
+ let characters = 0;
74
+ let wordy = 0;
75
+ let replaced = 0;
76
+ let noText = false;
77
+ const endPage = () => {
78
+ if (page === 0) return;
79
+ if (noText && characters === 0) {
80
+ emptyCount++;
81
+ if (empty.length < MAX_LISTED_PAGES) empty.push(page);
82
+ } else if (characters >= MIN_PAGE_CHARACTERS && (wordy / characters < 0.3 || replaced > Math.max(6, characters * 0.03))) {
83
+ garbledCount++;
84
+ if (garbled.length < MAX_LISTED_PAGES) garbled.push(page);
85
+ }
86
+ };
87
+ const letters = new Map<string, number>();
88
+ let sampled = 0;
89
+ let total = 0;
90
+ /** Adds a line of a PDF page to its counts, a character code at a time. */
91
+ const countPage = (line: string) => {
92
+ for (let at = 0; at < line.length; at++) {
93
+ const code = line.charCodeAt(at);
94
+ if (code === 32 || code === 9 || code === 0xa0 || code === 0x202f) continue;
95
+ // The second half of a character outside the basic plane is counted with its first.
96
+ if (code >= 0xdc00 && code <= 0xdfff) continue;
97
+ characters++;
98
+ if (code === 0xfffd) replaced++;
99
+ else if ((code >= 48 && code <= 57) || letterScript(line, at) !== undefined) wordy++;
100
+ }
101
+ };
102
+ for (let index = 0; index < lines.length; index++) {
103
+ if ((index & 4095) === 4095) await slicer.maybePause();
104
+ const line = lines[index]!;
105
+ if (format === "pdf") {
106
+ const header = PAGE_LINE.exec(line);
107
+ if (header && Number(header[1]) === page + 1) {
108
+ endPage();
109
+ page++;
110
+ characters = wordy = replaced = 0;
111
+ noText = false;
112
+ continue;
113
+ }
114
+ if (line === NO_TEXT_LINE) {
115
+ noText = true;
116
+ continue;
117
+ }
118
+ if (line !== PICTURE_LINE) countPage(line);
119
+ }
120
+ if (sampled < SCRIPT_SAMPLE) {
121
+ sampled += line.length + 1;
122
+ for (let at = 0; at < line.length; at++) {
123
+ const script = letterScript(line, at);
124
+ if (script === undefined) continue;
125
+ letters.set(script, (letters.get(script) ?? 0) + 1);
126
+ total++;
127
+ }
128
+ }
129
+ }
130
+ endPage();
131
+ const shares = total >= MIN_LETTERS
132
+ ? [...letters].map(([script, count]) => ({ script, percent: Math.round((count / total) * 100) })).filter((share) => share.percent >= MIN_SHARE && share.script !== "other").sort((left, right) => right.percent - left.percent)
133
+ : [];
134
+ const notLatinOnly = shares.some((share) => share.script !== "Latin");
135
+ return {
136
+ ...(emptyCount > 0 ? { pagesWithoutText: empty } : {}),
137
+ ...(garbledCount > 0 ? { garbledPages: garbled } : {}),
138
+ ...(notLatinOnly ? { scripts: shares } : {}),
139
+ };
140
+ }
141
+
142
+ /** Page numbers as a short list: "3, 7, 12" or "3, 7, 12 and 40 more". */
143
+ export function pageList(pages: number[], shown = 12): string {
144
+ const listed = pages.slice(0, shown).join(", ");
145
+ return pages.length > shown ? `${listed} and ${pages.length - shown} more` : listed;
146
+ }
package/src/ranged.ts CHANGED
@@ -44,7 +44,9 @@ export const pieceKey = (id: string, at: number) => `${id}#${at}`;
44
44
  const BUILD_READ_BYTES = 4 * 1024 * 1024;
45
45
  /** A pass shared by several scans lets other work run after this much time on the main thread. */
46
46
  const YIELD_AFTER_MS = 15;
47
- const decoder = new TextDecoder("utf-8");
47
+ // `ignoreBOM`: every decode is a stream of its own, and would drop a U+FEFF that starts it. A range
48
+ // starts at a line, so a line that began with one lost it, and its piece no longer matched the index.
49
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
48
50
 
49
51
  const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
50
52
 
@@ -347,7 +349,7 @@ export async function openRangedDocument(
347
349
  if (!index) return undefined;
348
350
  // An index that disagrees with the metadata describes a text that is not what was ingested.
349
351
  // It is used, since it is what the store holds, but not saved.
350
- if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters) {
352
+ if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && (meta.textBytes === undefined || index.textBytes === meta.textBytes)) {
351
353
  await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
352
354
  }
353
355
  }