llm-large-files 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/cache.d.ts +40 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +81 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/extract.d.ts +1 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +204 -22
  9. package/dist/extract.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/library.d.ts +28 -1
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +155 -47
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +20 -0
  19. package/dist/limiter.d.ts.map +1 -0
  20. package/dist/limiter.js +55 -0
  21. package/dist/limiter.js.map +1 -0
  22. package/dist/map-reduce.d.ts +8 -4
  23. package/dist/map-reduce.d.ts.map +1 -1
  24. package/dist/map-reduce.js +65 -24
  25. package/dist/map-reduce.js.map +1 -1
  26. package/dist/node/handlers.d.ts +9 -0
  27. package/dist/node/handlers.d.ts.map +1 -1
  28. package/dist/node/handlers.js +56 -13
  29. package/dist/node/handlers.js.map +1 -1
  30. package/dist/pdf-pictures.d.ts.map +1 -1
  31. package/dist/pdf-pictures.js +52 -9
  32. package/dist/pdf-pictures.js.map +1 -1
  33. package/dist/plan.d.ts +7 -5
  34. package/dist/plan.d.ts.map +1 -1
  35. package/dist/plan.js +9 -8
  36. package/dist/plan.js.map +1 -1
  37. package/dist/ranged.d.ts +102 -0
  38. package/dist/ranged.d.ts.map +1 -0
  39. package/dist/ranged.js +314 -0
  40. package/dist/ranged.js.map +1 -0
  41. package/dist/search.d.ts +79 -15
  42. package/dist/search.d.ts.map +1 -1
  43. package/dist/search.js +388 -130
  44. package/dist/search.js.map +1 -1
  45. package/dist/stores.d.ts +22 -2
  46. package/dist/stores.d.ts.map +1 -1
  47. package/dist/stores.js +132 -15
  48. package/dist/stores.js.map +1 -1
  49. package/dist/text-index.d.ts +64 -0
  50. package/dist/text-index.d.ts.map +1 -0
  51. package/dist/text-index.js +211 -0
  52. package/dist/text-index.js.map +1 -0
  53. package/dist/text.d.ts +2 -1
  54. package/dist/text.d.ts.map +1 -1
  55. package/dist/text.js +13 -4
  56. package/dist/text.js.map +1 -1
  57. package/dist/tools.d.ts +2 -2
  58. package/dist/tools.d.ts.map +1 -1
  59. package/dist/tools.js +20 -14
  60. package/dist/tools.js.map +1 -1
  61. package/dist/types.d.ts +15 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/docs/api.md +21 -5
  64. package/docs/configuration.md +50 -4
  65. package/docs/getting-started.md +3 -1
  66. package/docs/how-it-works.md +3 -1
  67. package/docs/security.md +8 -0
  68. package/package.json +7 -3
  69. package/src/cache.ts +83 -0
  70. package/src/extract.ts +198 -19
  71. package/src/index.ts +1 -1
  72. package/src/library.ts +176 -44
  73. package/src/limiter.ts +51 -0
  74. package/src/map-reduce.ts +70 -25
  75. package/src/node/handlers.ts +61 -9
  76. package/src/pdf-pictures.ts +60 -10
  77. package/src/plan.ts +10 -9
  78. package/src/ranged.ts +348 -0
  79. package/src/search.ts +432 -120
  80. package/src/stores.ts +136 -17
  81. package/src/text-index.ts +228 -0
  82. package/src/text.ts +13 -4
  83. package/src/tools.ts +22 -16
  84. package/src/types.ts +15 -0
package/dist/search.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createContext, Script } from "node:vm";
2
+ import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
2
3
  import { foldCase, LineIndex } from "./text.js";
3
- const PASSAGE_CHARACTERS = 1_500;
4
- const PASSAGE_MAX_LINES = 40;
5
4
  const MAX_OCCURRENCES_PER_TERM = 200_000;
5
+ const MAX_EXACT_MATCHES = 1_000_000;
6
+ const MAX_PHRASE_PASSAGES = 10_000;
6
7
  const REGEX_TIME_LIMIT_MS = 3_000;
7
8
  const SHOWN_LINE_CHARACTERS = 400;
8
9
  const STOPWORDS = new Set([
@@ -10,19 +11,54 @@ const STOPWORDS = new Set([
10
11
  "from", "into", "about", "does", "did", "have", "has", "had", "you", "your", "can", "all", "any", "not",
11
12
  "של", "את", "על", "עם", "מה", "איך", "למה", "מתי", "איפה", "מי", "זה", "זאת", "גם", "או", "אם", "כל", "יש", "אין",
12
13
  ]);
13
- /** A stored document with lazily built search structures. Build once, query many times. */
14
+ /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
15
+ export async function scanSource(source, feed, signal) {
16
+ if (source.scan)
17
+ return source.scan(feed, signal);
18
+ for await (const chunk of source.chunks(signal))
19
+ if (feed(chunk) === true)
20
+ break;
21
+ }
22
+ /** Lines as the tools show them: "12| text", one a line. */
23
+ export function numberLines(lines, from) {
24
+ return lines.map((text, index) => `${from + index}| ${text}`).join("\n");
25
+ }
26
+ /** The pages a range of lines is on, as "12" or "12-14", from the first line of each page. */
27
+ export function pagesOfLines(pageStarts, from, to) {
28
+ const page = (line) => (pageStarts.length === 0 || line < pageStarts[0] ? undefined : positionOf(pageStarts, line));
29
+ const last = page(to);
30
+ if (last === undefined)
31
+ return undefined;
32
+ const first = page(from) ?? 1;
33
+ return first === last ? String(last) : `${first}-${last}`;
34
+ }
35
+ /** A stored document held whole in memory, with lazily built search structures. */
14
36
  export class SearchableDocument {
15
37
  meta;
16
38
  text;
17
39
  lines;
18
40
  lowerText;
19
- passageStarts;
41
+ passageStartList;
20
42
  pageStarts;
21
43
  constructor(document) {
22
44
  this.meta = document.meta;
23
45
  this.text = document.text;
24
46
  this.lines = new LineIndex(document.text);
25
47
  }
48
+ get lineCount() {
49
+ return this.lines.lineCount;
50
+ }
51
+ get characters() {
52
+ return this.text.length;
53
+ }
54
+ /**
55
+ * Memory this document takes once it has been searched: the text, its lowercased copy, and the
56
+ * line index. A text of ASCII only is held at one byte a character, any other at two.
57
+ */
58
+ get memoryBytes() {
59
+ const ascii = this.meta.textBytes !== undefined && this.meta.textBytes === this.text.length;
60
+ return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 4 + 1_024;
61
+ }
26
62
  /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
27
63
  get lower() {
28
64
  this.lowerText ??= foldCase(this.text);
@@ -30,7 +66,7 @@ export class SearchableDocument {
30
66
  }
31
67
  /** First line of each passage: groups of lines up to about 1,500 characters. */
32
68
  get passages() {
33
- if (!this.passageStarts) {
69
+ if (!this.passageStartList) {
34
70
  const starts = [];
35
71
  let line = 1;
36
72
  while (line <= this.lines.lineCount) {
@@ -43,26 +79,19 @@ export class SearchableDocument {
43
79
  line++;
44
80
  }
45
81
  }
46
- this.passageStarts = starts;
82
+ this.passageStartList = starts;
47
83
  }
48
- return this.passageStarts;
84
+ return this.passageStartList;
85
+ }
86
+ get passageStarts() {
87
+ return this.passages;
49
88
  }
50
89
  passageRange(index) {
51
90
  const starts = this.passages;
52
91
  return { from: starts[index], to: (starts[index + 1] ?? this.lines.lineCount + 1) - 1 };
53
92
  }
54
93
  passageOfLine(line) {
55
- const starts = this.passages;
56
- let low = 0;
57
- let high = starts.length - 1;
58
- while (low < high) {
59
- const middle = (low + high + 1) >> 1;
60
- if (starts[middle] <= line)
61
- low = middle;
62
- else
63
- high = middle - 1;
64
- }
65
- return low;
94
+ return positionOf(this.passages, line) - 1;
66
95
  }
67
96
  /**
68
97
  * The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
@@ -70,6 +99,30 @@ export class SearchableDocument {
70
99
  * used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
71
100
  */
72
101
  pageOfLine(line) {
102
+ const starts = this.pageLines();
103
+ return starts.length === 0 || line < starts[0] ? undefined : positionOf(starts, line);
104
+ }
105
+ /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
106
+ pagesOfLines(from, to) {
107
+ return pagesOfLines(this.pageLines(), from, to);
108
+ }
109
+ async readLines(from, to) {
110
+ const out = [];
111
+ for (let line = Math.max(1, from); line <= Math.min(to, this.lines.lineCount); line++)
112
+ out.push(this.lines.line(line));
113
+ return out;
114
+ }
115
+ async readText() {
116
+ return this.text;
117
+ }
118
+ /** The whole text as one piece. */
119
+ wholeChunk() {
120
+ return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
121
+ }
122
+ async *chunks() {
123
+ yield this.wholeChunk();
124
+ }
125
+ pageLines() {
73
126
  if (!this.pageStarts) {
74
127
  const starts = [];
75
128
  const marker = "--- Page ";
@@ -82,27 +135,7 @@ export class SearchableDocument {
82
135
  }
83
136
  this.pageStarts = starts;
84
137
  }
85
- const starts = this.pageStarts;
86
- if (starts.length === 0 || line < starts[0])
87
- return undefined;
88
- let low = 0;
89
- let high = starts.length - 1;
90
- while (low < high) {
91
- const middle = (low + high + 1) >> 1;
92
- if (starts[middle] <= line)
93
- low = middle;
94
- else
95
- high = middle - 1;
96
- }
97
- return low + 1;
98
- }
99
- /** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
100
- pagesOfLines(from, to) {
101
- const last = this.pageOfLine(to);
102
- if (last === undefined)
103
- return undefined;
104
- const first = this.pageOfLine(from) ?? 1;
105
- return first === last ? String(last) : `${first}-${last}`;
138
+ return this.pageStarts;
106
139
  }
107
140
  }
108
141
  function clip(line, column) {
@@ -126,7 +159,7 @@ function withinTimeLimit(scan, milliseconds) {
126
159
  scanContext ??= createContext(scanSandbox);
127
160
  scanSandbox.scan = scan;
128
161
  try {
129
- RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
162
+ RUN_SCAN.runInContext(scanContext, { timeout: Math.max(1, Math.ceil(milliseconds)) });
130
163
  return true;
131
164
  }
132
165
  catch (error) {
@@ -156,113 +189,338 @@ export function unsafeRegexReason(pattern) {
156
189
  }
157
190
  return null;
158
191
  }
159
- /** Lines that contain `query` (exact text) or match it (regex). */
160
- export function grep(document, query, options) {
161
- const { lines } = document;
162
- if (!query)
163
- throw new Error("The search query is empty.");
164
- const hits = [];
165
- let total = 0;
166
- let stoppedEarly = false;
167
- const record = (line, column) => {
168
- total++;
169
- if (hits.length < options.maxResults)
170
- hits.push({ line, column });
171
- };
172
- if (options.regex) {
173
- const problem = unsafeRegexReason(query);
174
- if (problem)
175
- throw new Error(problem);
176
- const pattern = new RegExp(query, options.caseSensitive ? "" : "i");
177
- const finished = withinTimeLimit(() => {
178
- for (let line = 1; line <= lines.lineCount; line++) {
179
- const match = pattern.exec(lines.line(line));
180
- if (match)
181
- record(line, match.index);
192
+ const newlinesIn = (text) => text.split("\n").length - 1;
193
+ /**
194
+ * The text of the `keep` lines before a piece, with their line breaks, and the number of its
195
+ * first line: what a needle across lines may start in.
196
+ */
197
+ function carried(recent, keep) {
198
+ const lines = recent.slice(-keep);
199
+ if (lines.length === 0)
200
+ return undefined;
201
+ return { text: lines.map(([, text]) => `${text}\n`).join(""), firstLine: lines[0][0] };
202
+ }
203
+ /** The lines read last, for lines shown before a hit and for needles across lines. */
204
+ function remember(recent, chunk, keep) {
205
+ if (keep === 0)
206
+ return recent;
207
+ const count = chunk.lines.lineCount;
208
+ const fresh = [];
209
+ for (let local = Math.max(1, count - keep + 1); local <= count; local++)
210
+ fresh.push([chunk.firstLine + local - 1, chunk.lines.line(local)]);
211
+ return [...recent, ...fresh].slice(-keep);
212
+ }
213
+ /**
214
+ * Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
215
+ * a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
216
+ * what `grep` always did; given it in pieces, it finds the same lines.
217
+ */
218
+ class LineSearch {
219
+ settings;
220
+ lineCount;
221
+ hits = [];
222
+ total = 0;
223
+ stoppedEarly = false;
224
+ /** True once nothing more is to be found or counted: the rest of the text need not be read. */
225
+ done = false;
226
+ context;
227
+ /** Lines shown around the hits, by number: undefined until their piece has been read. */
228
+ shown = new Map();
229
+ unfilled = 0;
230
+ recent = [];
231
+ keep;
232
+ needle = "";
233
+ newlines = 0;
234
+ /** Exact mode: where the next match may start in the whole text, as the scan of one string skips past each match. */
235
+ nextAllowed = 0;
236
+ lastLine = 0;
237
+ pattern;
238
+ timeLeft;
239
+ constructor(query, settings, lineCount) {
240
+ this.settings = settings;
241
+ this.lineCount = lineCount;
242
+ if (!query)
243
+ throw new Error("The search query is empty.");
244
+ if (settings.regex) {
245
+ const problem = unsafeRegexReason(query);
246
+ if (problem)
247
+ throw new Error(problem);
248
+ this.pattern = new RegExp(query, settings.caseSensitive ? "" : "i");
249
+ }
250
+ else {
251
+ this.needle = settings.caseSensitive ? query : foldCase(query);
252
+ this.newlines = newlinesIn(this.needle);
253
+ }
254
+ this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
255
+ this.context = Math.max(0, Math.min(5, settings.contextLines));
256
+ this.keep = this.context + this.newlines;
257
+ }
258
+ add(chunk) {
259
+ if (this.done)
260
+ return;
261
+ if (this.pattern)
262
+ this.scanRegex(chunk);
263
+ else
264
+ this.scanExact(chunk);
265
+ if (this.unfilled > 0) {
266
+ const last = chunk.firstLine + chunk.lines.lineCount - 1;
267
+ for (const [line, text] of this.shown) {
268
+ if (text !== undefined)
269
+ continue;
270
+ const found = line >= chunk.firstLine && line <= last
271
+ ? chunk.lines.line(line - chunk.firstLine + 1)
272
+ : this.recent.find(([number]) => number === line)?.[1];
273
+ if (found !== undefined)
274
+ this.fill(line, found);
182
275
  }
183
- }, options.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
184
- if (!finished)
185
- stoppedEarly = true;
186
- }
187
- else {
188
- const haystack = options.caseSensitive ? document.text : document.lower;
189
- const needle = options.caseSensitive ? query : foldCase(query);
190
- let lastLine = 0;
191
- for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + needle.length)) {
192
- const line = lines.lineAt(at);
193
- if (line === lastLine)
276
+ }
277
+ this.recent = remember(this.recent, chunk, this.keep);
278
+ }
279
+ /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
280
+ missing() {
281
+ if (this.unfilled === 0)
282
+ return [];
283
+ return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
284
+ }
285
+ fill(line, text) {
286
+ if (this.shown.get(line) !== undefined || !this.shown.has(line))
287
+ return;
288
+ this.shown.set(line, text);
289
+ this.unfilled--;
290
+ }
291
+ result() {
292
+ const lineText = (line) => this.shown.get(line) ?? "";
293
+ const matches = this.hits.map(({ line, column, text }) => {
294
+ const match = { line, text: clip(text, column) };
295
+ if (this.context > 0) {
296
+ match.before = [];
297
+ match.after = [];
298
+ for (let other = Math.max(1, line - this.context); other < line; other++)
299
+ match.before.push(`${other}| ${clip(lineText(other), 0)}`);
300
+ for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++)
301
+ match.after.push(`${other}| ${clip(lineText(other), 0)}`);
302
+ }
303
+ return match;
304
+ });
305
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
306
+ }
307
+ record(line, column, text) {
308
+ this.total++;
309
+ if (this.hits.length >= this.settings.maxResults)
310
+ return;
311
+ this.hits.push({ line, column, text });
312
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
313
+ if (other !== line && !this.shown.has(other)) {
314
+ this.shown.set(other, undefined);
315
+ this.unfilled++;
316
+ }
317
+ }
318
+ }
319
+ scanExact(chunk) {
320
+ const { needle } = this;
321
+ const caseSensitive = this.settings.caseSensitive === true;
322
+ let text = caseSensitive ? chunk.text : chunk.lower();
323
+ let lines = chunk.lines;
324
+ let firstLine = chunk.firstLine;
325
+ let start = chunk.startCharacter;
326
+ // A needle across lines can start in the lines before this piece.
327
+ const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
328
+ if (before) {
329
+ text = (caseSensitive ? before.text : foldCase(before.text)) + text;
330
+ lines = new LineIndex(before.text + chunk.text);
331
+ firstLine = before.firstLine;
332
+ start = chunk.startCharacter - before.text.length;
333
+ }
334
+ for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
335
+ this.nextAllowed = start + at + needle.length;
336
+ const local = lines.lineAt(at);
337
+ const line = firstLine + local - 1;
338
+ if (line === this.lastLine)
194
339
  continue;
195
- lastLine = line;
196
- record(line, at - lines.startOf(line));
197
- if (total >= 1_000_000) {
198
- stoppedEarly = true;
199
- break;
340
+ this.lastLine = line;
341
+ this.record(line, at - lines.startOf(local), lines.line(local));
342
+ if (this.total >= MAX_EXACT_MATCHES) {
343
+ this.stoppedEarly = true;
344
+ this.done = true;
345
+ return;
200
346
  }
201
347
  }
202
348
  }
203
- const context = Math.max(0, Math.min(5, options.contextLines));
204
- const matches = hits.map(({ line, column }) => {
205
- const match = { line, text: clip(lines.line(line), column) };
206
- if (context > 0) {
207
- match.before = [];
208
- match.after = [];
209
- for (let other = Math.max(1, line - context); other < line; other++)
210
- match.before.push(`${other}| ${clip(lines.line(other), 0)}`);
211
- for (let other = line + 1; other <= Math.min(lines.lineCount, line + context); other++)
212
- match.after.push(`${other}| ${clip(lines.line(other), 0)}`);
349
+ scanRegex(chunk) {
350
+ if (this.timeLeft <= 0) {
351
+ this.stoppedEarly = true;
352
+ this.done = true;
353
+ return;
354
+ }
355
+ const pattern = this.pattern;
356
+ const { lines, firstLine } = chunk;
357
+ const started = performance.now();
358
+ const finished = withinTimeLimit(() => {
359
+ for (let local = 1; local <= lines.lineCount; local++) {
360
+ const text = lines.line(local);
361
+ const match = pattern.exec(text);
362
+ if (match)
363
+ this.record(firstLine + local - 1, match.index, text);
364
+ }
365
+ }, this.timeLeft);
366
+ this.timeLeft -= performance.now() - started;
367
+ if (!finished) {
368
+ this.stoppedEarly = true;
369
+ this.done = true;
213
370
  }
214
- return match;
215
- });
216
- return { totalMatchingLines: total, stoppedEarly, matches };
371
+ }
372
+ }
373
+ /** Reads the given lines (sorted) from a document, a run of neighbouring lines at a time. */
374
+ async function readSome(source, lines, use) {
375
+ for (let at = 0; at < lines.length;) {
376
+ let end = at;
377
+ while (end + 1 < lines.length && lines[end + 1] <= lines[end] + 1)
378
+ end++;
379
+ const texts = await source.readLines(lines[at], lines[end]);
380
+ texts.forEach((text, index) => use(lines[at] + index, text));
381
+ at = end + 1;
382
+ }
383
+ }
384
+ /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
385
+ export function grep(document, query, options) {
386
+ const search = new LineSearch(query, options, document.lines.lineCount);
387
+ search.add(document.wholeChunk());
388
+ for (const line of search.missing())
389
+ search.fill(line, document.lines.line(line));
390
+ return search.result();
391
+ }
392
+ /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
393
+ export async function grepSource(source, query, options) {
394
+ if (source instanceof SearchableDocument)
395
+ return grep(source, query, options);
396
+ const search = new LineSearch(query, options, source.lineCount);
397
+ await scanSource(source, (chunk) => {
398
+ search.add(chunk);
399
+ return search.done;
400
+ }, options.signal);
401
+ const missing = search.missing();
402
+ if (missing.length)
403
+ await readSome(source, missing, (line, text) => search.fill(line, text));
404
+ return search.result();
217
405
  }
218
406
  export function queryTerms(query) {
219
407
  const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
220
408
  return [...new Set(terms)].slice(0, 12);
221
409
  }
222
410
  /**
223
- * BM25 over fixed passages, computed at query time from substring hits. No index to build or
224
- * store, works for any language, and a term also matches longer words ("timeout" → "timeouts").
411
+ * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
412
+ * piece at a time (pieces start at passage starts). No index to build or store, works for any
413
+ * language, and a term also matches longer words ("timeout" → "timeouts").
225
414
  */
226
- export function rankPassages(document, query, topK) {
227
- const terms = queryTerms(query);
228
- if (terms.length === 0)
229
- return [];
230
- const haystack = document.lower;
231
- const passageCount = document.passages.length;
232
- const averageLength = Math.max(1, document.text.length / passageCount);
233
- const scores = new Map();
234
- for (const term of terms) {
235
- const frequency = new Map();
236
- let seen = 0;
237
- for (let at = haystack.indexOf(term); at !== -1 && seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
238
- seen++;
239
- const passage = document.passageOfLine(document.lines.lineAt(at));
240
- frequency.set(passage, (frequency.get(passage) ?? 0) + 1);
415
+ class PassageRank {
416
+ source;
417
+ terms;
418
+ /** Passage lengths in characters, for the passages that have a hit. */
419
+ lengths = new Map();
420
+ phrase;
421
+ recent = [];
422
+ constructor(query, source) {
423
+ this.source = source;
424
+ this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
425
+ // Passages that contain the whole phrase rank above passages with scattered terms.
426
+ const phrase = foldCase(query.trim());
427
+ if (this.terms.length > 1 && phrase.length <= 200)
428
+ this.phrase = { needle: phrase, newlines: newlinesIn(phrase), passages: new Set(), nextAllowed: 0 };
429
+ }
430
+ get empty() {
431
+ return this.terms.length === 0;
432
+ }
433
+ add(chunk) {
434
+ if (this.empty)
435
+ return;
436
+ const haystack = chunk.lower();
437
+ for (const entry of this.terms) {
438
+ const { term } = entry;
439
+ for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
440
+ entry.seen++;
441
+ const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
442
+ entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
443
+ if (!this.lengths.has(passage))
444
+ this.lengths.set(passage, this.lengthOf(passage, chunk));
445
+ }
241
446
  }
242
- const df = frequency.size;
243
- if (df === 0)
244
- continue;
245
- const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
246
- for (const [passage, tf] of frequency) {
247
- const range = document.passageRange(passage);
248
- const length = document.lines.endOf(range.to) - document.lines.startOf(range.from) + 1;
249
- const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
250
- scores.set(passage, (scores.get(passage) ?? 0) + score);
447
+ const phrase = this.phrase;
448
+ if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
449
+ let text = haystack;
450
+ let lines = chunk.lines;
451
+ let firstLine = chunk.firstLine;
452
+ let start = chunk.startCharacter;
453
+ const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
454
+ if (before) {
455
+ text = foldCase(before.text) + haystack;
456
+ lines = new LineIndex(before.text + chunk.text);
457
+ firstLine = before.firstLine;
458
+ start = chunk.startCharacter - before.text.length;
459
+ }
460
+ for (let at = text.indexOf(phrase.needle, Math.max(0, phrase.nextAllowed - start)); at !== -1 && phrase.passages.size < MAX_PHRASE_PASSAGES; at = text.indexOf(phrase.needle, at + phrase.needle.length)) {
461
+ phrase.nextAllowed = start + at + phrase.needle.length;
462
+ phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
463
+ }
464
+ this.recent = remember(this.recent, chunk, phrase.newlines);
251
465
  }
252
466
  }
253
- // Passages that contain the whole phrase rank above passages with scattered terms.
254
- const phrase = foldCase(query.trim());
255
- if (terms.length > 1 && phrase.length <= 200) {
256
- const withPhrase = new Set();
257
- for (let at = haystack.indexOf(phrase); at !== -1 && withPhrase.size < 10_000; at = haystack.indexOf(phrase, at + phrase.length)) {
258
- withPhrase.add(document.passageOfLine(document.lines.lineAt(at)));
467
+ result(topK) {
468
+ if (this.empty)
469
+ return [];
470
+ const passageCount = this.source.passageStarts.length;
471
+ const averageLength = Math.max(1, this.source.characters / passageCount);
472
+ const scores = new Map();
473
+ for (const { frequency } of this.terms) {
474
+ const df = frequency.size;
475
+ if (df === 0)
476
+ continue;
477
+ const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
478
+ for (const [passage, tf] of frequency) {
479
+ const length = this.lengths.get(passage);
480
+ const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
481
+ scores.set(passage, (scores.get(passage) ?? 0) + score);
482
+ }
259
483
  }
260
- for (const passage of withPhrase)
261
- scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
484
+ if (this.phrase)
485
+ for (const passage of this.phrase.passages)
486
+ scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
487
+ return [...scores.entries()]
488
+ .sort((left, right) => right[1] - left[1])
489
+ .slice(0, topK)
490
+ .map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
491
+ }
492
+ passageOf(line) {
493
+ return positionOf(this.source.passageStarts, line) - 1;
494
+ }
495
+ range(passage) {
496
+ const starts = this.source.passageStarts;
497
+ return { from: starts[passage], to: (passage + 1 < starts.length ? starts[passage + 1] : this.source.lineCount + 1) - 1 };
498
+ }
499
+ lengthOf(passage, chunk) {
500
+ const { from, to } = this.range(passage);
501
+ const first = from - chunk.firstLine + 1;
502
+ const last = to - chunk.firstLine + 1;
503
+ if (first < 1 || last > chunk.lines.lineCount)
504
+ throw new Error("A piece of the text does not hold whole passages.");
505
+ return chunk.lines.endOf(last) - chunk.lines.startOf(first) + 1;
262
506
  }
263
- return [...scores.entries()]
264
- .sort((left, right) => right[1] - left[1])
265
- .slice(0, topK)
266
- .map(([passage, score]) => ({ ...document.passageRange(passage), score: Math.round(score * 100) / 100 }));
507
+ }
508
+ /** BM25 passage ranking over a document held in memory. */
509
+ export function rankPassages(document, query, topK) {
510
+ const rank = new PassageRank(query, document);
511
+ rank.add(document.wholeChunk());
512
+ return rank.result(topK);
513
+ }
514
+ /** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
515
+ export async function rankSource(source, query, topK, signal) {
516
+ if (source instanceof SearchableDocument)
517
+ return rankPassages(source, query, topK);
518
+ const rank = new PassageRank(query, source);
519
+ if (rank.empty)
520
+ return [];
521
+ await scanSource(source, (chunk) => {
522
+ rank.add(chunk);
523
+ }, signal);
524
+ return rank.result(topK);
267
525
  }
268
526
  //# sourceMappingURL=search.js.map