okapibm25 2.0.0 → 2.1.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/README.md +220 -54
- package/dist/BM25.d.ts +67 -0
- package/dist/BM25.js +206 -0
- package/dist/BM25.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,98 +1,264 @@
|
|
|
1
1
|
# okapibm25
|
|
2
2
|
|
|
3
|
-
](https://www.npmjs.com/package/okapibm25)
|
|
4
|
+
[](https://github.com/FurkanToprak/OkapiBM25/actions/workflows/ci.yml)
|
|
5
|
+
[](https://www.npmjs.com/package/okapibm25)
|
|
6
|
+
[](https://www.npmjs.com/package/okapibm25)
|
|
7
|
+
[](https://www.npmjs.com/package/okapibm25?activeTab=dependencies)
|
|
8
|
+
[](LICENSE.md)
|
|
9
|
+
|
|
4
10
|

|
|
5
11
|

|
|
6
12
|

|
|
7
13
|

|
|
8
14
|
|
|
15
|
+
Score and rank documents against search keywords with [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25), the ranking function behind most full-text search engines.
|
|
9
16
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
-
|
|
16
|
-
- https://www.librechat.ai
|
|
17
|
-
- https://illuma.cx
|
|
18
|
-
- https://www.observee.com/
|
|
17
|
+
- One function. Give it your documents and your keywords, get a score per document.
|
|
18
|
+
- An optional index for searching the same documents many times: about half a millisecond per search on 10,000 documents.
|
|
19
|
+
- No dependencies, 5 kB gzipped.
|
|
20
|
+
- Written in TypeScript, types included.
|
|
21
|
+
- Runs on Node 12 and later, and in browsers through a bundler.
|
|
22
|
+
- Safe with text typed by users: keywords are matched as plain text.
|
|
19
23
|
|
|
20
|
-
## Installation
|
|
21
24
|
```sh
|
|
22
|
-
npm install okapibm25
|
|
25
|
+
npm install okapibm25
|
|
23
26
|
```
|
|
24
|
-
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
25
30
|
```ts
|
|
26
31
|
import { BM25 } from "okapibm25";
|
|
27
32
|
|
|
28
33
|
const documents = [
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"Each test document will be searched with the keywords specified below.",
|
|
34
|
+
"The quick brown fox jumps over the lazy dog",
|
|
35
|
+
"A quick guide to training your dog",
|
|
36
|
+
"Stock markets fell sharply on Monday",
|
|
33
37
|
];
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
console.log(result);
|
|
38
|
+
|
|
39
|
+
const scores = BM25(documents, ["quick", "dog"]);
|
|
40
|
+
// [0.860, 0.958, 0]
|
|
38
41
|
```
|
|
42
|
+
|
|
43
|
+
You get one score per document, in the order of `documents`. A higher score means a better match, and a document that contains none of the keywords scores `0`. The second document wins here because both contain the keywords once and it is shorter.
|
|
44
|
+
|
|
39
45
|
Every one of these gives you the same function:
|
|
46
|
+
|
|
40
47
|
```ts
|
|
41
48
|
import { BM25 } from "okapibm25"; // TypeScript, bundlers, Node ES modules
|
|
42
49
|
import BM25 from "okapibm25"; // TypeScript and bundlers
|
|
43
50
|
const { BM25 } = require("okapibm25"); // CommonJS
|
|
44
51
|
```
|
|
45
|
-
### Sorting
|
|
46
|
-
You can sort your documents. [This works very similar to JavaScript's Array.prototype.sort() function.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
|
|
47
52
|
|
|
48
|
-
|
|
53
|
+
## Used by
|
|
54
|
+
- [LlamaIndex](https://www.llamaindex.ai)
|
|
55
|
+
- [LibreChat](https://www.librechat.ai)
|
|
56
|
+
- [Illuma](https://illuma.cx)
|
|
57
|
+
- [Observee](https://www.observee.com/)
|
|
58
|
+
|
|
59
|
+
## Usage
|
|
60
|
+
|
|
61
|
+
### Ranked results
|
|
62
|
+
|
|
63
|
+
Pass a sorter as the fourth argument to get the documents back with their scores, sorted. It works like the function you give to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const ranked = BM25(documents, ["quick", "dog"], undefined, (a, b) => b.score - a.score);
|
|
67
|
+
// [
|
|
68
|
+
// { document: "A quick guide to training your dog", score: 0.958 },
|
|
69
|
+
// { document: "The quick brown fox jumps over the lazy dog", score: 0.860 },
|
|
70
|
+
// { document: "Stock markets fell sharply on Monday", score: 0 },
|
|
71
|
+
// ]
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The sorter receives both the document and its score, so you can sort by score, alphabetically, or by any rule of your own.
|
|
75
|
+
|
|
76
|
+
With a sorter the return type is `{ document: string; score: number }[]`, and without one it is `number[]`. TypeScript knows which one you get, so no cast is needed.
|
|
77
|
+
|
|
78
|
+
### Tuning `k1` and `b`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
BM25(documents, ["quick", "dog"], { k1: 1.5, b: 0.5 });
|
|
82
|
+
// [0.880, 0.953, 0]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `k1` sets how much it counts when a keyword occurs many times in a document. The default is `1.2`. With `k1: 0` a keyword counts the same whether it occurs once or twenty times.
|
|
86
|
+
- `b` sets how much long documents are penalised. The default is `0.75`. With `b: 0` document length is ignored, and with `b: 1` it counts fully.
|
|
87
|
+
|
|
88
|
+
### Searching for what a user typed
|
|
89
|
+
|
|
90
|
+
Matching is exact, so `"Quick"` does not match `"quick"` and `"dog?"` does not match `"dog"`. To search for text from a search box, lowercase both sides and take the words out of the text:
|
|
91
|
+
|
|
49
92
|
```ts
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
)
|
|
93
|
+
const toKeywords = (text: string) => text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
94
|
+
|
|
95
|
+
const lowered = documents.map((document) => document.toLowerCase());
|
|
96
|
+
const scores = BM25(lowered, toKeywords("Quick dog?")); // the keywords are ["quick", "dog"]
|
|
97
|
+
|
|
98
|
+
const best = scores
|
|
99
|
+
.map((score, index) => ({ document: documents[index], score }))
|
|
100
|
+
.filter((hit) => hit.score > 0)
|
|
101
|
+
.sort((a, b) => b.score - a.score)
|
|
102
|
+
.slice(0, 10);
|
|
58
103
|
```
|
|
59
|
-
I've purposely given a schema that lets you sort results by more than just score; you could also sort alphabetically (or by how many times the word 'unicorn' is mentioned, for all I care!) by comparing the documents as well. You can also even ignore scores while sorting!
|
|
60
104
|
|
|
61
|
-
|
|
105
|
+
The scores line up with `documents` by position, which is how the example gets back to the original text. Common words such as "the" and "is" are keywords like any other. If they drown out the words that matter, remove them from the keywords.
|
|
106
|
+
|
|
107
|
+
An index, described next, does the lowercasing and the splitting for you.
|
|
108
|
+
|
|
109
|
+
### Searching the same documents many times
|
|
110
|
+
|
|
111
|
+
`BM25` reads all the text on every call. When the documents stay the same between searches, build an index once and search that instead:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { createIndex } from "okapibm25";
|
|
115
|
+
|
|
116
|
+
const index = createIndex(documents);
|
|
117
|
+
|
|
118
|
+
const hits = index.search(["Quick", "dog?"]);
|
|
119
|
+
// [
|
|
120
|
+
// { index: 1, document: "A quick guide to training your dog", score: 0.958 },
|
|
121
|
+
// { index: 0, document: "The quick brown fox jumps over the lazy dog", score: 0.860 },
|
|
122
|
+
// ]
|
|
123
|
+
|
|
124
|
+
const top = index.search(["quick", "dog"], { limit: 1, k1: 1.5, b: 0.5 });
|
|
125
|
+
const all = index.scores(["quick", "dog"]);
|
|
126
|
+
// [0.860, 0.958, 0]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
- `search` returns the documents that contain at least one keyword, best match first. `index` is the position of the document in the array you gave to `createIndex`.
|
|
130
|
+
- `scores` returns one score per document, like `BM25`.
|
|
131
|
+
- The index is a snapshot of the documents. To add or change documents, build a new one.
|
|
132
|
+
|
|
133
|
+
The index uses the same formula as `BM25`, but it matches differently:
|
|
134
|
+
|
|
135
|
+
| | `BM25` | `createIndex` |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| What a keyword matches | Its exact text, anywhere: `"cat"` matches `"concatenate"` | Whole words: `"cat"` matches only the word `cat` |
|
|
138
|
+
| Case | `"Dog"` and `"dog"` differ | Ignored, unless you pass `{ caseSensitive: true }` |
|
|
139
|
+
| Punctuation in a keyword | Part of the text to find: `"c++"` finds `c++` | A gap between words: `"dog?"` finds `dog`, and `"c++"` finds the word `c` |
|
|
140
|
+
| A keyword of several words | Found as a phrase: `"quick guide"` | Each word counts on its own |
|
|
141
|
+
| What a word is | For document length only: a run of `a-z`, `A-Z`, `0-9` and `_` | A run of letters, digits and `_` in any script: `café` and `москва` are words |
|
|
142
|
+
| `k1` and `b` out of range | Used as given | Rejected with an error |
|
|
143
|
+
|
|
144
|
+
The formula is the same. With `{ caseSensitive: true }`, on English text, `index.scores` returns exactly the numbers `BM25` returns for keywords that are single words and occur only as whole words.
|
|
145
|
+
|
|
146
|
+
Languages that are written without spaces, such as Japanese and Chinese, need your own function to split a text into words. It is used for the documents and for the keywords:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
const segmenter = new Intl.Segmenter("ja", { granularity: "word" });
|
|
150
|
+
|
|
151
|
+
const japaneseIndex = createIndex(["犬は速い", "猫は眠る"], {
|
|
152
|
+
tokenizer: (text) =>
|
|
153
|
+
Array.from(segmenter.segment(text))
|
|
154
|
+
.filter((part) => part.isWordLike)
|
|
155
|
+
.map((part) => part.segment),
|
|
156
|
+
});
|
|
157
|
+
japaneseIndex.search(["犬"]); // finds the first document
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The same option is the place to remove common words or to cut endings off words.
|
|
161
|
+
|
|
162
|
+
## How matching works
|
|
163
|
+
|
|
164
|
+
This is how `BM25` matches. An index made with `createIndex` matches whole words instead; see the table above.
|
|
62
165
|
|
|
63
|
-
### How matching works
|
|
64
166
|
- A keyword matches wherever its exact text appears in a document, including inside a longer word: `"cat"` matches `"concatenate"`.
|
|
65
167
|
- Matching is case-sensitive. To ignore case, lowercase your documents and your keywords before calling `BM25`.
|
|
66
|
-
- Keywords are plain text, never regular expressions. `"c++"`, `"(draft)"` and anything else a user types into a search box are safe to pass in as they are.
|
|
168
|
+
- Keywords are plain text, never regular expressions. `"c++"`, `"(draft)"` and anything else a user types into a search box are safe to pass in as they are.
|
|
67
169
|
- Document length is the number of words, where a word is a run of the characters `a-z`, `A-Z`, `0-9` and `_`.
|
|
68
|
-
- `k1` and `b` default to `1.2` and `0.75`. Both accept `0
|
|
170
|
+
- `k1` and `b` default to `1.2` and `0.75`. Both accept `0`.
|
|
69
171
|
|
|
70
|
-
|
|
71
|
-
Each call reads every document once per keyword, plus once to measure it. On the benchmark in this repository it runs about twice as fast as version 1.4.1. Run it yourself with `npm run bench`.
|
|
172
|
+
## API
|
|
72
173
|
|
|
73
|
-
|
|
74
|
-
Under `license.md`
|
|
174
|
+
### `BM25(documents, keywords, constants?, sorter?)`
|
|
75
175
|
|
|
76
|
-
|
|
77
|
-
|
|
176
|
+
| Argument | Type | Meaning |
|
|
177
|
+
|---|---|---|
|
|
178
|
+
| `documents` | `readonly string[]` | The texts to score. A document that is not a string scores `0`. |
|
|
179
|
+
| `keywords` | `readonly string[]` | The words or phrases to look for. Each one adds to the score. |
|
|
180
|
+
| `constants` | `{ k1?: number; b?: number }` | Optional. Defaults: `k1` is `1.2`, `b` is `0.75`. |
|
|
181
|
+
| `sorter` | `(a: BMDocument, b: BMDocument) => number` | Optional. When given, the result is sorted with it. |
|
|
78
182
|
|
|
79
|
-
|
|
183
|
+
Returns `number[]` without a sorter and `BMDocument[]`, which is `{ document: string; score: number }[]`, with one. Throws a `TypeError` when `documents` or `keywords` is not an array.
|
|
80
184
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
185
|
+
### `createIndex(documents, options?)`
|
|
186
|
+
|
|
187
|
+
Returns an index of the documents with two methods.
|
|
188
|
+
|
|
189
|
+
| Option | Type | Meaning |
|
|
190
|
+
|---|---|---|
|
|
191
|
+
| `caseSensitive` | `boolean` | Optional. `false` by default: case is ignored. |
|
|
192
|
+
| `tokenizer` | `(text: string) => string[]` | Optional. Splits a text into words. It receives lowercased text unless `caseSensitive` is set. Empty words are dropped. |
|
|
193
|
+
|
|
194
|
+
| Method | Returns |
|
|
195
|
+
|---|---|
|
|
196
|
+
| `index.search(keywords, options?)` | `BMHit[]`, which is `{ index: number; document: string; score: number }[]`: the documents that contain a keyword, best match first. Equal scores keep the order of the documents. |
|
|
197
|
+
| `index.scores(keywords, constants?)` | `number[]`: one score per document, in the order of the documents. |
|
|
198
|
+
|
|
199
|
+
The options of `search` are `k1`, `b` and `limit`, the largest number of results to return. `scores` takes `k1` and `b`.
|
|
200
|
+
|
|
201
|
+
An index is stricter than `BM25` about what it is given:
|
|
202
|
+
|
|
203
|
+
- `k1` must be a finite number of 0 or more, `b` a number from 0 to 1, and `limit` a number of 0 or more. A value of another type throws a `TypeError`, and a number out of range a `RangeError`. Leave an option out to get its default.
|
|
204
|
+
- `documents` and `keywords` must be arrays, and a tokenizer must return an array of strings. Anything else throws a `TypeError`.
|
|
205
|
+
|
|
206
|
+
### Helpers
|
|
207
|
+
|
|
208
|
+
The parts of the calculation are exported too:
|
|
86
209
|
|
|
87
|
-
|
|
88
|
-
|
|
210
|
+
```ts
|
|
211
|
+
import { getWordCount, getTermFrequency, getIDF } from "okapibm25";
|
|
212
|
+
|
|
213
|
+
getWordCount("The quick brown fox"); // 4, the number of words
|
|
214
|
+
getTermFrequency("an", "banana bandana"); // 4, how often the text occurs
|
|
215
|
+
getIDF("dog", documents); // 0.470, higher when fewer documents contain the keyword
|
|
89
216
|
```
|
|
90
217
|
|
|
91
|
-
|
|
218
|
+
### Types
|
|
219
|
+
|
|
220
|
+
`BMDocument`, `BMConstants`, `BMSorter`, `BMIndex`, `BMIndexOptions`, `BMSearchOptions` and `BMHit` are exported for your own signatures.
|
|
221
|
+
|
|
222
|
+
## Upgrading from 1.x
|
|
223
|
+
|
|
224
|
+
Version 2 matches keywords as plain text. Version 1 treated them as regular expressions, so a keyword such as `dog?` or `c\+\+` gives different scores now. For ordinary keywords the scores are identical to 1.4.1. The cases to check are listed under [Upgrading from 1.x](CHANGELOG.md#upgrading-from-1x) in the changelog.
|
|
225
|
+
|
|
226
|
+
## Speed and limits
|
|
227
|
+
|
|
228
|
+
`BM25` builds no index. Each call reads every document once per keyword, plus once to count its words, so the time grows with the amount of text times the number of keywords. It is about twice as fast as version 1.4.1.
|
|
229
|
+
|
|
230
|
+
`createIndex` reads the documents once. After that a search looks its keywords up and never reads the text again.
|
|
231
|
+
|
|
232
|
+
Measured on an Apple M3 laptop with 10,000 documents of about 200 words each and five keywords:
|
|
233
|
+
|
|
234
|
+
| | Time |
|
|
235
|
+
|---|---|
|
|
236
|
+
| One `BM25` call | 60 ms |
|
|
237
|
+
| `createIndex`, once | 210 ms |
|
|
238
|
+
| `index.search`, best 10 results | 0.5 ms |
|
|
92
239
|
|
|
93
|
-
|
|
240
|
+
So `BM25` is the better fit when the documents are different on every call, or when you search them only a few times. The index pays for itself from the fourth search of the same documents. A search takes longer when its keywords are in many documents, because every matching document is ranked. Run `npm run bench` in a clone of the repository to measure it yourself.
|
|
241
|
+
|
|
242
|
+
Everything is kept in memory and nothing is saved to disk. For collections of hundreds of megabytes, use a search engine built for that.
|
|
243
|
+
|
|
244
|
+
## Compatibility
|
|
245
|
+
|
|
246
|
+
- **Node:** 12 and later. The build is ES2015 and CommonJS, and it is loaded on Node 12, 14, 16, 18 and 20 and fully tested on Node 22 and 24 for every change.
|
|
247
|
+
- **TypeScript:** 4.0 and later, with CommonJS, `nodenext` and `bundler` module settings.
|
|
248
|
+
- **Bundlers:** esbuild, webpack and vite are tested for every change.
|
|
249
|
+
- **Stable scores:** the tests compare every change against the published 1.4.1 build, so scores do not move by accident. The changes made on purpose are listed in [CHANGELOG.md](CHANGELOG.md).
|
|
250
|
+
|
|
251
|
+
## Security
|
|
252
|
+
|
|
253
|
+
Keywords are never run as regular expressions, so text from users cannot throw or freeze the process. Releases are published from GitHub Actions with a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements), which links the package on npm to the commit it was built from. To report a security problem, see [SECURITY.md](SECURITY.md).
|
|
254
|
+
|
|
255
|
+
## Contributing
|
|
256
|
+
|
|
257
|
+
Pull requests are welcome. If this isn't your area, open an issue and I'll get to it. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to run the checks and how a release is made.
|
|
258
|
+
|
|
259
|
+
## License
|
|
94
260
|
|
|
95
|
-
|
|
261
|
+
MIT. See [LICENSE.md](LICENSE.md).
|
|
96
262
|
|
|
97
263
|
## Sponsorship
|
|
98
264
|
Consider donating $5 to https://www.unicef.org/ if this has been useful to you.
|
package/dist/BM25.d.ts
CHANGED
|
@@ -48,4 +48,71 @@ export type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;
|
|
|
48
48
|
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants): number[];
|
|
49
49
|
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants: BMConstants | undefined, sorter: BMSorter): BMDocument[];
|
|
50
50
|
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants, sorter?: BMSorter): number[] | BMDocument[];
|
|
51
|
+
/** Options for {@link createIndex}. */
|
|
52
|
+
export interface BMIndexOptions {
|
|
53
|
+
/**
|
|
54
|
+
* Whether `Dog` and `dog` are different words. `false` by default: documents
|
|
55
|
+
* and keywords are lowercased before they are split into words.
|
|
56
|
+
*/
|
|
57
|
+
caseSensitive?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Splits a text into words. It is called for every document and for every
|
|
60
|
+
* keyword, after lowercasing unless `caseSensitive` is set. Empty words are
|
|
61
|
+
* dropped. By default a word is a run of letters, digits and underscores in
|
|
62
|
+
* any script. Pass a tokenizer for languages that are written without
|
|
63
|
+
* spaces, or to remove common words or endings.
|
|
64
|
+
*/
|
|
65
|
+
tokenizer?: (text: string) => string[];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Options for {@link BMIndex.search}. Unlike `BM25`, an index rejects values
|
|
69
|
+
* that cannot give a meaningful score: `k1` must be a finite number of 0 or
|
|
70
|
+
* more and `b` a number from 0 to 1.
|
|
71
|
+
*/
|
|
72
|
+
export interface BMSearchOptions extends BMConstants {
|
|
73
|
+
/** Return at most this many results. All matching documents by default. */
|
|
74
|
+
limit?: number;
|
|
75
|
+
}
|
|
76
|
+
/** A document found by {@link BMIndex.search}. */
|
|
77
|
+
export interface BMHit extends BMDocument {
|
|
78
|
+
/** Position of the document in the array given to {@link createIndex}. */
|
|
79
|
+
index: number;
|
|
80
|
+
}
|
|
81
|
+
/** A searchable index of a fixed set of documents, made by {@link createIndex}. */
|
|
82
|
+
export interface BMIndex {
|
|
83
|
+
/**
|
|
84
|
+
* The documents that contain at least one of the keywords, best match first.
|
|
85
|
+
* Documents with equal scores keep the order they were indexed in.
|
|
86
|
+
*/
|
|
87
|
+
search(keywords: readonly string[], options?: BMSearchOptions): BMHit[];
|
|
88
|
+
/**
|
|
89
|
+
* One score per document, in the order the documents were indexed in. A
|
|
90
|
+
* document that contains none of the keywords scores `0`.
|
|
91
|
+
*/
|
|
92
|
+
scores(keywords: readonly string[], constants?: BMConstants): number[];
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Reads the documents once and builds an index of their words, so that each
|
|
96
|
+
* later search looks words up instead of reading the text again. Worth it when
|
|
97
|
+
* the same documents are searched many times.
|
|
98
|
+
*
|
|
99
|
+
* Matching differs from {@link BM25}: the index matches whole words. `cat`
|
|
100
|
+
* finds the word `cat` and not `concatenate`, and case is ignored unless
|
|
101
|
+
* `caseSensitive` is set. Keywords are split into words the same way as the
|
|
102
|
+
* documents, so the keyword `dog?` finds the word `dog`. The scoring formula
|
|
103
|
+
* and the defaults of `k1` and `b` are those of {@link BM25}.
|
|
104
|
+
*
|
|
105
|
+
* The index is a snapshot. Changing the array afterwards does not change it.
|
|
106
|
+
*
|
|
107
|
+
* @throws TypeError when `documents` is not an array, when `tokenizer` is not
|
|
108
|
+
* a function, or when it returns something other than an array of strings.
|
|
109
|
+
* `search` and `scores` throw a TypeError when `keywords` is not an array or
|
|
110
|
+
* an option is not a number, and a RangeError when an option is out of range.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* const index = createIndex(["A quick dog", "A lazy cat", "Stock markets"]);
|
|
114
|
+
* index.search(["Dog?"]); // [{ index: 0, document: "A quick dog", score: 0.93... }]
|
|
115
|
+
* index.scores(["dog"]); // [0.93..., 0, 0]
|
|
116
|
+
*/
|
|
117
|
+
export declare function createIndex(documents: readonly string[], options?: BMIndexOptions): BMIndex;
|
|
51
118
|
export default BM25;
|
package/dist/BM25.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getIDF = exports.getTermFrequency = exports.getWordCount = void 0;
|
|
4
4
|
exports.BM25 = BM25;
|
|
5
|
+
exports.createIndex = createIndex;
|
|
5
6
|
/** Default value of the free parameter `b`. */
|
|
6
7
|
const DEFAULT_B = 0.75;
|
|
7
8
|
/** Default value of the free parameter `k1`. */
|
|
@@ -142,5 +143,210 @@ function BM25(documents, keywords, constants, sorter) {
|
|
|
142
143
|
}
|
|
143
144
|
return scores;
|
|
144
145
|
}
|
|
146
|
+
/** `undefined` when the JavaScript engine does not support the pattern. */
|
|
147
|
+
const compilePattern = (source, flags) => {
|
|
148
|
+
try {
|
|
149
|
+
return new RegExp(source, flags);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* The default definition of a word for an index: a run of letters, marks that
|
|
157
|
+
* combine with letters, digits and underscores, in any script. For ASCII text
|
|
158
|
+
* these are the words that `getWordCount` counts. The pattern is compiled at
|
|
159
|
+
* run time because its syntax is newer than the ES2015 this file is built
|
|
160
|
+
* for; engines from before 2018 fall back to ASCII words.
|
|
161
|
+
*/
|
|
162
|
+
const WORDS = compilePattern("[\\p{L}\\p{M}\\p{N}_]+", "gu") || /\w+/g;
|
|
163
|
+
/** Reads an option that has to be a number from 0 to `max`. `undefined` gives the default. */
|
|
164
|
+
const readNumber = (value, fallback, max, rule) => {
|
|
165
|
+
if (value === undefined) {
|
|
166
|
+
return fallback;
|
|
167
|
+
}
|
|
168
|
+
if (typeof value !== "number") {
|
|
169
|
+
throw new TypeError("BM25 index: " + rule);
|
|
170
|
+
}
|
|
171
|
+
// Written so that NaN fails it too.
|
|
172
|
+
if (!(value >= 0 && value <= max)) {
|
|
173
|
+
throw new RangeError("BM25 index: " + rule);
|
|
174
|
+
}
|
|
175
|
+
return value;
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* Reads the documents once and builds an index of their words, so that each
|
|
179
|
+
* later search looks words up instead of reading the text again. Worth it when
|
|
180
|
+
* the same documents are searched many times.
|
|
181
|
+
*
|
|
182
|
+
* Matching differs from {@link BM25}: the index matches whole words. `cat`
|
|
183
|
+
* finds the word `cat` and not `concatenate`, and case is ignored unless
|
|
184
|
+
* `caseSensitive` is set. Keywords are split into words the same way as the
|
|
185
|
+
* documents, so the keyword `dog?` finds the word `dog`. The scoring formula
|
|
186
|
+
* and the defaults of `k1` and `b` are those of {@link BM25}.
|
|
187
|
+
*
|
|
188
|
+
* The index is a snapshot. Changing the array afterwards does not change it.
|
|
189
|
+
*
|
|
190
|
+
* @throws TypeError when `documents` is not an array, when `tokenizer` is not
|
|
191
|
+
* a function, or when it returns something other than an array of strings.
|
|
192
|
+
* `search` and `scores` throw a TypeError when `keywords` is not an array or
|
|
193
|
+
* an option is not a number, and a RangeError when an option is out of range.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* const index = createIndex(["A quick dog", "A lazy cat", "Stock markets"]);
|
|
197
|
+
* index.search(["Dog?"]); // [{ index: 0, document: "A quick dog", score: 0.93... }]
|
|
198
|
+
* index.scores(["dog"]); // [0.93..., 0, 0]
|
|
199
|
+
*/
|
|
200
|
+
function createIndex(documents, options) {
|
|
201
|
+
if (!Array.isArray(documents)) {
|
|
202
|
+
throw new TypeError("createIndex: `documents` must be an array of strings.");
|
|
203
|
+
}
|
|
204
|
+
const caseSensitive = options ? options.caseSensitive === true : false;
|
|
205
|
+
const tokenizer = options ? options.tokenizer : undefined;
|
|
206
|
+
if (tokenizer !== undefined && typeof tokenizer !== "function") {
|
|
207
|
+
throw new TypeError("createIndex: `tokenizer` must be a function.");
|
|
208
|
+
}
|
|
209
|
+
/** The words of a text. A custom tokenizer may return empty words; callers skip those. */
|
|
210
|
+
const toWords = (text) => {
|
|
211
|
+
const prepared = caseSensitive ? text : text.toLowerCase();
|
|
212
|
+
if (tokenizer === undefined) {
|
|
213
|
+
return prepared.match(WORDS) || [];
|
|
214
|
+
}
|
|
215
|
+
const words = tokenizer(prepared);
|
|
216
|
+
if (!Array.isArray(words)) {
|
|
217
|
+
throw new TypeError("createIndex: `tokenizer` must return an array of strings.");
|
|
218
|
+
}
|
|
219
|
+
for (let w = 0; w < words.length; w++) {
|
|
220
|
+
if (typeof words[w] !== "string") {
|
|
221
|
+
throw new TypeError("createIndex: `tokenizer` must return an array of strings.");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return words;
|
|
225
|
+
};
|
|
226
|
+
const documentCount = documents.length;
|
|
227
|
+
const originals = documents.slice();
|
|
228
|
+
// A Map, not an object, so that words such as `constructor` are ordinary keys.
|
|
229
|
+
const postings = new Map();
|
|
230
|
+
const documentLengths = new Float64Array(documentCount);
|
|
231
|
+
let totalLength = 0;
|
|
232
|
+
for (let i = 0; i < documentCount; i++) {
|
|
233
|
+
const words = toWords(toText(documents[i]));
|
|
234
|
+
let length = 0;
|
|
235
|
+
for (let w = 0; w < words.length; w++) {
|
|
236
|
+
const word = words[w];
|
|
237
|
+
if (word.length === 0) {
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
length++;
|
|
241
|
+
const posting = postings.get(word);
|
|
242
|
+
if (posting === undefined) {
|
|
243
|
+
postings.set(word, { documents: [i], frequencies: [1] });
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
// Documents are added in order, so a repeat of the word within this
|
|
247
|
+
// document is always at the end of the list.
|
|
248
|
+
const last = posting.documents.length - 1;
|
|
249
|
+
if (posting.documents[last] === i) {
|
|
250
|
+
posting.frequencies[last]++;
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
posting.documents.push(i);
|
|
254
|
+
posting.frequencies.push(1);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
documentLengths[i] = length;
|
|
258
|
+
totalLength += length;
|
|
259
|
+
}
|
|
260
|
+
// Only read once a word has been found, and then at least one document has
|
|
261
|
+
// a word, so it is a positive number wherever it is used.
|
|
262
|
+
const averageDocumentLength = totalLength / documentCount;
|
|
263
|
+
// Working memory shared by all searches, so that a search costs time in
|
|
264
|
+
// proportion to the documents it finds and not to the size of the index.
|
|
265
|
+
// Both are all zeros between searches: `clear` undoes what `collect` wrote.
|
|
266
|
+
const totals = new Float64Array(documentCount);
|
|
267
|
+
const isMatched = new Uint8Array(documentCount);
|
|
268
|
+
/**
|
|
269
|
+
* Adds the score of every document that contains a keyword into `totals`
|
|
270
|
+
* and returns the positions of those documents, in the order they were
|
|
271
|
+
* first found. The caller reads `totals` and then calls `clear`.
|
|
272
|
+
*/
|
|
273
|
+
const collect = (keywords, constants) => {
|
|
274
|
+
if (!Array.isArray(keywords)) {
|
|
275
|
+
throw new TypeError("BM25 index: `keywords` must be an array of strings.");
|
|
276
|
+
}
|
|
277
|
+
const b = readNumber(constants ? constants.b : undefined, DEFAULT_B, 1, "`b` must be a number from 0 to 1.");
|
|
278
|
+
const k1 = readNumber(constants ? constants.k1 : undefined, DEFAULT_K1, Number.MAX_VALUE, "`k1` must be a finite number, 0 or more.");
|
|
279
|
+
// Every keyword is split into words before any score is added. The
|
|
280
|
+
// tokenizer is the caller's code, and none of it runs, and nothing can
|
|
281
|
+
// throw, while `totals` holds a search in progress.
|
|
282
|
+
const words = [];
|
|
283
|
+
for (let k = 0; k < keywords.length; k++) {
|
|
284
|
+
// As in BM25, a number is searched as text and other values match nothing.
|
|
285
|
+
const rawKeyword = keywords[k];
|
|
286
|
+
const keywordWords = toWords(typeof rawKeyword === "number" ? String(rawKeyword) : toText(rawKeyword));
|
|
287
|
+
for (let w = 0; w < keywordWords.length; w++) {
|
|
288
|
+
words.push(keywordWords[w]);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const matched = [];
|
|
292
|
+
for (let w = 0; w < words.length; w++) {
|
|
293
|
+
const posting = postings.get(words[w]);
|
|
294
|
+
if (posting === undefined) {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const matches = posting.documents.length;
|
|
298
|
+
// The arithmetic below is the same, operation for operation, as in
|
|
299
|
+
// BM25, so both give identical scores when they match the same words.
|
|
300
|
+
const inverseDocumentFrequency = Math.log((documentCount - matches + 0.5) / (matches + 0.5) + 1);
|
|
301
|
+
for (let m = 0; m < matches; m++) {
|
|
302
|
+
const i = posting.documents[m];
|
|
303
|
+
const termFrequency = posting.frequencies[m];
|
|
304
|
+
const relativeLength = (b * documentLengths[i]) / averageDocumentLength;
|
|
305
|
+
const lengthNorm = k1 * (1 - b + relativeLength);
|
|
306
|
+
totals[i] +=
|
|
307
|
+
(inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
|
|
308
|
+
(termFrequency + lengthNorm);
|
|
309
|
+
if (isMatched[i] === 0) {
|
|
310
|
+
isMatched[i] = 1;
|
|
311
|
+
matched.push(i);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return matched;
|
|
316
|
+
};
|
|
317
|
+
const clear = (matched) => {
|
|
318
|
+
for (let m = 0; m < matched.length; m++) {
|
|
319
|
+
totals[matched[m]] = 0;
|
|
320
|
+
isMatched[matched[m]] = 0;
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
search(keywords, options) {
|
|
325
|
+
const limit = readNumber(options ? options.limit : undefined, Infinity, Infinity, "`limit` must be a number, 0 or more.");
|
|
326
|
+
const matched = collect(keywords, options);
|
|
327
|
+
// The position breaks ties, so the order never depends on the engine's sort.
|
|
328
|
+
matched.sort((first, second) => totals[second] - totals[first] || first - second);
|
|
329
|
+
const hits = new Array(Math.floor(Math.min(matched.length, limit)));
|
|
330
|
+
for (let m = 0; m < hits.length; m++) {
|
|
331
|
+
const i = matched[m];
|
|
332
|
+
hits[m] = { index: i, document: originals[i], score: totals[i] };
|
|
333
|
+
}
|
|
334
|
+
clear(matched);
|
|
335
|
+
return hits;
|
|
336
|
+
},
|
|
337
|
+
scores(keywords, constants) {
|
|
338
|
+
const matched = collect(keywords, constants);
|
|
339
|
+
const scores = new Array(documentCount);
|
|
340
|
+
for (let i = 0; i < documentCount; i++) {
|
|
341
|
+
scores[i] = 0;
|
|
342
|
+
}
|
|
343
|
+
for (let m = 0; m < matched.length; m++) {
|
|
344
|
+
scores[matched[m]] = totals[matched[m]];
|
|
345
|
+
}
|
|
346
|
+
clear(matched);
|
|
347
|
+
return scores;
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
}
|
|
145
351
|
exports.default = BM25;
|
|
146
352
|
//# sourceMappingURL=BM25.js.map
|
package/dist/BM25.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BM25.js","sourceRoot":"","sources":["../BM25.ts"],"names":[],"mappings":";;;;AAAA,+CAA+C;AAC/C,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,gDAAgD;AAChD,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,oEAAoE;AACpE,MAAM,MAAM,GAAG,CAAC,KAAc,EAAU,EAAE,CACxC,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IAAI,MAAM,EAAE,CAAC;QACX,MAAM,eAAe,GAAiB,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAC/D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,EAAE,CAAC,EAAE,EAAE,CAAC;YACvC,eAAe,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;QACpE,CAAC;QACD,OAAO,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;kBAEc,IAAI","sourcesContent":["/** Default value of the free parameter `b`. */\nconst DEFAULT_B = 0.75;\n/** Default value of the free parameter `k1`. */\nconst DEFAULT_K1 = 1.2;\n\n/** Anything that is not a string is scored as an empty document. */\nconst toText = (value: unknown): string =>\n typeof value === \"string\" ? value : \"\";\n\n/** A free parameter is used when it is a real number, `0` included. Anything else falls back to the default. */\nconst resolveConstant = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && !Number.isNaN(value) ? value : fallback;\n\n/** 1 for the ASCII characters that `\\w` matches (letters, digits, underscore), 0 for the rest. */\nconst WORD_CHARACTERS = new Uint8Array(128);\nfor (let code = 0; code < 128; code++) {\n const isWordCharacter =\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n (code >= 48 && code <= 57) || // 0-9\n code === 95; // _\n WORD_CHARACTERS[code] = isWordCharacter ? 1 : 0;\n}\n\n/**\n * Gets word count. A word is a run of ASCII letters, digits and underscores,\n * the same as the regular expression `\\w+`.\n */\nexport const getWordCount = (corpus: string): number => {\n const text = toText(corpus);\n let count = 0;\n let insideWord = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n const isWordCharacter = code < 128 ? WORD_CHARACTERS[code] : 0;\n // A word starts where a word character follows a character that is not one.\n count += isWordCharacter & ~insideWord;\n insideWord = isWordCharacter;\n }\n return count;\n};\n\n/** Counts occurrences of `needle` in `text` that do not overlap. An empty needle occurs zero times. */\nconst countOccurrences = (needle: string, text: string): number => {\n if (needle.length === 0) {\n return 0;\n }\n let count = 0;\n let position = text.indexOf(needle);\n while (position !== -1) {\n count++;\n position = text.indexOf(needle, position + needle.length);\n }\n return count;\n};\n\n/**\n * Number of occurrences of a term in a string.\n *\n * The term is matched literally and case-sensitively, and occurrences do not\n * overlap. It is never interpreted as a regular expression, so terms such as\n * `c++` or `(a+)+$` are safe to pass straight from user input. An empty term\n * occurs zero times.\n */\nexport const getTermFrequency = (term: string, corpus: string): number =>\n countOccurrences(toText(term), toText(corpus));\n\n/** Inverse document frequency. */\nexport const getIDF = (term: string, documents: readonly string[]): number => {\n let relevantDocuments = 0;\n for (let i = 0; i < documents.length; i++) {\n if (toText(documents[i]).includes(term)) {\n relevantDocuments++;\n }\n }\n return Math.log(\n (documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1\n );\n};\n\n/** Represents a document; useful when sorting results.\n */\nexport interface BMDocument {\n /** The document that was scored. */\n document: string;\n /** The score that the document receives. */\n score: number;\n}\n\n/** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */\nexport interface BMConstants {\n /** Free parameter. Is 0.75 by default. `0` turns length normalization off, `1` applies it fully. */\n b?: number;\n /** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0]. `0` ignores how often a term occurs. */\n k1?: number;\n}\n\n/** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */\nexport type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;\n\n/** Implementation of Okapi BM25 algorithm.\n *\n * Keywords are matched literally and case-sensitively anywhere in a document.\n *\n * @param documents: Collection of documents.\n * @param keywords: query terms.\n * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.\n * @param sorter: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.\n * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.\n *\n * @example\n * const scores = BM25([\"a cat\", \"a dog\"], [\"cat\"]); // number[]\n * const ranked = BM25([\"a cat\", \"a dog\"], [\"cat\"], undefined, (x, y) => y.score - x.score); // BMDocument[]\n */\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants\n): number[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants: BMConstants | undefined,\n sorter: BMSorter\n): BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[] {\n if (!Array.isArray(documents)) {\n throw new TypeError(\"BM25: `documents` must be an array of strings.\");\n }\n if (!Array.isArray(keywords)) {\n throw new TypeError(\"BM25: `keywords` must be an array of strings.\");\n }\n const b = resolveConstant(constants ? constants.b : undefined, DEFAULT_B);\n const k1 = resolveConstant(constants ? constants.k1 : undefined, DEFAULT_K1);\n const documentCount = documents.length;\n\n // Each document is measured once.\n const texts: string[] = new Array(documentCount);\n const documentLengths = new Float64Array(documentCount);\n let totalLength = 0;\n for (let i = 0; i < documentCount; i++) {\n const text = toText(documents[i]);\n const length = getWordCount(text);\n texts[i] = text;\n documentLengths[i] = length;\n totalLength += length;\n }\n const averageDocumentLength =\n documentCount > 0 ? totalLength / documentCount : 0;\n\n // The part of the denominator that depends only on the document. A\n // collection with no countable words has no length to normalize by, so every\n // document is treated as being of average length.\n const lengthNorms = new Float64Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n const relativeLength =\n averageDocumentLength > 0\n ? (b * documentLengths[i]) / averageDocumentLength\n : b;\n lengthNorms[i] = k1 * (1 - b + relativeLength);\n }\n\n const scores: number[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scores[i] = 0;\n }\n\n // Each keyword reads every document once. That single pass gives both the\n // term frequencies and the number of documents containing the keyword.\n const matchedDocuments = new Uint32Array(documentCount);\n const matchedFrequencies = new Uint32Array(documentCount);\n for (let k = 0; k < keywords.length; k++) {\n // JavaScript callers may pass a number, such as a year. It is searched as text.\n const rawKeyword: unknown = keywords[k];\n const keyword =\n typeof rawKeyword === \"number\" ? String(rawKeyword) : toText(rawKeyword);\n let matches = 0;\n for (let i = 0; i < documentCount; i++) {\n const termFrequency = countOccurrences(keyword, texts[i]);\n if (termFrequency > 0) {\n matchedDocuments[matches] = i;\n matchedFrequencies[matches] = termFrequency;\n matches++;\n }\n }\n const inverseDocumentFrequency = Math.log(\n (documentCount - matches + 0.5) / (matches + 0.5) + 1\n );\n for (let m = 0; m < matches; m++) {\n const i = matchedDocuments[m];\n const termFrequency = matchedFrequencies[m];\n scores[i] +=\n (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /\n (termFrequency + lengthNorms[i]);\n }\n }\n\n if (sorter) {\n const scoredDocuments: BMDocument[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scoredDocuments[i] = { score: scores[i], document: documents[i] };\n }\n return scoredDocuments.sort(sorter);\n }\n return scores;\n}\n\nexport default BM25;\n"]}
|
|
1
|
+
{"version":3,"file":"BM25.js","sourceRoot":"","sources":["../BM25.ts"],"names":[],"mappings":";;;;;AAAA,+CAA+C;AAC/C,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,gDAAgD;AAChD,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,oEAAoE;AACpE,MAAM,MAAM,GAAG,CAAC,KAAc,EAAU,EAAE,CACxC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAEzC,gHAAgH;AAChH,MAAM,eAAe,GAAG,CAAC,KAAc,EAAE,QAAgB,EAAU,EAAE,CACnE,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,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CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAC5C,CAAC;YACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACrC,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBACrB,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;YACnE,CAAC;YACD,KAAK,CAAC,OAAO,CAAC,CAAC;YACf,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,CAAC,QAAQ,EAAE,SAAS;YACxB,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;YAC7C,MAAM,MAAM,GAAa,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;YAClD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,EAAE,CAAC,EAAE,EAAE,CAAC;gBACvC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAChB,CAAC;YACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACxC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1C,CAAC;YACD,KAAK,CAAC,OAAO,CAAC,CAAC;YACf,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC;kBAEc,IAAI","sourcesContent":["/** Default value of the free parameter `b`. */\nconst DEFAULT_B = 0.75;\n/** Default value of the free parameter `k1`. */\nconst DEFAULT_K1 = 1.2;\n\n/** Anything that is not a string is scored as an empty document. */\nconst toText = (value: unknown): string =>\n typeof value === \"string\" ? value : \"\";\n\n/** A free parameter is used when it is a real number, `0` included. Anything else falls back to the default. */\nconst resolveConstant = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && !Number.isNaN(value) ? value : fallback;\n\n/** 1 for the ASCII characters that `\\w` matches (letters, digits, underscore), 0 for the rest. */\nconst WORD_CHARACTERS = new Uint8Array(128);\nfor (let code = 0; code < 128; code++) {\n const isWordCharacter =\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n (code >= 48 && code <= 57) || // 0-9\n code === 95; // _\n WORD_CHARACTERS[code] = isWordCharacter ? 1 : 0;\n}\n\n/**\n * Gets word count. A word is a run of ASCII letters, digits and underscores,\n * the same as the regular expression `\\w+`.\n */\nexport const getWordCount = (corpus: string): number => {\n const text = toText(corpus);\n let count = 0;\n let insideWord = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n const isWordCharacter = code < 128 ? WORD_CHARACTERS[code] : 0;\n // A word starts where a word character follows a character that is not one.\n count += isWordCharacter & ~insideWord;\n insideWord = isWordCharacter;\n }\n return count;\n};\n\n/** Counts occurrences of `needle` in `text` that do not overlap. An empty needle occurs zero times. */\nconst countOccurrences = (needle: string, text: string): number => {\n if (needle.length === 0) {\n return 0;\n }\n let count = 0;\n let position = text.indexOf(needle);\n while (position !== -1) {\n count++;\n position = text.indexOf(needle, position + needle.length);\n }\n return count;\n};\n\n/**\n * Number of occurrences of a term in a string.\n *\n * The term is matched literally and case-sensitively, and occurrences do not\n * overlap. It is never interpreted as a regular expression, so terms such as\n * `c++` or `(a+)+$` are safe to pass straight from user input. An empty term\n * occurs zero times.\n */\nexport const getTermFrequency = (term: string, corpus: string): number =>\n countOccurrences(toText(term), toText(corpus));\n\n/** Inverse document frequency. */\nexport const getIDF = (term: string, documents: readonly string[]): number => {\n let relevantDocuments = 0;\n for (let i = 0; i < documents.length; i++) {\n if (toText(documents[i]).includes(term)) {\n relevantDocuments++;\n }\n }\n return Math.log(\n (documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1\n );\n};\n\n/** Represents a document; useful when sorting results.\n */\nexport interface BMDocument {\n /** The document that was scored. */\n document: string;\n /** The score that the document receives. */\n score: number;\n}\n\n/** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */\nexport interface BMConstants {\n /** Free parameter. Is 0.75 by default. `0` turns length normalization off, `1` applies it fully. */\n b?: number;\n /** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0]. `0` ignores how often a term occurs. */\n k1?: number;\n}\n\n/** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */\nexport type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;\n\n/** Implementation of Okapi BM25 algorithm.\n *\n * Keywords are matched literally and case-sensitively anywhere in a document.\n *\n * @param documents: Collection of documents.\n * @param keywords: query terms.\n * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.\n * @param sorter: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.\n * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.\n *\n * @example\n * const scores = BM25([\"a cat\", \"a dog\"], [\"cat\"]); // number[]\n * const ranked = BM25([\"a cat\", \"a dog\"], [\"cat\"], undefined, (x, y) => y.score - x.score); // BMDocument[]\n */\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants\n): number[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants: BMConstants | undefined,\n sorter: BMSorter\n): BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[] {\n if (!Array.isArray(documents)) {\n throw new TypeError(\"BM25: `documents` must be an array of strings.\");\n }\n if (!Array.isArray(keywords)) {\n throw new TypeError(\"BM25: `keywords` must be an array of strings.\");\n }\n const b = resolveConstant(constants ? constants.b : undefined, DEFAULT_B);\n const k1 = resolveConstant(constants ? constants.k1 : undefined, DEFAULT_K1);\n const documentCount = documents.length;\n\n // Each document is measured once.\n const texts: string[] = new Array(documentCount);\n const documentLengths = new Float64Array(documentCount);\n let totalLength = 0;\n for (let i = 0; i < documentCount; i++) {\n const text = toText(documents[i]);\n const length = getWordCount(text);\n texts[i] = text;\n documentLengths[i] = length;\n totalLength += length;\n }\n const averageDocumentLength =\n documentCount > 0 ? totalLength / documentCount : 0;\n\n // The part of the denominator that depends only on the document. A\n // collection with no countable words has no length to normalize by, so every\n // document is treated as being of average length.\n const lengthNorms = new Float64Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n const relativeLength =\n averageDocumentLength > 0\n ? (b * documentLengths[i]) / averageDocumentLength\n : b;\n lengthNorms[i] = k1 * (1 - b + relativeLength);\n }\n\n const scores: number[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scores[i] = 0;\n }\n\n // Each keyword reads every document once. That single pass gives both the\n // term frequencies and the number of documents containing the keyword.\n const matchedDocuments = new Uint32Array(documentCount);\n const matchedFrequencies = new Uint32Array(documentCount);\n for (let k = 0; k < keywords.length; k++) {\n // JavaScript callers may pass a number, such as a year. It is searched as text.\n const rawKeyword: unknown = keywords[k];\n const keyword =\n typeof rawKeyword === \"number\" ? String(rawKeyword) : toText(rawKeyword);\n let matches = 0;\n for (let i = 0; i < documentCount; i++) {\n const termFrequency = countOccurrences(keyword, texts[i]);\n if (termFrequency > 0) {\n matchedDocuments[matches] = i;\n matchedFrequencies[matches] = termFrequency;\n matches++;\n }\n }\n const inverseDocumentFrequency = Math.log(\n (documentCount - matches + 0.5) / (matches + 0.5) + 1\n );\n for (let m = 0; m < matches; m++) {\n const i = matchedDocuments[m];\n const termFrequency = matchedFrequencies[m];\n scores[i] +=\n (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /\n (termFrequency + lengthNorms[i]);\n }\n }\n\n if (sorter) {\n const scoredDocuments: BMDocument[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scoredDocuments[i] = { score: scores[i], document: documents[i] };\n }\n return scoredDocuments.sort(sorter);\n }\n return scores;\n}\n\n/** Options for {@link createIndex}. */\nexport interface BMIndexOptions {\n /**\n * Whether `Dog` and `dog` are different words. `false` by default: documents\n * and keywords are lowercased before they are split into words.\n */\n caseSensitive?: boolean;\n /**\n * Splits a text into words. It is called for every document and for every\n * keyword, after lowercasing unless `caseSensitive` is set. Empty words are\n * dropped. By default a word is a run of letters, digits and underscores in\n * any script. Pass a tokenizer for languages that are written without\n * spaces, or to remove common words or endings.\n */\n tokenizer?: (text: string) => string[];\n}\n\n/**\n * Options for {@link BMIndex.search}. Unlike `BM25`, an index rejects values\n * that cannot give a meaningful score: `k1` must be a finite number of 0 or\n * more and `b` a number from 0 to 1.\n */\nexport interface BMSearchOptions extends BMConstants {\n /** Return at most this many results. All matching documents by default. */\n limit?: number;\n}\n\n/** A document found by {@link BMIndex.search}. */\nexport interface BMHit extends BMDocument {\n /** Position of the document in the array given to {@link createIndex}. */\n index: number;\n}\n\n/** A searchable index of a fixed set of documents, made by {@link createIndex}. */\nexport interface BMIndex {\n /**\n * The documents that contain at least one of the keywords, best match first.\n * Documents with equal scores keep the order they were indexed in.\n */\n search(keywords: readonly string[], options?: BMSearchOptions): BMHit[];\n /**\n * One score per document, in the order the documents were indexed in. A\n * document that contains none of the keywords scores `0`.\n */\n scores(keywords: readonly string[], constants?: BMConstants): number[];\n}\n\n/** The documents containing a word, and how often each one contains it. */\ninterface Posting {\n documents: number[];\n frequencies: number[];\n}\n\n/** `undefined` when the JavaScript engine does not support the pattern. */\nconst compilePattern = (source: string, flags: string): RegExp | undefined => {\n try {\n return new RegExp(source, flags);\n } catch (error) {\n return undefined;\n }\n};\n\n/**\n * The default definition of a word for an index: a run of letters, marks that\n * combine with letters, digits and underscores, in any script. For ASCII text\n * these are the words that `getWordCount` counts. The pattern is compiled at\n * run time because its syntax is newer than the ES2015 this file is built\n * for; engines from before 2018 fall back to ASCII words.\n */\nconst WORDS = compilePattern(\"[\\\\p{L}\\\\p{M}\\\\p{N}_]+\", \"gu\") || /\\w+/g;\n\n/** Reads an option that has to be a number from 0 to `max`. `undefined` gives the default. */\nconst readNumber = (\n value: unknown,\n fallback: number,\n max: number,\n rule: string\n): number => {\n if (value === undefined) {\n return fallback;\n }\n if (typeof value !== \"number\") {\n throw new TypeError(\"BM25 index: \" + rule);\n }\n // Written so that NaN fails it too.\n if (!(value >= 0 && value <= max)) {\n throw new RangeError(\"BM25 index: \" + rule);\n }\n return value;\n};\n\n/**\n * Reads the documents once and builds an index of their words, so that each\n * later search looks words up instead of reading the text again. Worth it when\n * the same documents are searched many times.\n *\n * Matching differs from {@link BM25}: the index matches whole words. `cat`\n * finds the word `cat` and not `concatenate`, and case is ignored unless\n * `caseSensitive` is set. Keywords are split into words the same way as the\n * documents, so the keyword `dog?` finds the word `dog`. The scoring formula\n * and the defaults of `k1` and `b` are those of {@link BM25}.\n *\n * The index is a snapshot. Changing the array afterwards does not change it.\n *\n * @throws TypeError when `documents` is not an array, when `tokenizer` is not\n * a function, or when it returns something other than an array of strings.\n * `search` and `scores` throw a TypeError when `keywords` is not an array or\n * an option is not a number, and a RangeError when an option is out of range.\n *\n * @example\n * const index = createIndex([\"A quick dog\", \"A lazy cat\", \"Stock markets\"]);\n * index.search([\"Dog?\"]); // [{ index: 0, document: \"A quick dog\", score: 0.93... }]\n * index.scores([\"dog\"]); // [0.93..., 0, 0]\n */\nexport function createIndex(\n documents: readonly string[],\n options?: BMIndexOptions\n): BMIndex {\n if (!Array.isArray(documents)) {\n throw new TypeError(\n \"createIndex: `documents` must be an array of strings.\"\n );\n }\n const caseSensitive = options ? options.caseSensitive === true : false;\n const tokenizer = options ? options.tokenizer : undefined;\n if (tokenizer !== undefined && typeof tokenizer !== \"function\") {\n throw new TypeError(\"createIndex: `tokenizer` must be a function.\");\n }\n\n /** The words of a text. A custom tokenizer may return empty words; callers skip those. */\n const toWords = (text: string): string[] => {\n const prepared = caseSensitive ? text : text.toLowerCase();\n if (tokenizer === undefined) {\n return prepared.match(WORDS) || [];\n }\n const words: unknown = tokenizer(prepared);\n if (!Array.isArray(words)) {\n throw new TypeError(\n \"createIndex: `tokenizer` must return an array of strings.\"\n );\n }\n for (let w = 0; w < words.length; w++) {\n if (typeof words[w] !== \"string\") {\n throw new TypeError(\n \"createIndex: `tokenizer` must return an array of strings.\"\n );\n }\n }\n return words;\n };\n\n const documentCount = documents.length;\n const originals = documents.slice();\n // A Map, not an object, so that words such as `constructor` are ordinary keys.\n const postings = new Map<string, Posting>();\n const documentLengths = new Float64Array(documentCount);\n let totalLength = 0;\n for (let i = 0; i < documentCount; i++) {\n const words = toWords(toText(documents[i]));\n let length = 0;\n for (let w = 0; w < words.length; w++) {\n const word = words[w];\n if (word.length === 0) {\n continue;\n }\n length++;\n const posting = postings.get(word);\n if (posting === undefined) {\n postings.set(word, { documents: [i], frequencies: [1] });\n continue;\n }\n // Documents are added in order, so a repeat of the word within this\n // document is always at the end of the list.\n const last = posting.documents.length - 1;\n if (posting.documents[last] === i) {\n posting.frequencies[last]++;\n } else {\n posting.documents.push(i);\n posting.frequencies.push(1);\n }\n }\n documentLengths[i] = length;\n totalLength += length;\n }\n // Only read once a word has been found, and then at least one document has\n // a word, so it is a positive number wherever it is used.\n const averageDocumentLength = totalLength / documentCount;\n\n // Working memory shared by all searches, so that a search costs time in\n // proportion to the documents it finds and not to the size of the index.\n // Both are all zeros between searches: `clear` undoes what `collect` wrote.\n const totals = new Float64Array(documentCount);\n const isMatched = new Uint8Array(documentCount);\n\n /**\n * Adds the score of every document that contains a keyword into `totals`\n * and returns the positions of those documents, in the order they were\n * first found. The caller reads `totals` and then calls `clear`.\n */\n const collect = (\n keywords: readonly string[],\n constants: BMConstants | undefined\n ): number[] => {\n if (!Array.isArray(keywords)) {\n throw new TypeError(\n \"BM25 index: `keywords` must be an array of strings.\"\n );\n }\n const b = readNumber(\n constants ? constants.b : undefined,\n DEFAULT_B,\n 1,\n \"`b` must be a number from 0 to 1.\"\n );\n const k1 = readNumber(\n constants ? constants.k1 : undefined,\n DEFAULT_K1,\n Number.MAX_VALUE,\n \"`k1` must be a finite number, 0 or more.\"\n );\n // Every keyword is split into words before any score is added. The\n // tokenizer is the caller's code, and none of it runs, and nothing can\n // throw, while `totals` holds a search in progress.\n const words: string[] = [];\n for (let k = 0; k < keywords.length; k++) {\n // As in BM25, a number is searched as text and other values match nothing.\n const rawKeyword: unknown = keywords[k];\n const keywordWords = toWords(\n typeof rawKeyword === \"number\" ? String(rawKeyword) : toText(rawKeyword)\n );\n for (let w = 0; w < keywordWords.length; w++) {\n words.push(keywordWords[w]);\n }\n }\n\n const matched: number[] = [];\n for (let w = 0; w < words.length; w++) {\n const posting = postings.get(words[w]);\n if (posting === undefined) {\n continue;\n }\n const matches = posting.documents.length;\n // The arithmetic below is the same, operation for operation, as in\n // BM25, so both give identical scores when they match the same words.\n const inverseDocumentFrequency = Math.log(\n (documentCount - matches + 0.5) / (matches + 0.5) + 1\n );\n for (let m = 0; m < matches; m++) {\n const i = posting.documents[m];\n const termFrequency = posting.frequencies[m];\n const relativeLength =\n (b * documentLengths[i]) / averageDocumentLength;\n const lengthNorm = k1 * (1 - b + relativeLength);\n totals[i] +=\n (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /\n (termFrequency + lengthNorm);\n if (isMatched[i] === 0) {\n isMatched[i] = 1;\n matched.push(i);\n }\n }\n }\n return matched;\n };\n\n const clear = (matched: number[]): void => {\n for (let m = 0; m < matched.length; m++) {\n totals[matched[m]] = 0;\n isMatched[matched[m]] = 0;\n }\n };\n\n return {\n search(keywords, options) {\n const limit = readNumber(\n options ? options.limit : undefined,\n Infinity,\n Infinity,\n \"`limit` must be a number, 0 or more.\"\n );\n const matched = collect(keywords, options);\n // The position breaks ties, so the order never depends on the engine's sort.\n matched.sort(\n (first, second) => totals[second] - totals[first] || first - second\n );\n const hits: BMHit[] = new Array(\n Math.floor(Math.min(matched.length, limit))\n );\n for (let m = 0; m < hits.length; m++) {\n const i = matched[m];\n hits[m] = { index: i, document: originals[i], score: totals[i] };\n }\n clear(matched);\n return hits;\n },\n scores(keywords, constants) {\n const matched = collect(keywords, constants);\n const scores: number[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scores[i] = 0;\n }\n for (let m = 0; m < matched.length; m++) {\n scores[matched[m]] = totals[matched[m]];\n }\n clear(matched);\n return scores;\n },\n };\n}\n\nexport default BM25;\n"]}
|