1import { AutoModel, AutoTokenizer, matmul } from '@huggingface/transformers';
2
3const model = await AutoModel.from_pretrained(
4 "cfsdwe/static-embedding-japanese-for-js",
5 { dtype: "q8" } // or fp32
6 );
7const tokenizer = await AutoTokenizer.from_pretrained('cfsdwe/static-embedding-japanese-for-js');
8
9const sentences = [
10 "カレーはおいしい。",
11 "カレースープはそこそこ美味しい。",
12 "トマトジュースは好みが分かれる。",
13];
14
15// `Nmt` normalizerに相当する処理をtokenizerに渡す前に自前で追加
16function myNmtNormalizer(text) {
17 let normalizedText = text;
18 const controlCharsRegex =
19 /[\u{1}-\u{8}\u{B}\u{E}-\u{1F}\u{7F}\u{8F}\u{9F}]/gu;
20 normalizedText = normalizedText.replace(controlCharsRegex, "");
21
22 const mapToSpaceRegex =
23 /[\u{0009}\u{000A}\u{000C}\u{000D}\u{1680}\u{200B}-\u{200F}\u{2028}\u{2029}\u{2581}\u{FEFF}\u{FFFD}]/gu;
24 normalizedText = normalizedText.replace(mapToSpaceRegex, " ");
25
26 return normalizedText;
27}
28
29const sentences_normalized = sentences.map((s) => myNmtNormalizer(s))
30const inputs = tokenizer(sentences_normalized, { padding: true, truncation: true });
31const { sentence_embedding } = await model(inputs);
32
33const normalized = sentence_embedding.normalize();
34const scores = await matmul(normalized, normalized.transpose(1, 0));
35console.log(scores.tolist());
36// [
37// [1.0000001192092896, 0.7581136226654053, 0.25487640500068665]
38// [0.7581136226654053, 0.9999997019767761, 0.24671493470668793]
39// [0.25487640500068665, 0.24671493470668793, 0.9999983906745911],
40// ]