辞書管理
OPFS からの辞書読み込み
WASM で辞書を使用する推奨方法は、GitHub Releases からダウンロードし、OPFS 経由で読み込むことです。これにより、WASM バイナリに大きな辞書を埋め込む必要がなくなります。
バイトデータからの読み込み
OPFS やその他のブラウザストレージに保存された辞書を loadDictionaryFromBytes() で読み込みます。
loadDictionaryFromBytes(metadata, dictTrie, dictValsIdx, dictVals, dictWordsIdx, dictWords, matrixMtx, charDef, unk)
- パラメータ:
metadata(Uint8Array) --metadata.jsonの内容dictTrie(Uint8Array) --dict.trieの内容(文字単位のダブル配列トライ)dictValsIdx(Uint8Array) --dict.valsidxの内容(単語値インデックス)dictVals(Uint8Array) --dict.valsの内容(単語値データ)dictWordsIdx(Uint8Array) --dict.wordsidxの内容(単語詳細インデックス)dictWords(Uint8Array) --dict.wordsの内容(単語詳細)matrixMtx(Uint8Array) --matrix.mtxの内容(連接コスト行列)charDef(Uint8Array) --char_def.binの内容(文字定義)unk(Uint8Array) --unk.binの内容(未知語辞書)
- 戻り値:
Dictionary
import { loadDictionaryFromBytes, TokenizerBuilder } from 'lindera-wasm';
import { loadDictionaryFiles } from 'lindera-wasm/opfs';
// OPFS から辞書ファイルを読み込む
const files = await loadDictionaryFiles("ipadic");
// バイトデータから Dictionary を作成
const dictionary = loadDictionaryFromBytes(
files.metadata,
files.dictTrie,
files.dictValsIdx,
files.dictVals,
files.dictWordsIdx,
files.dictWords,
files.matrixMtx,
files.charDef,
files.unk,
);
// TokenizerBuilder で使用
const builder = new TokenizerBuilder();
builder.setDictionaryInstance(dictionary);
builder.setMode("normal");
const tokenizer = builder.build();
ダウンロードとキャッシュを含む完全なワークフローは OPFS 辞書ストレージ を参照してください。
埋め込み辞書(上級者向け)
embed-* feature フラグ付きでビルドした場合、embedded:// URI スキームで埋め込み辞書を読み込めます。WASM バイナリのサイズが大幅に増加します。
[!NOTE] 以下の例の
lindera-wasm-ipadicはembed-ipadicfeature でローカルビルドした場合の説明用パッケージ名であり、npm に公開されているものではありません。実際に公開されているのはlindera-wasmのみです。詳細は npm パッケージの命名規則 を参照してください。
埋め込み辞書の読み込み
import { loadDictionary } from 'lindera-wasm-ipadic';
const dictionary = loadDictionary("embedded://ipadic");
利用可能な埋め込み辞書の URI(ビルド時に有効にした feature に依存):
| URI | Feature フラグ |
|---|---|
embedded://ipadic | embed-ipadic |
embedded://unidic | embed-unidic |
embedded://ko-dic | embed-ko-dic |
embedded://cc-cedict | embed-cc-cedict |
embedded://jieba | embed-jieba |
TokenizerBuilder での使用
const builder = new TokenizerBuilder();
builder.setDictionary("embedded://ipadic");
builder.setMode("normal");
const tokenizer = builder.build();
Tokenizer コンストラクタでの使用
import { loadDictionary, Tokenizer } from 'lindera-wasm-ipadic';
const dictionary = loadDictionary("embedded://ipadic");
const tokenizer = new Tokenizer(dictionary, "normal");
Dictionary クラス
Dictionary クラスは、読み込み済みの形態素解析辞書を表します。
プロパティ
| プロパティ | 型 | 説明 |
|---|---|---|
name | string | 辞書名(例: "ipadic") |
encoding | string | 辞書の文字エンコーディング |
metadata | Metadata | 完全なメタデータオブジェクト |
console.log(dictionary.name); // "ipadic"
console.log(dictionary.encoding); // "utf-8"
ユーザー辞書
ユーザー辞書を使用すると、システム辞書にないカスタム語彙を追加できます。
WebAssembly にはファイルシステムが無いため、ユーザー辞書は JavaScript 側で
取得したバイト列(fetch・<input type="file">・OPFS)から読み込みます。
CSV バイト列からのユーザー辞書の読み込み
ユーザー辞書を組み合わせるシステム辞書のメタデータ(例:
dictionary.metadata)を渡してください。CSV の内容は UTF-8 である必要が
あります。
import { loadUserDictionaryFromBytes } from 'lindera-wasm';
const response = await fetch('/dictionaries/user_dict.csv');
const csvBytes = new Uint8Array(await response.arrayBuffer());
const userDict = loadUserDictionaryFromBytes(csvBytes, dictionary.metadata);
OPFS 上のファイルも同じ形で使えます:
const root = await navigator.storage.getDirectory();
const handle = await root.getFileHandle('user_dict.csv');
const csvBytes = new Uint8Array(await (await handle.getFile()).arrayBuffer());
const userDict = loadUserDictionaryFromBytes(csvBytes, dictionary.metadata);
ビルド済みユーザー辞書(.bin)の読み込み
lindera build --user でコンパイルしたユーザー辞書はそのまま読み込めます:
import { loadUserDictionaryBinFromBytes } from 'lindera-wasm';
const response = await fetch('/dictionaries/user_dict.bin');
const binBytes = new Uint8Array(await response.arrayBuffer());
const userDict = loadUserDictionaryBinFromBytes(binBytes);
Tokenizer でのユーザー辞書の使用
import { loadDictionaryFromBytes, loadUserDictionaryFromBytes, Tokenizer } from 'lindera-wasm';
import { loadDictionaryFiles } from 'lindera-wasm/opfs';
const files = await loadDictionaryFiles("ipadic");
const dictionary = loadDictionaryFromBytes(
files.metadata, files.dictTrie, files.dictValsIdx, files.dictVals,
files.dictWordsIdx, files.dictWords, files.matrixMtx, files.charDef,
files.unk,
);
const response = await fetch('/dictionaries/user_dict.csv');
const csvBytes = new Uint8Array(await response.arrayBuffer());
const userDict = loadUserDictionaryFromBytes(csvBytes, dictionary.metadata);
const tokenizer = new Tokenizer(dictionary, "normal", userDict);
ユーザー辞書の CSV フォーマット
ユーザー辞書の CSV は Lindera ユーザー辞書と同じフォーマットに準拠します。 IPADIC のシンプル形式は以下のとおりです:
東京スカイツリー,カスタム名詞,トウキョウスカイツリー
東武スカイツリーライン,カスタム名詞,トウブスカイツリーライン
各行の構成: surface,part_of_speech,reading。辞書のフル形式
(IPADIC では 13 フィールド以上)の行も併用できます。内容は UTF-8 で
ある必要があります。
辞書のビルド
WebAssembly では辞書のビルドはできません。ビルドはソースディレクトリを
読み出力ディレクトリへ書き込みますが、wasm32-unknown-unknown には
ファイルシステムが無いためです。辞書は lindera CLI(またはネイティブ
バインディング)でビルドし、結果をバイト列としてここに読み込んでください。
ビルド済み辞書のダウンロードは OPFS 辞書管理 を参照してください。
Metadata
Metadata クラスは辞書のパラメータを設定します。
コンストラクタ
const metadata = new Metadata(name?, encoding?);
- パラメータ:
name(string, 省略可) -- 辞書名(デフォルト:"default")encoding(string, 省略可) -- 文字エンコーディング(デフォルト:"UTF-8")
静的メソッド
Metadata.createDefault()
デフォルト値で Metadata インスタンスを作成します。
const metadata = Metadata.createDefault();
Metadata プロパティ
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
name | string | "default" | 辞書名 |
encoding | string | "UTF-8" | 文字エンコーディング |
dictionary_schema | Schema | IPADIC スキーマ | メイン辞書のスキーマ |
user_dictionary_schema | Schema | 最小スキーマ | ユーザー辞書のスキーマ |
すべてのプロパティは取得と設定の両方に対応しています:
const metadata = Metadata.createDefault();
metadata.name = "custom_dict";
metadata.encoding = "EUC-JP";
console.log(metadata.name); // "custom_dict"
[!NOTE] Python・Node.js・Ruby・PHP の各バインディングと異なり、WASM の
Metadataクラスはdefault_word_cost、default_left_context_id、default_right_context_id、default_field_value、flexible_csv、skip_invalid_cost_or_id、normalize_detailsを取得・設定可能なプロパティとして公開していません(lindera-wasm/src/metadata.rs参照)。これらは常にバインディング共通のデフォルト値(コスト-10000、文脈 ID1288、フィールド値"*"、フラグはすべてfalse)にフォールバックし、JavaScript から変更することはできません。
読み込み済み辞書のメタデータには dictionary.metadata からアクセスできます。
Schema
Schema クラスは辞書エントリのフィールド構造を定義します。
Schema コンストラクタ
const schema = new Schema(["surface", "left_id", "right_id", "cost", "pos", "reading"]);
Schema 静的メソッド
Schema.create_default()-- IPADIC のレイアウトを緩やかに踏襲した組み込みの 13 フィールドスキーマを作成する。内訳は 4 つのシステムフィールド(surface、left_context_id、right_context_id、cost)に続く 9 つの汎用素性フィールド(major_pos、pos_detail_1〜pos_detail_3、conjugation_type、conjugation_form、base_form、reading、pronunciation)。これらのフィールド名(およびconjugation_type/conjugation_formの順序)は、実際のlindera-ipadic辞書スキーマ(part_of_speech、part_of_speech_subcategory_1〜_3、conjugation_form、conjugation_type、...)とは異なる。実際の IPADIC 辞書のスキーマに合わせたい場合は、読み込み済み辞書のdictionary.metadata.dictionary_schemaを使用すること
Schema メソッド
| メソッド | 戻り値 | 説明 |
|---|---|---|
get_field_index(name) | number | undefined | フィールド名からインデックスを取得 |
field_count() | number | フィールドの総数 |
get_field_name(index) | string | undefined | インデックスからフィールド名を取得 |
get_custom_fields() | string[] | インデックス 3 以降のフィールド(形態素素性) |
get_all_fields() | string[] | すべてのフィールド名 |
get_field_by_name(name) | FieldDefinition | undefined | フィールド定義の完全な情報を取得 |
FieldDefinition
| プロパティ | 型 | 説明 |
|---|---|---|
index | number | フィールドの位置インデックス |
name | string | フィールド名 |
field_type | FieldType | フィールド型の列挙値 |
description | string | undefined | 説明(省略可) |
FieldType
| 値 | 説明 |
|---|---|
FieldType.Surface | 単語の表層形テキスト |
FieldType.LeftContextId | 左文脈 ID |
FieldType.RightContextId | 右文脈 ID |
FieldType.Cost | 単語コスト |
FieldType.Custom | 形態素素性フィールド |