okapibm25 1.4.0 → 2.0.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 +63 -22
- package/dist/BM25.d.ts +30 -10
- package/dist/BM25.js +130 -41
- package/dist/BM25.js.map +1 -1
- package/package.json +31 -10
- package/BM25.test.ts +0 -109
- package/BM25.ts +0 -85
- package/babel.config.js +0 -6
- package/coverage/BM25.ts.html +0 -335
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -79
- package/coverage/coverage-summary.json +0 -3
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -111
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -170
- package/dist/jest.config.d.ts +0 -7
- package/dist/jest.config.js +0 -9
- package/dist/jest.config.js.map +0 -1
- package/jest.config.ts +0 -6
- package/tsconfig.json +0 -10
package/README.md
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# okapibm25
|
|
2
2
|
|
|
3
|
+

|
|
3
4
|

|
|
4
5
|

|
|
5
6
|

|
|
6
7
|

|
|
7
8
|
|
|
8
9
|
|
|
9
|
-
A strongly typed,
|
|
10
|
+
A strongly typed, tested, and profiled implementation of the [Okapi BM25 algorithm](https://en.wikipedia.org/wiki/Okapi_BM25). Just provide your documents to search, query keywords, and (optionally) your weights (*b* and *k1*).
|
|
11
|
+
|
|
12
|
+
Install the [NPM package!](https://www.npmjs.com/package/okapibm25)
|
|
13
|
+
|
|
14
|
+
## Used by
|
|
15
|
+
- https://www.llamaindex.ai
|
|
16
|
+
- https://www.librechat.ai
|
|
17
|
+
- https://illuma.cx
|
|
18
|
+
- https://www.observee.com/
|
|
10
19
|
|
|
11
20
|
## Installation
|
|
12
|
-
|
|
13
|
-
```
|
|
21
|
+
```sh
|
|
14
22
|
npm install okapibm25 --save
|
|
15
23
|
```
|
|
16
24
|
## Usage
|
|
17
|
-
```
|
|
25
|
+
```ts
|
|
18
26
|
import { BM25 } from "okapibm25";
|
|
19
27
|
|
|
20
28
|
const documents = [
|
|
@@ -23,35 +31,68 @@ const documents = [
|
|
|
23
31
|
"here",
|
|
24
32
|
"Each test document will be searched with the keywords specified below.",
|
|
25
33
|
];
|
|
26
|
-
const query = ["keywords", "of", "your", "query
|
|
27
|
-
// A numerical scoring will be returned.
|
|
28
|
-
const result = BM25(documents, query, { k1: 1.3, b: 0.9 })
|
|
34
|
+
const query = ["keywords", "of", "your", "query"];
|
|
35
|
+
// A numerical scoring will be returned, one score per document.
|
|
36
|
+
const result = BM25(documents, query, { k1: 1.3, b: 0.9 });
|
|
29
37
|
console.log(result);
|
|
30
|
-
|
|
38
|
+
```
|
|
39
|
+
Every one of these gives you the same function:
|
|
40
|
+
```ts
|
|
41
|
+
import { BM25 } from "okapibm25"; // TypeScript, bundlers, Node ES modules
|
|
42
|
+
import BM25 from "okapibm25"; // TypeScript and bundlers
|
|
43
|
+
const { BM25 } = require("okapibm25"); // CommonJS
|
|
31
44
|
```
|
|
32
45
|
### Sorting
|
|
33
|
-
|
|
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)
|
|
34
47
|
|
|
35
48
|
Here is an example of how to sort in descending order (by score).
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
49
|
+
```ts
|
|
50
|
+
const results = BM25(
|
|
51
|
+
documents,
|
|
52
|
+
["relevant"],
|
|
53
|
+
undefined,
|
|
54
|
+
(firstEl, secondEl) => {
|
|
55
|
+
return secondEl.score - firstEl.score;
|
|
56
|
+
}
|
|
57
|
+
);
|
|
45
58
|
```
|
|
46
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!
|
|
47
60
|
|
|
48
|
-
*Important:* Note that enabling sorting changes the return type from `number[]` to `{ document: string; score: number; }[]
|
|
61
|
+
*Important:* Note that enabling sorting changes the return type from `number[]` to `{ document: string; score: number; }[]`. TypeScript knows which one you get, so no cast is needed.
|
|
62
|
+
|
|
63
|
+
### How matching works
|
|
64
|
+
- A keyword matches wherever its exact text appears in a document, including inside a longer word: `"cat"` matches `"concatenate"`.
|
|
65
|
+
- 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. Version 1 treated keywords as regular expressions; if you are upgrading, see "Upgrading from 1.x" in `CHANGELOG.md`.
|
|
67
|
+
- 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`: `k1: 0` ignores how often a keyword occurs and `b: 0` ignores document length.
|
|
49
69
|
|
|
50
|
-
|
|
51
|
-
|
|
70
|
+
### Speed
|
|
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`.
|
|
52
72
|
|
|
53
73
|
## License
|
|
54
74
|
Under `license.md`
|
|
55
75
|
|
|
56
76
|
## Contributing
|
|
57
77
|
Submit a Pull Request if you have a useful feature that you'd like to add. If you're too lazy or this isn't your area of expertise, open an issue and I'll get to it.
|
|
78
|
+
|
|
79
|
+
Working on the package needs Node 22.18 or later. The published package itself runs on Node 12 and later.
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
npm install
|
|
83
|
+
npm run check # typecheck, tests, build, package check
|
|
84
|
+
npm test # tests only; coverage must stay at 100%
|
|
85
|
+
npm run bench # speed compared with version 1.4.1
|
|
86
|
+
|
|
87
|
+
npm run test:compat # the packed package on TypeScript 4.0 to current, esbuild, webpack and vite
|
|
88
|
+
npm run test:downstream # the largest dependent package gives the same results as with the published version
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The tests in `tests/regression` compare the code against the published 1.4.1 build, so a change in scores shows up as a failure. If you change scores on purpose, add the case to `tests/behavior_changes.test.ts` and note it in `CHANGELOG.md`. A change to the exported types or names fails the check until you update the snapshot with `npm run test:api -- --update`.
|
|
92
|
+
|
|
93
|
+
To release, bump `version` in `package.json`, move the notes in `CHANGELOG.md` under a heading for that version, and merge the pull request. The `Publish` workflow then publishes the new version to npm and creates the GitHub release. `node scripts/publish-plan.mjs` shows what it would do.
|
|
94
|
+
|
|
95
|
+
To report a security problem, see `SECURITY.md`.
|
|
96
|
+
|
|
97
|
+
## Sponsorship
|
|
98
|
+
Consider donating $5 to https://www.unicef.org/ if this has been useful to you.
|
package/dist/BM25.d.ts
CHANGED
|
@@ -1,31 +1,51 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Gets word count. A word is a run of ASCII letters, digits and underscores,
|
|
3
|
+
* the same as the regular expression `\w+`.
|
|
4
|
+
*/
|
|
2
5
|
export declare const getWordCount: (corpus: string) => number;
|
|
3
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Number of occurrences of a term in a string.
|
|
8
|
+
*
|
|
9
|
+
* The term is matched literally and case-sensitively, and occurrences do not
|
|
10
|
+
* overlap. It is never interpreted as a regular expression, so terms such as
|
|
11
|
+
* `c++` or `(a+)+$` are safe to pass straight from user input. An empty term
|
|
12
|
+
* occurs zero times.
|
|
13
|
+
*/
|
|
4
14
|
export declare const getTermFrequency: (term: string, corpus: string) => number;
|
|
5
15
|
/** Inverse document frequency. */
|
|
6
|
-
export declare const getIDF: (term: string, documents: string[]) => number;
|
|
16
|
+
export declare const getIDF: (term: string, documents: readonly string[]) => number;
|
|
7
17
|
/** Represents a document; useful when sorting results.
|
|
8
18
|
*/
|
|
9
19
|
export interface BMDocument {
|
|
10
|
-
/** The document
|
|
20
|
+
/** The document that was scored. */
|
|
11
21
|
document: string;
|
|
12
|
-
/** The score that the document
|
|
22
|
+
/** The score that the document receives. */
|
|
13
23
|
score: number;
|
|
14
24
|
}
|
|
15
25
|
/** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */
|
|
16
26
|
export interface BMConstants {
|
|
17
|
-
/** Free parameter. Is 0.75 by default.
|
|
27
|
+
/** Free parameter. Is 0.75 by default. `0` turns length normalization off, `1` applies it fully. */
|
|
18
28
|
b?: number;
|
|
19
|
-
/** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0] */
|
|
29
|
+
/** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0]. `0` ignores how often a term occurs. */
|
|
20
30
|
k1?: number;
|
|
21
31
|
}
|
|
22
32
|
/** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */
|
|
23
|
-
export
|
|
33
|
+
export type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;
|
|
24
34
|
/** Implementation of Okapi BM25 algorithm.
|
|
35
|
+
*
|
|
36
|
+
* Keywords are matched literally and case-sensitively anywhere in a document.
|
|
37
|
+
*
|
|
25
38
|
* @param documents: Collection of documents.
|
|
26
39
|
* @param keywords: query terms.
|
|
27
40
|
* @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
|
|
28
|
-
* @param
|
|
41
|
+
* @param sorter: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
|
|
29
42
|
* If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const scores = BM25(["a cat", "a dog"], ["cat"]); // number[]
|
|
46
|
+
* const ranked = BM25(["a cat", "a dog"], ["cat"], undefined, (x, y) => y.score - x.score); // BMDocument[]
|
|
30
47
|
*/
|
|
31
|
-
export
|
|
48
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants): number[];
|
|
49
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants: BMConstants | undefined, sorter: BMSorter): BMDocument[];
|
|
50
|
+
export declare function BM25(documents: readonly string[], keywords: readonly string[], constants?: BMConstants, sorter?: BMSorter): number[] | BMDocument[];
|
|
51
|
+
export default BM25;
|
package/dist/BM25.js
CHANGED
|
@@ -1,55 +1,144 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getIDF = exports.getTermFrequency = exports.getWordCount = void 0;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
exports.BM25 = BM25;
|
|
5
|
+
/** Default value of the free parameter `b`. */
|
|
6
|
+
const DEFAULT_B = 0.75;
|
|
7
|
+
/** Default value of the free parameter `k1`. */
|
|
8
|
+
const DEFAULT_K1 = 1.2;
|
|
9
|
+
/** Anything that is not a string is scored as an empty document. */
|
|
10
|
+
const toText = (value) => typeof value === "string" ? value : "";
|
|
11
|
+
/** A free parameter is used when it is a real number, `0` included. Anything else falls back to the default. */
|
|
12
|
+
const resolveConstant = (value, fallback) => typeof value === "number" && !Number.isNaN(value) ? value : fallback;
|
|
13
|
+
/** 1 for the ASCII characters that `\w` matches (letters, digits, underscore), 0 for the rest. */
|
|
14
|
+
const WORD_CHARACTERS = new Uint8Array(128);
|
|
15
|
+
for (let code = 0; code < 128; code++) {
|
|
16
|
+
const isWordCharacter = (code >= 97 && code <= 122) || // a-z
|
|
17
|
+
(code >= 65 && code <= 90) || // A-Z
|
|
18
|
+
(code >= 48 && code <= 57) || // 0-9
|
|
19
|
+
code === 95; // _
|
|
20
|
+
WORD_CHARACTERS[code] = isWordCharacter ? 1 : 0;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Gets word count. A word is a run of ASCII letters, digits and underscores,
|
|
24
|
+
* the same as the regular expression `\w+`.
|
|
25
|
+
*/
|
|
26
|
+
const getWordCount = (corpus) => {
|
|
27
|
+
const text = toText(corpus);
|
|
28
|
+
let count = 0;
|
|
29
|
+
let insideWord = 0;
|
|
30
|
+
for (let i = 0; i < text.length; i++) {
|
|
31
|
+
const code = text.charCodeAt(i);
|
|
32
|
+
const isWordCharacter = code < 128 ? WORD_CHARACTERS[code] : 0;
|
|
33
|
+
// A word starts where a word character follows a character that is not one.
|
|
34
|
+
count += isWordCharacter & ~insideWord;
|
|
35
|
+
insideWord = isWordCharacter;
|
|
36
|
+
}
|
|
37
|
+
return count;
|
|
7
38
|
};
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
39
|
+
exports.getWordCount = getWordCount;
|
|
40
|
+
/** Counts occurrences of `needle` in `text` that do not overlap. An empty needle occurs zero times. */
|
|
41
|
+
const countOccurrences = (needle, text) => {
|
|
42
|
+
if (needle.length === 0) {
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
let count = 0;
|
|
46
|
+
let position = text.indexOf(needle);
|
|
47
|
+
while (position !== -1) {
|
|
48
|
+
count++;
|
|
49
|
+
position = text.indexOf(needle, position + needle.length);
|
|
50
|
+
}
|
|
51
|
+
return count;
|
|
11
52
|
};
|
|
53
|
+
/**
|
|
54
|
+
* Number of occurrences of a term in a string.
|
|
55
|
+
*
|
|
56
|
+
* The term is matched literally and case-sensitively, and occurrences do not
|
|
57
|
+
* overlap. It is never interpreted as a regular expression, so terms such as
|
|
58
|
+
* `c++` or `(a+)+$` are safe to pass straight from user input. An empty term
|
|
59
|
+
* occurs zero times.
|
|
60
|
+
*/
|
|
61
|
+
const getTermFrequency = (term, corpus) => countOccurrences(toText(term), toText(corpus));
|
|
62
|
+
exports.getTermFrequency = getTermFrequency;
|
|
12
63
|
/** Inverse document frequency. */
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
64
|
+
const getIDF = (term, documents) => {
|
|
65
|
+
let relevantDocuments = 0;
|
|
66
|
+
for (let i = 0; i < documents.length; i++) {
|
|
67
|
+
if (toText(documents[i]).includes(term)) {
|
|
68
|
+
relevantDocuments++;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
18
71
|
return Math.log((documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1);
|
|
19
72
|
};
|
|
20
|
-
|
|
21
|
-
* @param documents: Collection of documents.
|
|
22
|
-
* @param keywords: query terms.
|
|
23
|
-
* @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
|
|
24
|
-
* @param sort: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
|
|
25
|
-
* If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
|
|
26
|
-
*/
|
|
73
|
+
exports.getIDF = getIDF;
|
|
27
74
|
function BM25(documents, keywords, constants, sorter) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
75
|
+
if (!Array.isArray(documents)) {
|
|
76
|
+
throw new TypeError("BM25: `documents` must be an array of strings.");
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(keywords)) {
|
|
79
|
+
throw new TypeError("BM25: `keywords` must be an array of strings.");
|
|
80
|
+
}
|
|
81
|
+
const b = resolveConstant(constants ? constants.b : undefined, DEFAULT_B);
|
|
82
|
+
const k1 = resolveConstant(constants ? constants.k1 : undefined, DEFAULT_K1);
|
|
83
|
+
const documentCount = documents.length;
|
|
84
|
+
// Each document is measured once.
|
|
85
|
+
const texts = new Array(documentCount);
|
|
86
|
+
const documentLengths = new Float64Array(documentCount);
|
|
87
|
+
let totalLength = 0;
|
|
88
|
+
for (let i = 0; i < documentCount; i++) {
|
|
89
|
+
const text = toText(documents[i]);
|
|
90
|
+
const length = (0, exports.getWordCount)(text);
|
|
91
|
+
texts[i] = text;
|
|
92
|
+
documentLengths[i] = length;
|
|
93
|
+
totalLength += length;
|
|
94
|
+
}
|
|
95
|
+
const averageDocumentLength = documentCount > 0 ? totalLength / documentCount : 0;
|
|
96
|
+
// The part of the denominator that depends only on the document. A
|
|
97
|
+
// collection with no countable words has no length to normalize by, so every
|
|
98
|
+
// document is treated as being of average length.
|
|
99
|
+
const lengthNorms = new Float64Array(documentCount);
|
|
100
|
+
for (let i = 0; i < documentCount; i++) {
|
|
101
|
+
const relativeLength = averageDocumentLength > 0
|
|
102
|
+
? (b * documentLengths[i]) / averageDocumentLength
|
|
103
|
+
: b;
|
|
104
|
+
lengthNorms[i] = k1 * (1 - b + relativeLength);
|
|
105
|
+
}
|
|
106
|
+
const scores = new Array(documentCount);
|
|
107
|
+
for (let i = 0; i < documentCount; i++) {
|
|
108
|
+
scores[i] = 0;
|
|
109
|
+
}
|
|
110
|
+
// Each keyword reads every document once. That single pass gives both the
|
|
111
|
+
// term frequencies and the number of documents containing the keyword.
|
|
112
|
+
const matchedDocuments = new Uint32Array(documentCount);
|
|
113
|
+
const matchedFrequencies = new Uint32Array(documentCount);
|
|
114
|
+
for (let k = 0; k < keywords.length; k++) {
|
|
115
|
+
// JavaScript callers may pass a number, such as a year. It is searched as text.
|
|
116
|
+
const rawKeyword = keywords[k];
|
|
117
|
+
const keyword = typeof rawKeyword === "number" ? String(rawKeyword) : toText(rawKeyword);
|
|
118
|
+
let matches = 0;
|
|
119
|
+
for (let i = 0; i < documentCount; i++) {
|
|
120
|
+
const termFrequency = countOccurrences(keyword, texts[i]);
|
|
121
|
+
if (termFrequency > 0) {
|
|
122
|
+
matchedDocuments[matches] = i;
|
|
123
|
+
matchedFrequencies[matches] = termFrequency;
|
|
124
|
+
matches++;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const inverseDocumentFrequency = Math.log((documentCount - matches + 0.5) / (matches + 0.5) + 1);
|
|
128
|
+
for (let m = 0; m < matches; m++) {
|
|
129
|
+
const i = matchedDocuments[m];
|
|
130
|
+
const termFrequency = matchedFrequencies[m];
|
|
131
|
+
scores[i] +=
|
|
132
|
+
(inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
|
|
133
|
+
(termFrequency + lengthNorms[i]);
|
|
47
134
|
}
|
|
48
|
-
|
|
49
|
-
});
|
|
50
|
-
// sort the results
|
|
135
|
+
}
|
|
51
136
|
if (sorter) {
|
|
52
|
-
|
|
137
|
+
const scoredDocuments = new Array(documentCount);
|
|
138
|
+
for (let i = 0; i < documentCount; i++) {
|
|
139
|
+
scoredDocuments[i] = { score: scores[i], document: documents[i] };
|
|
140
|
+
}
|
|
141
|
+
return scoredDocuments.sort(sorter);
|
|
53
142
|
}
|
|
54
143
|
return scores;
|
|
55
144
|
}
|
package/dist/BM25.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BM25.js","sourceRoot":"","sources":["../BM25.ts"],"names":[],"mappings":";;;AAAA,uBAAuB;AACV,QAAA,YAAY,GAAG,UAAC,MAAc;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrD,CAAC,CAAC;AAEF,kDAAkD;AACrC,QAAA,gBAAgB,GAAG,UAAC,IAAY,EAAE,MAAc;IAC3D,OAAO,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACpE,CAAC,CAAC;AAEF,kCAAkC;AACrB,QAAA,MAAM,GAAG,UAAC,IAAY,EAAE,SAAmB;IACtD,gCAAgC;IAChC,IAAM,iBAAiB,GAAG,SAAS,CAAC,MAAM,CAAC,UAAC,QAAgB;QAC1D,OAAA,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC;IAAvB,CAAuB,CACxB,CAAC,MAAM,CAAC;IACT,OA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/** 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"]}
|
package/package.json
CHANGED
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "okapibm25",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "A simple, easy to use implementation of the Okapi BM25 algorithm.",
|
|
5
5
|
"main": "dist/BM25.js",
|
|
6
6
|
"types": "dist/BM25.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"sideEffects": false,
|
|
7
11
|
"scripts": {
|
|
12
|
+
"build": "node scripts/clean.mjs && tsc -p tsconfig.build.json",
|
|
13
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
8
14
|
"test": "jest",
|
|
9
|
-
"
|
|
10
|
-
"
|
|
15
|
+
"test:package": "npm run build && node scripts/check-package.mjs",
|
|
16
|
+
"test:api": "npm run build && node scripts/check-api.mjs",
|
|
17
|
+
"test:compat": "npm run build && node compat/run.mjs",
|
|
18
|
+
"test:downstream": "npm run build && node compat/downstream.mjs",
|
|
19
|
+
"bench": "npm run build && node bench/bench.mjs",
|
|
20
|
+
"check": "npm run typecheck && npm test && npm run test:package && node scripts/check-api.mjs",
|
|
21
|
+
"make-badges": "istanbul-badges-readme",
|
|
22
|
+
"prepublishOnly": "npm run check && npm run make-badges"
|
|
11
23
|
},
|
|
12
24
|
"author": "furkantoprak",
|
|
13
25
|
"keywords": [
|
|
@@ -15,19 +27,28 @@
|
|
|
15
27
|
"bm25",
|
|
16
28
|
"ranking",
|
|
17
29
|
"relevance",
|
|
18
|
-
"information retrieval"
|
|
30
|
+
"information retrieval",
|
|
31
|
+
"search",
|
|
32
|
+
"typescript"
|
|
19
33
|
],
|
|
20
34
|
"repository": {
|
|
21
35
|
"type": "git",
|
|
22
36
|
"url": "https://github.com/FurkanToprak/OkapiBM25.git"
|
|
23
37
|
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/FurkanToprak/OkapiBM25/issues"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/FurkanToprak/OkapiBM25#readme",
|
|
24
42
|
"license": "MIT",
|
|
25
43
|
"devDependencies": {
|
|
26
|
-
"@babel/
|
|
27
|
-
"@
|
|
28
|
-
"
|
|
29
|
-
"jest": "^
|
|
30
|
-
"
|
|
31
|
-
"
|
|
44
|
+
"@babel/core": "^8.1.3",
|
|
45
|
+
"@babel/preset-env": "^8.0.7",
|
|
46
|
+
"@babel/preset-typescript": "^8.0.7",
|
|
47
|
+
"@types/jest": "^30.0.0",
|
|
48
|
+
"@types/node": "^26.6.6",
|
|
49
|
+
"fast-check": "^4.11.0",
|
|
50
|
+
"istanbul-badges-readme": "^1.9.0",
|
|
51
|
+
"jest": "^30.5.2",
|
|
52
|
+
"typescript": "^7.0.2"
|
|
32
53
|
}
|
|
33
54
|
}
|
package/BM25.test.ts
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import BM25, { BMDocument, getTermFrequency, getWordCount } from "./BM25";
|
|
2
|
-
|
|
3
|
-
describe("Bare bones functionality", () => {
|
|
4
|
-
test("Irrelevant queries should return 0.", () => {
|
|
5
|
-
const documents = ["fee", "fi", "fum"];
|
|
6
|
-
const query = ["qwerty"];
|
|
7
|
-
const results = BM25(documents, query, { k1: 1.3, b: 0.9 }) as number[];
|
|
8
|
-
results.forEach((result: number) => {
|
|
9
|
-
expect(result).toBe(0);
|
|
10
|
-
});
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
test("Relevant queries should be greater than 0.", () => {
|
|
14
|
-
const documents = ["fee", "feel", "I'm feeling lucky."];
|
|
15
|
-
const query = ["fee"];
|
|
16
|
-
const results = BM25(documents, query) as number[];
|
|
17
|
-
results.forEach((result: number) => {
|
|
18
|
-
expect(result).toBeGreaterThan(0);
|
|
19
|
-
});
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
test("Make sure word count is detected correctly", () => {
|
|
23
|
-
const expectResults = [
|
|
24
|
-
{
|
|
25
|
-
corpus: "Pass the potatoes.",
|
|
26
|
-
expect: 3,
|
|
27
|
-
},
|
|
28
|
-
{ corpus: "pass.the.potatoes", expect: 3 },
|
|
29
|
-
{ corpus: "pass\nthe\npotatoes.", expect: 3 },
|
|
30
|
-
];
|
|
31
|
-
expectResults.forEach((expectResult) => {
|
|
32
|
-
const wordCount = getWordCount(expectResult.corpus);
|
|
33
|
-
expect(wordCount).toBe(expectResult.expect);
|
|
34
|
-
});
|
|
35
|
-
const emptyWordCount = getWordCount(null);
|
|
36
|
-
expect(emptyWordCount).toBe(0);
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
test("Expect word frequency to be detected correctly", () => {
|
|
40
|
-
// @ts-ignore
|
|
41
|
-
const emptyWordFrequency = getTermFrequency("anything", null);
|
|
42
|
-
expect(emptyWordFrequency).toBe(0);
|
|
43
|
-
const expectResults = [
|
|
44
|
-
{
|
|
45
|
-
corpus: "Pass the pass.",
|
|
46
|
-
term: "pass",
|
|
47
|
-
expect: 1,
|
|
48
|
-
},
|
|
49
|
-
{
|
|
50
|
-
corpus: "Pass the pass.",
|
|
51
|
-
term: "Pass",
|
|
52
|
-
expect: 1,
|
|
53
|
-
},
|
|
54
|
-
{
|
|
55
|
-
corpus: "Pass.pass.pass.",
|
|
56
|
-
term: "pass",
|
|
57
|
-
expect: 2,
|
|
58
|
-
},
|
|
59
|
-
];
|
|
60
|
-
expectResults.forEach((expectResult) => {
|
|
61
|
-
const result = getTermFrequency(expectResult.term, expectResult.corpus);
|
|
62
|
-
expect(result).toBe(expectResult.expect);
|
|
63
|
-
});
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
describe("Testing fancy sorting mechanism.", () => {
|
|
68
|
-
test("Should sort in ascending order", () => {
|
|
69
|
-
const expectResults = new Map<number, string>();
|
|
70
|
-
expectResults.set(0, "The least relevant");
|
|
71
|
-
expectResults.set(1, "Medium relevant relevant");
|
|
72
|
-
expectResults.set(2, "The most relevant relevant relevant relevant");
|
|
73
|
-
|
|
74
|
-
const corpuses = Array.from(expectResults.values());
|
|
75
|
-
const results = BM25(
|
|
76
|
-
corpuses,
|
|
77
|
-
["relevant"],
|
|
78
|
-
undefined,
|
|
79
|
-
(firstEl, secondEl) => {
|
|
80
|
-
return firstEl.score - secondEl.score;
|
|
81
|
-
}
|
|
82
|
-
) as BMDocument[];
|
|
83
|
-
results.forEach((result, index) => {
|
|
84
|
-
const expectedDocument = expectResults.get(index);
|
|
85
|
-
expect(expectedDocument).toEqual(result.document);
|
|
86
|
-
});
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
test("Should sort in descending order", () => {
|
|
90
|
-
const expectResults = new Map<number, string>();
|
|
91
|
-
expectResults.set(2, "The least relevant");
|
|
92
|
-
expectResults.set(1, "Medium relevant relevant");
|
|
93
|
-
expectResults.set(0, "The most relevant relevant relevant relevant");
|
|
94
|
-
|
|
95
|
-
const corpuses = Array.from(expectResults.values());
|
|
96
|
-
const results = BM25(
|
|
97
|
-
corpuses,
|
|
98
|
-
["relevant"],
|
|
99
|
-
undefined,
|
|
100
|
-
(firstEl, secondEl) => {
|
|
101
|
-
return secondEl.score - firstEl.score;
|
|
102
|
-
}
|
|
103
|
-
) as BMDocument[];
|
|
104
|
-
results.forEach((result, index) => {
|
|
105
|
-
const expectedDocument = expectResults.get(index);
|
|
106
|
-
expect(expectedDocument).toEqual(result.document);
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
});
|