辞書管理

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-ipadicembed-ipadic feature でローカルビルドした場合の説明用パッケージ名であり、npm に公開されているものではありません。実際に公開されているのは lindera-wasm のみです。詳細は npm パッケージの命名規則 を参照してください。

埋め込み辞書の読み込み

import { loadDictionary } from 'lindera-wasm-ipadic';

const dictionary = loadDictionary("embedded://ipadic");

利用可能な埋め込み辞書の URI(ビルド時に有効にした feature に依存):

URIFeature フラグ
embedded://ipadicembed-ipadic
embedded://unidicembed-unidic
embedded://ko-dicembed-ko-dic
embedded://cc-cedictembed-cc-cedict
embedded://jiebaembed-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 クラスは、読み込み済みの形態素解析辞書を表します。

プロパティ

プロパティ説明
namestring辞書名(例: "ipadic"
encodingstring辞書の文字エンコーディング
metadataMetadata完全なメタデータオブジェクト
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 プロパティ

プロパティデフォルト説明
namestring"default"辞書名
encodingstring"UTF-8"文字エンコーディング
dictionary_schemaSchemaIPADIC スキーマメイン辞書のスキーマ
user_dictionary_schemaSchema最小スキーマユーザー辞書のスキーマ

すべてのプロパティは取得と設定の両方に対応しています:

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_costdefault_left_context_iddefault_right_context_iddefault_field_valueflexible_csvskip_invalid_cost_or_idnormalize_details を取得・設定可能なプロパティとして公開していません(lindera-wasm/src/metadata.rs 参照)。これらは常にバインディング共通のデフォルト値(コスト -10000、文脈 ID 1288、フィールド値 "*"、フラグはすべて 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 つのシステムフィールド(surfaceleft_context_idright_context_idcost)に続く 9 つの汎用素性フィールド(major_pospos_detail_1pos_detail_3conjugation_typeconjugation_formbase_formreadingpronunciation)。これらのフィールド名(および conjugation_type/conjugation_form の順序)は、実際の lindera-ipadic 辞書スキーマ(part_of_speechpart_of_speech_subcategory_1_3conjugation_formconjugation_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

プロパティ説明
indexnumberフィールドの位置インデックス
namestringフィールド名
field_typeFieldTypeフィールド型の列挙値
descriptionstring | undefined説明(省略可)

FieldType

説明
FieldType.Surface単語の表層形テキスト
FieldType.LeftContextId左文脈 ID
FieldType.RightContextId右文脈 ID
FieldType.Cost単語コスト
FieldType.Custom形態素素性フィールド