lindera 6.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.
Files changed (4) hide show
  1. package/README.md +345 -0
  2. package/index.d.ts +606 -0
  3. package/index.js +723 -0
  4. package/package.json +70 -0
package/README.md ADDED
@@ -0,0 +1,345 @@
1
+ # lindera-nodejs
2
+
3
+ Node.js binding for [Lindera](https://github.com/lindera/lindera), a Japanese morphological analysis engine.
4
+
5
+ ## Overview
6
+
7
+ lindera-nodejs provides a comprehensive Node.js interface to the Lindera morphological analysis engine, supporting Japanese, Korean, and Chinese text analysis. This implementation includes all major features:
8
+
9
+ - **Multi-language Support**: Japanese (IPADIC, IPADIC-NEologd, UniDic), Korean (ko-dic), Chinese (CC-CEDICT, Jieba)
10
+ - **Character Filters**: Text preprocessing with mapping, regex, Unicode normalization, and Japanese iteration mark handling
11
+ - **Token Filters**: Post-processing filters including lowercase, length filtering, stop words, and Japanese-specific filters
12
+ - **Flexible Configuration**: Configurable tokenization modes and penalty settings
13
+ - **Metadata Support**: Complete dictionary schema and metadata management
14
+ - **TypeScript Support**: Full type definitions included out of the box
15
+
16
+ ## Features
17
+
18
+ ### Core Components
19
+
20
+ - **TokenizerBuilder**: Fluent API for building customized tokenizers
21
+ - **Tokenizer**: High-performance text tokenization with integrated filtering
22
+ - **CharacterFilter**: Pre-processing filters for text normalization
23
+ - **TokenFilter**: Post-processing filters for token refinement
24
+ - **Metadata & Schema**: Dictionary structure and configuration management
25
+ - **Training & Export** (optional): Train custom morphological analysis models from corpus data
26
+
27
+ ### Supported Dictionaries
28
+
29
+ - **Japanese**: IPADIC, IPADIC-NEologd, UniDic
30
+ - **Korean**: ko-dic
31
+ - **Chinese**: CC-CEDICT, Jieba
32
+ - **Custom**: User dictionary support
33
+
34
+ Pre-built dictionaries are available from [GitHub Releases](https://github.com/lindera/lindera/releases).
35
+ Download a dictionary archive (e.g. `lindera-ipadic-*.zip`) and specify the extracted path when loading.
36
+
37
+ ### Filter Types
38
+
39
+ **Character Filters:**
40
+
41
+ - Mapping filter (character replacement)
42
+ - Regex filter (pattern-based replacement)
43
+ - Unicode normalization (NFKC, etc.)
44
+ - Japanese iteration mark normalization
45
+
46
+ **Token Filters:**
47
+
48
+ - Text case transformation (lowercase, uppercase)
49
+ - Length filtering (min/max character length)
50
+ - Stop words filtering
51
+ - Japanese-specific filters (base form, reading form, etc.)
52
+ - Korean-specific filters
53
+
54
+ ## Install project dependencies
55
+
56
+ - Node.js `^20.17.0 || ^22.13.0 || >= 23.5.0` : <https://nodejs.org/>
57
+ - Rust : <https://www.rust-lang.org/tools/install>
58
+ - @napi-rs/cli : `npm install -g @napi-rs/cli`
59
+
60
+ ## Setup repository
61
+
62
+ ```shell
63
+ # Clone lindera project repository
64
+ git clone git@github.com:lindera/lindera.git
65
+ cd lindera
66
+ ```
67
+
68
+ ## Install lindera-nodejs
69
+
70
+ This command builds the library with development settings (debug build).
71
+
72
+ ```shell
73
+ cd lindera-nodejs
74
+ npm install
75
+ npm run build
76
+ ```
77
+
78
+ ## Quick Start
79
+
80
+ The examples below use CommonJS. The package is also importable from ESM — the
81
+ same named exports are available:
82
+
83
+ ```javascript
84
+ import { loadDictionary, Tokenizer } from "lindera";
85
+ ```
86
+
87
+ ### Basic Tokenization
88
+
89
+ ```javascript
90
+ const { loadDictionary, Tokenizer } = require("lindera");
91
+
92
+ // Load dictionary
93
+ // Load dictionary from a local path (download from GitHub Releases)
94
+ const dictionary = loadDictionary("/path/to/ipadic");
95
+
96
+ // Create a tokenizer
97
+ const tokenizer = new Tokenizer(dictionary, "normal");
98
+
99
+ // Tokenize Japanese text
100
+ const text = "すもももももももものうち";
101
+ const tokens = tokenizer.tokenize(text);
102
+
103
+ for (const token of tokens) {
104
+ console.log(`Text: ${token.surface}, Position: ${token.byteStart}-${token.byteEnd}`);
105
+ }
106
+ ```
107
+
108
+ ### Tokens Are Plain Objects
109
+
110
+ `tokenize` and `tokenizeNbest` return plain JavaScript objects, not class
111
+ instances. This keeps memory predictable in large synchronous batches: a napi
112
+ class instance frees its native memory through a finalizer that napi defers to
113
+ the event loop, so a loop that never yields accumulates native memory even
114
+ under forced GC, whereas plain objects are reclaimed by ordinary GC
115
+ ([#930](https://github.com/lindera/lindera/issues/930)).
116
+
117
+ They also serialize without conversion:
118
+
119
+ ```javascript
120
+ const tokens = tokenizer.tokenize(text);
121
+
122
+ JSON.stringify(tokens); // works as-is
123
+ structuredClone(tokens); // safe to send to a worker
124
+ ```
125
+
126
+ Read a single detail by indexing the array — `token.details[0]` — which
127
+ replaces the `token.getDetail(0)` method that existed while tokens were class
128
+ instances (out-of-range reads now yield `undefined` rather than `null`).
129
+
130
+ ### Using Character Filters
131
+
132
+ ```javascript
133
+ const { TokenizerBuilder } = require("lindera");
134
+
135
+ // Create tokenizer builder
136
+ const builder = new TokenizerBuilder();
137
+ builder.setMode("normal");
138
+ builder.setDictionary("/path/to/ipadic");
139
+
140
+ // Add character filters
141
+ builder.appendCharacterFilter("mapping", { mapping: { "ー": "-" } });
142
+ builder.appendCharacterFilter("unicode_normalize", { kind: "nfkc" });
143
+
144
+ // Build tokenizer with filters
145
+ const tokenizer = builder.build();
146
+ const text = "テストー123";
147
+ const tokens = tokenizer.tokenize(text); // Will apply filters automatically
148
+ ```
149
+
150
+ ### Using Token Filters
151
+
152
+ ```javascript
153
+ const { TokenizerBuilder } = require("lindera");
154
+
155
+ // Create tokenizer builder
156
+ const builder = new TokenizerBuilder();
157
+ builder.setMode("normal");
158
+ builder.setDictionary("/path/to/ipadic");
159
+
160
+ // Add token filters
161
+ builder.appendTokenFilter("lowercase");
162
+ builder.appendTokenFilter("length", { min: 2, max: 10 });
163
+ builder.appendTokenFilter("japanese_stop_tags", {
164
+ tags: ["助詞,格助詞,一般", "助詞,係助詞", "助詞,連体化", "助動詞"],
165
+ });
166
+
167
+ // Build tokenizer with filters
168
+ const tokenizer = builder.build();
169
+ const tokens = tokenizer.tokenize("テキストの解析");
170
+ ```
171
+
172
+ ### Integrated Pipeline
173
+
174
+ ```javascript
175
+ const { TokenizerBuilder } = require("lindera");
176
+
177
+ // Build tokenizer with integrated filters
178
+ const builder = new TokenizerBuilder();
179
+ builder.setMode("normal");
180
+ builder.setDictionary("/path/to/ipadic");
181
+
182
+ // Add character filters
183
+ builder.appendCharacterFilter("mapping", { mapping: { "ー": "-" } });
184
+ builder.appendCharacterFilter("unicode_normalize", { kind: "nfkc" });
185
+
186
+ // Add token filters
187
+ builder.appendTokenFilter("lowercase");
188
+ builder.appendTokenFilter("japanese_base_form");
189
+
190
+ // Build and use
191
+ const tokenizer = builder.build();
192
+ const tokens = tokenizer.tokenize("コーヒーショップ");
193
+ ```
194
+
195
+ ### Working with Metadata
196
+
197
+ ```javascript
198
+ const { Metadata } = require("lindera");
199
+
200
+ // Create metadata with default values
201
+ const metadata = new Metadata();
202
+ console.log(`Name: ${metadata.name}`);
203
+ console.log(`Encoding: ${metadata.encoding}`);
204
+
205
+ // Create metadata from a JSON file
206
+ const loaded = Metadata.fromJsonFile("metadata.json");
207
+ console.log(loaded.toObject());
208
+ ```
209
+
210
+ ## Advanced Usage
211
+
212
+ ### Filter Configuration Examples
213
+
214
+ Character filters and token filters accept configuration as object arguments:
215
+
216
+ ```javascript
217
+ const { TokenizerBuilder } = require("lindera");
218
+
219
+ const builder = new TokenizerBuilder();
220
+ builder.setDictionary("/path/to/ipadic");
221
+
222
+ // Character filters with object configuration
223
+ builder.appendCharacterFilter("unicode_normalize", { kind: "nfkc" });
224
+ builder.appendCharacterFilter("japanese_iteration_mark", {
225
+ normalize_kanji: true,
226
+ normalize_kana: true,
227
+ });
228
+ builder.appendCharacterFilter("mapping", {
229
+ mapping: { "リンデラ": "lindera", "トウキョウ": "東京" },
230
+ });
231
+
232
+ // Token filters with object configuration
233
+ builder.appendTokenFilter("japanese_katakana_stem", { min: 3 });
234
+ builder.appendTokenFilter("length", { min: 2, max: 10 });
235
+ builder.appendTokenFilter("japanese_stop_tags", {
236
+ tags: ["助詞,格助詞,一般", "助詞,係助詞", "助詞,連体化", "助動詞", "記号,句点", "記号,読点"],
237
+ });
238
+
239
+ // Filters without configuration can omit the object
240
+ builder.appendTokenFilter("lowercase");
241
+ builder.appendTokenFilter("japanese_base_form");
242
+
243
+ const tokenizer = builder.build();
244
+ ```
245
+
246
+ See `examples/` directory for comprehensive examples including:
247
+
248
+ - `tokenize.js`: Basic tokenization
249
+ - `tokenize_with_filters.js`: Using character and token filters
250
+ - `tokenize_with_userdict.js`: Custom user dictionary
251
+ - `train_and_export.js`: Train and export custom dictionaries (requires `train` feature)
252
+ - `tokenize_with_decompose.js`: Decompose mode tokenization
253
+
254
+ ## Dictionary Support
255
+
256
+ ### Japanese
257
+
258
+ - **IPADIC**: Default Japanese dictionary, good for general text
259
+ - **UniDic**: Academic dictionary with detailed morphological information
260
+
261
+ ### Korean
262
+
263
+ - **ko-dic**: Standard Korean dictionary for morphological analysis
264
+
265
+ ### Chinese
266
+
267
+ - **CC-CEDICT**: Community-maintained Chinese-English dictionary
268
+
269
+ ### Custom Dictionaries
270
+
271
+ - User dictionary support for domain-specific terms
272
+ - CSV format for easy customization
273
+
274
+ ## Dictionary Training (Experimental)
275
+
276
+ lindera-nodejs supports training custom morphological analysis models from annotated corpus data when built with the `train` feature.
277
+
278
+ ### Building with Training Support
279
+
280
+ ```shell
281
+ npm run build -- --features train
282
+ ```
283
+
284
+ ### Training a Model
285
+
286
+ ```javascript
287
+ const { train } = require("lindera");
288
+
289
+ // Train a model from corpus
290
+ train({
291
+ seed: "path/to/seed.csv",
292
+ corpus: "path/to/corpus.txt",
293
+ charDef: "path/to/char.def",
294
+ unkDef: "path/to/unk.def",
295
+ featureDef: "path/to/feature.def",
296
+ rewriteDef: "path/to/rewrite.def",
297
+ output: "model.dat",
298
+ lambda: 0.01,
299
+ maxIter: 100,
300
+ });
301
+ ```
302
+
303
+ ### Exporting Dictionary Files
304
+
305
+ ```javascript
306
+ const { exportModel } = require("lindera");
307
+
308
+ // Export trained model to dictionary files
309
+ exportModel({
310
+ model: "model.dat",
311
+ output: "exported_dict/",
312
+ metadata: "metadata.json",
313
+ });
314
+ ```
315
+
316
+ This will create:
317
+
318
+ - `lex.csv`: Lexicon file
319
+ - `matrix.def`: Connection cost matrix
320
+ - `unk.def`: Unknown word definitions
321
+ - `char.def`: Character definitions
322
+ - `metadata.json`: Dictionary metadata (if provided)
323
+
324
+ See `examples/train_and_export.js` for a complete example.
325
+
326
+ ## API Reference
327
+
328
+ ### Core Classes
329
+
330
+ - `TokenizerBuilder`: Fluent builder for tokenizer configuration
331
+ - `Tokenizer`: Main tokenization engine
332
+ - `Dictionary`: A loaded system dictionary
333
+ - `UserDictionary`: A loaded user dictionary
334
+ - `Metadata`: Dictionary metadata and configuration
335
+ - `Schema`: Dictionary schema definition
336
+
337
+ ### Core Types
338
+
339
+ - `Token`: A plain object with text, position, and linguistic features
340
+ - `NbestResult`: A plain object holding one N-best candidate (`tokens` and `cost`)
341
+
342
+ ### Training Functions (requires `train` feature)
343
+
344
+ - `train()`: Train a morphological analysis model from corpus
345
+ - `exportModel()`: Export trained model to dictionary files