@mark1russell7/text 0.0.14 → 0.0.15
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 +1 -0
- package/build/search.d.ts +12 -0
- package/build/search.d.ts.map +1 -1
- package/build/search.js +25 -7
- package/build/search.js.map +1 -1
- package/package.json +1 -1
- package/src/search.ts +22 -3
package/README.md
CHANGED
|
@@ -74,6 +74,7 @@ The entry `@mark1russell7/text/search` also ranks the documents of a corpus for
|
|
|
74
74
|
- `inverseDocumentFrequency(documents, form)` gives the IDF of each term. The form `plain` is ln(N / df), so a term in each document has the weight 0. The form `smooth` is ln((N + 1) / (df + 1)) + 1.
|
|
75
75
|
- `termVector(words, idf)` gives the weights (1 + ln(tf)) × idf with a length of 1. `cosineSimilarity(a, b)` compares two vectors.
|
|
76
76
|
- `rankDocuments(corpus, query, form)` gives the score of each document, best first. A tie keeps the order of the corpus.
|
|
77
|
+
- `rankerOf(corpus, form)` computes the IDF and the vectors of a corpus one time. It gives a function of a query with the same scores as `rankDocuments`.
|
|
77
78
|
|
|
78
79
|
```ts
|
|
79
80
|
import { rankDocuments, searchWords } from "@mark1russell7/text/search";
|
package/build/search.d.ts
CHANGED
|
@@ -110,4 +110,16 @@ export interface DocumentScore {
|
|
|
110
110
|
* @returns The score of each document, best first.
|
|
111
111
|
*/
|
|
112
112
|
export declare function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form?: IdfForm): DocumentScore[];
|
|
113
|
+
/**
|
|
114
|
+
* This function makes a ranker for one corpus. It computes the IDF and the vector of each document one time. It has no I/O.
|
|
115
|
+
*
|
|
116
|
+
* - For each query, the ranker gives the same scores as `rankDocuments(corpus, query, form)`.
|
|
117
|
+
* - A query costs one vector and one cosine for each document. Use the ranker when many queries search one corpus.
|
|
118
|
+
* - The ranker keeps the vectors of the corpus at the time of the call. A later change of the corpus does not change it.
|
|
119
|
+
*
|
|
120
|
+
* @param corpus - The documents, each as a list of words.
|
|
121
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
122
|
+
* @returns A function that gives the score of each document for a query, best first.
|
|
123
|
+
*/
|
|
124
|
+
export declare function rankerOf(corpus: readonly (readonly string[])[], form?: IdfForm): (query: readonly string[]) => DocumentScore[];
|
|
113
125
|
//# sourceMappingURL=search.d.ts.map
|
package/build/search.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.d.ts","names":[],"sources":["../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"search.d.ts","names":[],"sources":["../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;wBA4BgB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB;;iBAQ3B;;WAEN,OAAO;;WAEP,QAAQ;;WAER,QAAQ;;;;;;;;;;;;;;;wBAmBH,YAAY,cAAc,UAAS;;;;;;;;YAmBvC;;;;;;;;;;;wBAYI,yBAAyB,2CAA2C,OAAM,UAAoB;;;;;;;;;;;;wBAkB9F,WAAW,0BAA0B,KAAK,8BAA8B;;;;;;;;;;wBA0BxE,iBAAiB,GAAG,6BAA6B,GAAG;;iBAQnD;;WAEN;;WAEA;;;;;;;;;;;;;;wBAeK,cAAc,wCAAwC,0BAA0B,OAAM,UAAoB;;;;;;;;;;;;wBAe1G,SAAS,wCAAwC,OAAM,WAAqB,6BAA6B"}
|
package/build/search.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* in any order. The case of the letters is not significant.
|
|
5
5
|
*
|
|
6
6
|
* The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.
|
|
7
|
-
* `rankDocuments` puts the documents of a corpus in order for a query.
|
|
7
|
+
* `rankDocuments` puts the documents of a corpus in order for a query. `rankerOf` does this for many queries on one corpus.
|
|
8
|
+
* Each function has no I/O.
|
|
8
9
|
*/
|
|
9
10
|
/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
|
|
10
11
|
const FINAL_SIGMA = /ς/gu;
|
|
@@ -138,13 +139,30 @@ function cosineSimilarity(a, b) {
|
|
|
138
139
|
* @returns The score of each document, best first.
|
|
139
140
|
*/
|
|
140
141
|
function rankDocuments(corpus, query, form = "plain") {
|
|
142
|
+
return rankerOf(corpus, form)(query);
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* This function makes a ranker for one corpus. It computes the IDF and the vector of each document one time. It has no I/O.
|
|
146
|
+
*
|
|
147
|
+
* - For each query, the ranker gives the same scores as `rankDocuments(corpus, query, form)`.
|
|
148
|
+
* - A query costs one vector and one cosine for each document. Use the ranker when many queries search one corpus.
|
|
149
|
+
* - The ranker keeps the vectors of the corpus at the time of the call. A later change of the corpus does not change it.
|
|
150
|
+
*
|
|
151
|
+
* @param corpus - The documents, each as a list of words.
|
|
152
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
153
|
+
* @returns A function that gives the score of each document for a query, best first.
|
|
154
|
+
*/
|
|
155
|
+
function rankerOf(corpus, form = "plain") {
|
|
141
156
|
const idf = inverseDocumentFrequency(corpus, form);
|
|
142
|
-
const
|
|
143
|
-
return
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
157
|
+
const vectors = corpus.map((document) => termVector(document, idf));
|
|
158
|
+
return (query) => {
|
|
159
|
+
const q = termVector(query, idf);
|
|
160
|
+
return vectors.map((vector, index) => ({
|
|
161
|
+
index,
|
|
162
|
+
score: cosineSimilarity(q, vector)
|
|
163
|
+
})).sort((a, b) => b.score - a.score);
|
|
164
|
+
};
|
|
147
165
|
}
|
|
148
|
-
export { cosineSimilarity, inverseDocumentFrequency, rankDocuments, searchKey, searchWords, termVector, wordSearch };
|
|
166
|
+
export { cosineSimilarity, inverseDocumentFrequency, rankDocuments, rankerOf, searchKey, searchWords, termVector, wordSearch };
|
|
149
167
|
|
|
150
168
|
//# sourceMappingURL=search.js.map
|
package/build/search.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.js","names":[],"sources":["../src/search.ts"],"sourcesContent":["/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n *\n * The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.\n * `rankDocuments` puts the documents of a corpus in order for a query. Each function has no I/O.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n\n/** The options of `searchWords`. Each option is a rule of the caller, for example a list of stop words of a language. */\nexport interface WordOptions {\n /** The words that do not go in, as search keys. */\n readonly stop?: ReadonlySet<string>;\n /** The test of a word after the stop words. A word goes in only when the test gives true. */\n readonly keep?: (word: string) => boolean;\n /** The change of a word that goes in, for example a cut of a plural ending. */\n readonly stem?: (word: string) => string;\n}\n\n/** The word segmenter of `searchWords`. A segmenter is costly to make, so the module makes it one time, at the first use. */\nlet wordSegmenter: Intl.Segmenter | undefined;\n\n/**\n * This function gives the words of a text, in their order, for a ranked search. The function does these steps:\n *\n * 1. It makes the search key of the text with `searchKey`.\n * 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments\n * that are words or numbers, not spaces or punctuation.\n * 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.\n * 4. It applies `options.stem` to each word that stays.\n *\n * @param text - The plain text.\n * @param options - The rules of the caller. With no options, each word goes in with no change.\n * @returns The words of the text.\n */\nexport function searchWords(text: string, options: WordOptions = {}): string[] {\n const out: string[] = [];\n wordSegmenter ??= new Intl.Segmenter(\"en\", { granularity: \"word\" });\n for (const segment of wordSegmenter.segment(searchKey(text))) {\n if (!segment.isWordLike) continue;\n const word = segment.segment;\n if (options.stop?.has(word) || (options.keep && !options.keep(word))) continue;\n out.push(options.stem ? options.stem(word) : word);\n }\n return out;\n}\n\n/**\n * The two forms of the inverse document frequency (IDF) of a term. N is the count of documents, and df is the count of\n * the documents that have the term.\n *\n * - `plain` is ln(N / df). A term in each document has the weight 0, so it does not change a rank.\n * - `smooth` is ln((N + 1) / (df + 1)) + 1, as scikit-learn computes it. Each term has a weight of 1 or more.\n */\nexport type IdfForm = \"plain\" | \"smooth\";\n\n/**\n * This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for\n * example from `searchWords`. A term counts one time in each document that has it.\n *\n * The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.\n *\n * @param documents - The corpus.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The IDF of each term of the corpus.\n */\nexport function inverseDocumentFrequency(documents: readonly (readonly string[])[], form: IdfForm = \"plain\"): Map<string, number> {\n const df = new Map<string, number>();\n for (const document of documents) for (const term of new Set(document)) df.set(term, (df.get(term) ?? 0) + 1);\n const n = documents.length;\n return new Map([...df].map(([term, count]) => [term, form === \"plain\" ? Math.log(n / count) : Math.log((n + 1) / (count + 1)) + 1]));\n}\n\n/**\n * This function gives the TF-IDF vector of a list of words, with a length of 1.\n *\n * - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.\n * - A term with a weight of 0, or with no IDF, is not in the vector.\n * - A list with no term of weight above 0 gives an empty vector.\n *\n * @param words - The words of a document or of a query.\n * @param idf - The IDF of each term, from `inverseDocumentFrequency`.\n * @returns The weight of each term, divided by the Euclidean length of the vector.\n */\nexport function termVector(words: readonly string[], idf: ReadonlyMap<string, number>): Map<string, number> {\n const tf = new Map<string, number>();\n for (const word of words) tf.set(word, (tf.get(word) ?? 0) + 1);\n const vector = new Map<string, number>();\n let norm = 0;\n for (const [term, count] of tf) {\n const weight = (1 + Math.log(count)) * (idf.get(term) ?? 0);\n if (weight > 0) {\n vector.set(term, weight);\n norm += weight * weight;\n }\n }\n norm = Math.sqrt(norm);\n if (norm > 0) for (const [term, weight] of vector) vector.set(term, weight / norm);\n return vector;\n}\n\n/**\n * This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the\n * sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.\n * The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The similarity, from 0 to 1.\n */\nexport function cosineSimilarity(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): number {\n const [small, large] = a.size < b.size ? [a, b] : [b, a];\n let sum = 0;\n for (const [term, weight] of small) sum += weight * (large.get(term) ?? 0);\n return Math.min(1, Math.max(0, sum));\n}\n\n/** The score of one document of a corpus for a query. */\nexport interface DocumentScore {\n /** The position of the document in the corpus. */\n readonly index: number;\n /** The cosine similarity of the TF-IDF vectors of the document and of the query. */\n readonly score: number;\n}\n\n/**\n * This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.\n *\n * - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.\n * - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.\n * - The score of a document does not change when the order of the other documents changes.\n *\n * @param corpus - The documents, each as a list of words.\n * @param query - The words of the query.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The score of each document, best first.\n */\nexport function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form: IdfForm = \"plain\"): DocumentScore[] {\n const idf = inverseDocumentFrequency(corpus, form);\n const q = termVector(query, idf);\n return corpus.map((document, index) => ({ index, score: cosineSimilarity(q, termVector(document, idf)) })).sort((a, b) => b.score - a.score);\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F;;AAaA,IAAI;;;;;;;;;;;;;;AAeJ,SAAgB,YAAY,MAAc,UAAuB,CAAC,GAAa;CAC7E,MAAM,MAAgB,CAAC;CACvB,kBAAkB,IAAI,KAAK,UAAU,MAAM,EAAE,aAAa,OAAO,CAAC;CAClE,KAAK,MAAM,WAAW,cAAc,QAAQ,UAAU,IAAI,CAAC,GAAG;EAC5D,IAAI,CAAC,QAAQ,YAAY;EACzB,MAAM,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G,MAAM,CAAC,OAAO,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;CACvD,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,OAAO,UAAU,MAAM,IAAI,IAAI,KAAK;CACxE,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,GAAG,CAAC;AACrC;;;;;;;;;;;;;AAsBA,SAAgB,cAAc,QAAwC,OAA0B,OAAgB,SAA0B;CACxI,MAAM,MAAM,yBAAyB,QAAQ,IAAI;CACjD,MAAM,IAAI,WAAW,OAAO,GAAG;CAC/B,OAAO,OAAO,KAAK,UAAU,WAAW;EAAE;EAAO,OAAO,iBAAiB,GAAG,WAAW,UAAU,GAAG,CAAC;CAAE,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC7I"}
|
|
1
|
+
{"version":3,"file":"search.js","names":[],"sources":["../src/search.ts"],"sourcesContent":["/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n *\n * The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.\n * `rankDocuments` puts the documents of a corpus in order for a query. `rankerOf` does this for many queries on one corpus.\n * Each function has no I/O.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n\n/** The options of `searchWords`. Each option is a rule of the caller, for example a list of stop words of a language. */\nexport interface WordOptions {\n /** The words that do not go in, as search keys. */\n readonly stop?: ReadonlySet<string>;\n /** The test of a word after the stop words. A word goes in only when the test gives true. */\n readonly keep?: (word: string) => boolean;\n /** The change of a word that goes in, for example a cut of a plural ending. */\n readonly stem?: (word: string) => string;\n}\n\n/** The word segmenter of `searchWords`. A segmenter is costly to make, so the module makes it one time, at the first use. */\nlet wordSegmenter: Intl.Segmenter | undefined;\n\n/**\n * This function gives the words of a text, in their order, for a ranked search. The function does these steps:\n *\n * 1. It makes the search key of the text with `searchKey`.\n * 2. It divides the key into word segments with `Intl.Segmenter` (Unicode Standard Annex 29). It keeps only the segments\n * that are words or numbers, not spaces or punctuation.\n * 3. It removes each word of `options.stop`, then each word that `options.keep` refuses.\n * 4. It applies `options.stem` to each word that stays.\n *\n * @param text - The plain text.\n * @param options - The rules of the caller. With no options, each word goes in with no change.\n * @returns The words of the text.\n */\nexport function searchWords(text: string, options: WordOptions = {}): string[] {\n const out: string[] = [];\n wordSegmenter ??= new Intl.Segmenter(\"en\", { granularity: \"word\" });\n for (const segment of wordSegmenter.segment(searchKey(text))) {\n if (!segment.isWordLike) continue;\n const word = segment.segment;\n if (options.stop?.has(word) || (options.keep && !options.keep(word))) continue;\n out.push(options.stem ? options.stem(word) : word);\n }\n return out;\n}\n\n/**\n * The two forms of the inverse document frequency (IDF) of a term. N is the count of documents, and df is the count of\n * the documents that have the term.\n *\n * - `plain` is ln(N / df). A term in each document has the weight 0, so it does not change a rank.\n * - `smooth` is ln((N + 1) / (df + 1)) + 1, as scikit-learn computes it. Each term has a weight of 1 or more.\n */\nexport type IdfForm = \"plain\" | \"smooth\";\n\n/**\n * This function gives the inverse document frequency of each term of a corpus. A document is a list of words, for\n * example from `searchWords`. A term counts one time in each document that has it.\n *\n * The weight of a term depends only on N and on its df. Thus the order of the documents does not change a weight.\n *\n * @param documents - The corpus.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The IDF of each term of the corpus.\n */\nexport function inverseDocumentFrequency(documents: readonly (readonly string[])[], form: IdfForm = \"plain\"): Map<string, number> {\n const df = new Map<string, number>();\n for (const document of documents) for (const term of new Set(document)) df.set(term, (df.get(term) ?? 0) + 1);\n const n = documents.length;\n return new Map([...df].map(([term, count]) => [term, form === \"plain\" ? Math.log(n / count) : Math.log((n + 1) / (count + 1)) + 1]));\n}\n\n/**\n * This function gives the TF-IDF vector of a list of words, with a length of 1.\n *\n * - The weight of a term is (1 + ln(tf)) × idf, where tf is the count of the term in the list.\n * - A term with a weight of 0, or with no IDF, is not in the vector.\n * - A list with no term of weight above 0 gives an empty vector.\n *\n * @param words - The words of a document or of a query.\n * @param idf - The IDF of each term, from `inverseDocumentFrequency`.\n * @returns The weight of each term, divided by the Euclidean length of the vector.\n */\nexport function termVector(words: readonly string[], idf: ReadonlyMap<string, number>): Map<string, number> {\n const tf = new Map<string, number>();\n for (const word of words) tf.set(word, (tf.get(word) ?? 0) + 1);\n const vector = new Map<string, number>();\n let norm = 0;\n for (const [term, count] of tf) {\n const weight = (1 + Math.log(count)) * (idf.get(term) ?? 0);\n if (weight > 0) {\n vector.set(term, weight);\n norm += weight * weight;\n }\n }\n norm = Math.sqrt(norm);\n if (norm > 0) for (const [term, weight] of vector) vector.set(term, weight / norm);\n return vector;\n}\n\n/**\n * This function gives the cosine similarity of two vectors with a length of 1, from `termVector`. The similarity is the\n * sum of the products of the weights of each term in the two vectors. It is 0 when the vectors have no term in common.\n * The function clamps the sum to 0 to 1. Thus a vector with itself gives exactly 1, and not 1 plus a rounding error.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The similarity, from 0 to 1.\n */\nexport function cosineSimilarity(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): number {\n const [small, large] = a.size < b.size ? [a, b] : [b, a];\n let sum = 0;\n for (const [term, weight] of small) sum += weight * (large.get(term) ?? 0);\n return Math.min(1, Math.max(0, sum));\n}\n\n/** The score of one document of a corpus for a query. */\nexport interface DocumentScore {\n /** The position of the document in the corpus. */\n readonly index: number;\n /** The cosine similarity of the TF-IDF vectors of the document and of the query. */\n readonly score: number;\n}\n\n/**\n * This function ranks the documents of a corpus for a query with TF-IDF and the cosine similarity. It has no I/O.\n *\n * - The IDF comes from the corpus only. A term of the query that is not in the corpus has no weight.\n * - The result has one score for each document, from the best to the worst. A tie keeps the order of the corpus.\n * - The score of a document does not change when the order of the other documents changes.\n *\n * @param corpus - The documents, each as a list of words.\n * @param query - The words of the query.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns The score of each document, best first.\n */\nexport function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form: IdfForm = \"plain\"): DocumentScore[] {\n return rankerOf(corpus, form)(query);\n}\n\n/**\n * This function makes a ranker for one corpus. It computes the IDF and the vector of each document one time. It has no I/O.\n *\n * - For each query, the ranker gives the same scores as `rankDocuments(corpus, query, form)`.\n * - A query costs one vector and one cosine for each document. Use the ranker when many queries search one corpus.\n * - The ranker keeps the vectors of the corpus at the time of the call. A later change of the corpus does not change it.\n *\n * @param corpus - The documents, each as a list of words.\n * @param form - The form of the IDF. The default is `plain`.\n * @returns A function that gives the score of each document for a query, best first.\n */\nexport function rankerOf(corpus: readonly (readonly string[])[], form: IdfForm = \"plain\"): (query: readonly string[]) => DocumentScore[] {\n const idf = inverseDocumentFrequency(corpus, form);\n const vectors = corpus.map((document) => termVector(document, idf));\n return (query) => {\n const q = termVector(query, idf);\n return vectors.map((vector, index) => ({ index, score: cosineSimilarity(q, vector) })).sort((a, b) => b.score - a.score);\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F;;AAaA,IAAI;;;;;;;;;;;;;;AAeJ,SAAgB,YAAY,MAAc,UAAuB,CAAC,GAAa;CAC7E,MAAM,MAAgB,CAAC;CACvB,kBAAkB,IAAI,KAAK,UAAU,MAAM,EAAE,aAAa,OAAO,CAAC;CAClE,KAAK,MAAM,WAAW,cAAc,QAAQ,UAAU,IAAI,CAAC,GAAG;EAC5D,IAAI,CAAC,QAAQ,YAAY;EACzB,MAAM,OAAO,QAAQ;EACrB,IAAI,QAAQ,MAAM,IAAI,IAAI,KAAM,QAAQ,QAAQ,CAAC,QAAQ,KAAK,IAAI,GAAI;EACtE,IAAI,KAAK,QAAQ,OAAO,QAAQ,KAAK,IAAI,IAAI,IAAI;CACnD;CACA,OAAO;AACT;;;;;;;;;;;A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KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,GAAG,CAAC;AACrC;;;;;;;;;;;;;AAsBA,SAAgB,cAAc,QAAwC,OAA0B,OAAgB,SAA0B;CACxI,OAAO,SAAS,QAAQ,IAAI,CAAC,CAAC,KAAK;AACrC;;;;;;;;;;;;AAaA,SAAgB,SAAS,QAAwC,OAAgB,SAAwD;CACvI,MAAM,MAAM,yBAAyB,QAAQ,IAAI;CACjD,MAAM,UAAU,OAAO,KAAK,aAAa,WAAW,UAAU,GAAG,CAAC;CAClE,QAAQ,UAAU;EAChB,MAAM,IAAI,WAAW,OAAO,GAAG;EAC/B,OAAO,QAAQ,KAAK,QAAQ,WAAW;GAAE;GAAO,OAAO,iBAAiB,GAAG,MAAM;EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;CACzH;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.15",
|
|
5
5
|
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens and of secrets by their context (findSecretShapes, redactSecretShapes, findSecretShapesInValue, CONTEXT_SHAPES, isSecretName), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), and a scan of HTML for its text and its start tags (scanHtml).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
package/src/search.ts
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* in any order. The case of the letters is not significant.
|
|
4
4
|
*
|
|
5
5
|
* The module also has a ranked search: the words of a text (`searchWords`), TF-IDF weights and the cosine similarity.
|
|
6
|
-
* `rankDocuments` puts the documents of a corpus in order for a query.
|
|
6
|
+
* `rankDocuments` puts the documents of a corpus in order for a query. `rankerOf` does this for many queries on one corpus.
|
|
7
|
+
* Each function has no I/O.
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
10
|
/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */
|
|
@@ -175,7 +176,25 @@ export interface DocumentScore {
|
|
|
175
176
|
* @returns The score of each document, best first.
|
|
176
177
|
*/
|
|
177
178
|
export function rankDocuments(corpus: readonly (readonly string[])[], query: readonly string[], form: IdfForm = "plain"): DocumentScore[] {
|
|
179
|
+
return rankerOf(corpus, form)(query);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* This function makes a ranker for one corpus. It computes the IDF and the vector of each document one time. It has no I/O.
|
|
184
|
+
*
|
|
185
|
+
* - For each query, the ranker gives the same scores as `rankDocuments(corpus, query, form)`.
|
|
186
|
+
* - A query costs one vector and one cosine for each document. Use the ranker when many queries search one corpus.
|
|
187
|
+
* - The ranker keeps the vectors of the corpus at the time of the call. A later change of the corpus does not change it.
|
|
188
|
+
*
|
|
189
|
+
* @param corpus - The documents, each as a list of words.
|
|
190
|
+
* @param form - The form of the IDF. The default is `plain`.
|
|
191
|
+
* @returns A function that gives the score of each document for a query, best first.
|
|
192
|
+
*/
|
|
193
|
+
export function rankerOf(corpus: readonly (readonly string[])[], form: IdfForm = "plain"): (query: readonly string[]) => DocumentScore[] {
|
|
178
194
|
const idf = inverseDocumentFrequency(corpus, form);
|
|
179
|
-
const
|
|
180
|
-
return
|
|
195
|
+
const vectors = corpus.map((document) => termVector(document, idf));
|
|
196
|
+
return (query) => {
|
|
197
|
+
const q = termVector(query, idf);
|
|
198
|
+
return vectors.map((vector, index) => ({ index, score: cosineSimilarity(q, vector) })).sort((a, b) => b.score - a.score);
|
|
199
|
+
};
|
|
181
200
|
}
|