lindera 6.2.0

A morphological analysis library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use std::path::{Path, PathBuf};
use std::str::FromStr;

use percent_encoding::percent_decode_str;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use url::Url;

#[cfg(feature = "embed-cc-cedict")]
use lindera_cc_cedict::DICTIONARY_NAME as CC_CEDICT_DICTIONARY_NAME;
#[cfg(feature = "embed-cc-cedict")]
use lindera_cc_cedict::embedded::EmbeddedCcCedictLoader;
use lindera_dictionary::loader::DictionaryLoader;
use lindera_dictionary::loader::FSDictionaryLoader;
use lindera_dictionary::loader::user_dictionary::UserDictionaryLoader;
#[cfg(feature = "embed-ipadic")]
use lindera_ipadic::DICTIONARY_NAME as IPADIC_DICTIONARY_NAME;
#[cfg(feature = "embed-ipadic")]
use lindera_ipadic::embedded::EmbeddedIPADICLoader;
#[cfg(feature = "embed-ipadic-neologd")]
use lindera_ipadic_neologd::DICTIONARY_NAME as IPADIC_NEOLOGD_DICTIONARY_NAME;
#[cfg(feature = "embed-ipadic-neologd")]
use lindera_ipadic_neologd::embedded::EmbeddedIPADICNEologdLoader;
#[cfg(feature = "embed-jieba")]
use lindera_jieba::DICTIONARY_NAME as JIEBA_DICTIONARY_NAME;
#[cfg(feature = "embed-jieba")]
use lindera_jieba::embedded::EmbeddedJiebaLoader;
#[cfg(feature = "embed-ko-dic")]
use lindera_ko_dic::DICTIONARY_NAME as KO_DIC_DICTIONARY_NAME;
#[cfg(feature = "embed-ko-dic")]
use lindera_ko_dic::embedded::EmbeddedKoDicLoader;
#[cfg(feature = "embed-sudachidict")]
use lindera_sudachidict::DICTIONARY_NAME as SUDACHIDICT_DICTIONARY_NAME;
#[cfg(feature = "embed-sudachidict")]
use lindera_sudachidict::embedded::EmbeddedSudachiDictLoader;
#[cfg(feature = "train")]
#[cfg_attr(docsrs, doc(cfg(feature = "train")))]
pub use lindera_trainer as trainer;
#[cfg(feature = "embed-unidic")]
use lindera_unidic::DICTIONARY_NAME as UNIDIC_DICTIONARY_NAME;
#[cfg(feature = "embed-unidic")]
use lindera_unidic::embedded::EmbeddedUniDicLoader;

use crate::LinderaResult;
use crate::error::{LinderaError, LinderaErrorKind};

pub type Dictionary = lindera_dictionary::dictionary::Dictionary;
pub type Metadata = lindera_dictionary::dictionary::metadata::Metadata;
pub type UserDictionary = lindera_dictionary::dictionary::UserDictionary;
pub type Lattice = lindera_dictionary::viterbi::Lattice;
pub type WordId = lindera_dictionary::viterbi::WordId;
pub type DictionaryBuilder = lindera_dictionary::builder::DictionaryBuilder;
pub type DictionaryConfig = Value;
pub type UserDictionaryConfig = Value;
pub type Schema = lindera_dictionary::dictionary::schema::Schema;
pub type FieldDefinition = lindera_dictionary::dictionary::schema::FieldDefinition;
pub type FieldType = lindera_dictionary::dictionary::schema::FieldType;
#[derive(Debug, Clone, EnumIter, Deserialize, Serialize, PartialEq, Eq)]
pub enum DictionaryScheme {
    #[cfg(any(
        feature = "embed-ipadic",
        feature = "embed-ipadic-neologd",
        feature = "embed-unidic",
        feature = "embed-sudachidict",
        feature = "embed-ko-dic",
        feature = "embed-cc-cedict",
        feature = "embed-jieba",
    ))]
    #[serde(rename = "embedded")]
    Embedded,
    #[serde(rename = "file")]
    File,
}

impl DictionaryScheme {
    pub fn as_str(&self) -> &str {
        match self {
            #[cfg(any(
                feature = "embed-ipadic",
                feature = "embed-ipadic-neologd",
                feature = "embed-unidic",
                feature = "embed-sudachidict",
                feature = "embed-ko-dic",
                feature = "embed-cc-cedict",
                feature = "embed-jieba",
            ))]
            DictionaryScheme::Embedded => "embedded",
            DictionaryScheme::File => "file",
        }
    }
}

impl FromStr for DictionaryScheme {
    type Err = LinderaError;
    fn from_str(input: &str) -> Result<DictionaryScheme, Self::Err> {
        match input {
            #[cfg(any(
                feature = "embed-ipadic",
                feature = "embed-ipadic-neologd",
                feature = "embed-unidic",
                feature = "embed-sudachidict",
                feature = "embed-ko-dic",
                feature = "embed-cc-cedict",
                feature = "embed-jieba",
            ))]
            "embedded" => Ok(DictionaryScheme::Embedded),
            "file" => Ok(DictionaryScheme::File),
            _ => Err(LinderaErrorKind::Dictionary
                .with_error(anyhow::anyhow!("Invalid dictionary scheme: {input}"))),
        }
    }
}

#[derive(Debug, Clone, EnumIter, Deserialize, Serialize, PartialEq, Eq)]
pub enum DictionaryKind {
    #[cfg(feature = "embed-ipadic")]
    #[serde(rename = "ipadic")]
    IPADIC,
    #[cfg(feature = "embed-ipadic-neologd")]
    #[serde(rename = "ipadic-neologd")]
    IPADICNEologd,
    #[cfg(feature = "embed-unidic")]
    #[serde(rename = "unidic")]
    UniDic,
    #[cfg(feature = "embed-sudachidict")]
    #[serde(rename = "sudachidict")]
    SudachiDict,
    #[cfg(feature = "embed-ko-dic")]
    #[serde(rename = "ko-dic")]
    KoDic,
    #[cfg(feature = "embed-cc-cedict")]
    #[serde(rename = "cc-cedict")]
    CcCedict,
    #[cfg(feature = "embed-jieba")]
    #[serde(rename = "jieba")]
    Jieba,
}

impl DictionaryKind {
    pub fn variants() -> Vec<DictionaryKind> {
        DictionaryKind::iter().collect::<Vec<_>>()
    }

    pub fn contained_variants() -> Vec<DictionaryKind> {
        DictionaryKind::variants()
            .into_iter()
            .filter(|kind| match kind {
                #[cfg(feature = "embed-ipadic")]
                DictionaryKind::IPADIC => cfg!(feature = "embed-ipadic"),
                #[cfg(feature = "embed-ipadic-neologd")]
                DictionaryKind::IPADICNEologd => cfg!(feature = "embed-ipadic-neologd"),
                #[cfg(feature = "embed-unidic")]
                DictionaryKind::UniDic => cfg!(feature = "embed-unidic"),
                #[cfg(feature = "embed-sudachidict")]
                DictionaryKind::SudachiDict => cfg!(feature = "embed-sudachidict"),
                #[cfg(feature = "embed-ko-dic")]
                DictionaryKind::KoDic => cfg!(feature = "embed-ko-dic"),
                #[cfg(feature = "embed-cc-cedict")]
                DictionaryKind::CcCedict => cfg!(feature = "embed-cc-cedict"),
                #[cfg(feature = "embed-jieba")]
                DictionaryKind::Jieba => cfg!(feature = "embed-jieba"),
                #[allow(unreachable_patterns)]
                _ => false,
            })
            .collect::<Vec<_>>()
    }

    pub fn as_str(&self) -> &str {
        match self {
            #[cfg(feature = "embed-ipadic")]
            DictionaryKind::IPADIC => IPADIC_DICTIONARY_NAME,
            #[cfg(feature = "embed-ipadic-neologd")]
            DictionaryKind::IPADICNEologd => IPADIC_NEOLOGD_DICTIONARY_NAME,
            #[cfg(feature = "embed-unidic")]
            DictionaryKind::UniDic => UNIDIC_DICTIONARY_NAME,
            #[cfg(feature = "embed-sudachidict")]
            DictionaryKind::SudachiDict => SUDACHIDICT_DICTIONARY_NAME,
            #[cfg(feature = "embed-ko-dic")]
            DictionaryKind::KoDic => KO_DIC_DICTIONARY_NAME,
            #[cfg(feature = "embed-cc-cedict")]
            DictionaryKind::CcCedict => CC_CEDICT_DICTIONARY_NAME,
            #[cfg(feature = "embed-jieba")]
            DictionaryKind::Jieba => JIEBA_DICTIONARY_NAME,
            #[allow(unreachable_patterns)]
            _ => "",
        }
    }
}

impl FromStr for DictionaryKind {
    type Err = LinderaError;
    fn from_str(input: &str) -> Result<DictionaryKind, Self::Err> {
        // Use if-else chain instead of match because const &str values
        // are interpreted as variable bindings in match patterns.
        #[cfg(feature = "embed-ipadic")]
        if input == IPADIC_DICTIONARY_NAME {
            return Ok(DictionaryKind::IPADIC);
        }
        #[cfg(feature = "embed-ipadic-neologd")]
        if input == IPADIC_NEOLOGD_DICTIONARY_NAME {
            return Ok(DictionaryKind::IPADICNEologd);
        }
        #[cfg(feature = "embed-unidic")]
        if input == UNIDIC_DICTIONARY_NAME {
            return Ok(DictionaryKind::UniDic);
        }
        #[cfg(feature = "embed-sudachidict")]
        if input == SUDACHIDICT_DICTIONARY_NAME {
            return Ok(DictionaryKind::SudachiDict);
        }
        #[cfg(feature = "embed-ko-dic")]
        if input == KO_DIC_DICTIONARY_NAME {
            return Ok(DictionaryKind::KoDic);
        }
        #[cfg(feature = "embed-cc-cedict")]
        if input == CC_CEDICT_DICTIONARY_NAME {
            return Ok(DictionaryKind::CcCedict);
        }
        #[cfg(feature = "embed-jieba")]
        if input == JIEBA_DICTIONARY_NAME {
            return Ok(DictionaryKind::Jieba);
        }
        Err(LinderaErrorKind::Dictionary
            .with_error(anyhow::anyhow!("Invalid dictionary kind: {input}")))
    }
}

/// Resolve the embedded loader for a given dictionary kind.
///
/// # Arguments
///
/// * `dictionary_type` - Which embedded dictionary to load.
///
/// # Returns
///
/// A boxed loader for the requested dictionary kind, or an error if the
/// corresponding `embed-*` feature was not compiled in.
pub fn resolve_embedded_loader(
    dictionary_type: DictionaryKind,
) -> LinderaResult<Box<dyn DictionaryLoader>> {
    match dictionary_type {
        #[cfg(feature = "embed-ipadic")]
        DictionaryKind::IPADIC => Ok(Box::new(EmbeddedIPADICLoader::new())),
        #[cfg(feature = "embed-ipadic-neologd")]
        DictionaryKind::IPADICNEologd => Ok(Box::new(EmbeddedIPADICNEologdLoader::new())),
        #[cfg(feature = "embed-unidic")]
        DictionaryKind::UniDic => Ok(Box::new(EmbeddedUniDicLoader::new())),
        #[cfg(feature = "embed-sudachidict")]
        DictionaryKind::SudachiDict => Ok(Box::new(EmbeddedSudachiDictLoader::new())),
        #[cfg(feature = "embed-ko-dic")]
        DictionaryKind::KoDic => Ok(Box::new(EmbeddedKoDicLoader::new())),
        #[cfg(feature = "embed-cc-cedict")]
        DictionaryKind::CcCedict => Ok(Box::new(EmbeddedCcCedictLoader::new())),
        #[cfg(feature = "embed-jieba")]
        DictionaryKind::Jieba => Ok(Box::new(EmbeddedJiebaLoader::new())),
    }
}

/// Load a dictionary from a filesystem directory, always doing a plain file
/// read (no memory mapping).
///
/// # Arguments
///
/// * `path` - Path to the directory containing dictionary files.
///
/// # Returns
///
/// A `Dictionary`, or an error if loading fails.
pub fn load_fs_dictionary(path: &Path) -> LinderaResult<Dictionary> {
    load_fs_dictionary_with_options(path, cfg!(feature = "mmap"))
}

/// Load a dictionary from a filesystem directory, optionally via
/// memory-mapped reads. See
/// [`lindera_dictionary::dictionary::Dictionary::load_from_path_with_options`]
/// for exactly which components `use_mmap` does and does not make lazy.
///
/// # Arguments
///
/// * `path` - Path to the directory containing dictionary files.
/// * `use_mmap` - Whether to route the connection-cost matrix and prefix
///   dictionary through memory-mapped reads.
///
/// # Returns
///
/// A `Dictionary`, or an error if loading fails.
pub fn load_fs_dictionary_with_options(path: &Path, use_mmap: bool) -> LinderaResult<Dictionary> {
    let loader = FSDictionaryLoader::new();
    loader.load_from_path_with_options(path, use_mmap)
}

/// Load an embedded dictionary of the given kind.
///
/// # Arguments
///
/// * `kind` - Which embedded dictionary to load.
///
/// # Returns
///
/// A `Dictionary`, or an error if the corresponding `embed-*` feature was
/// not compiled in or loading otherwise fails.
pub fn load_embedded_dictionary(kind: DictionaryKind) -> LinderaResult<Dictionary> {
    let loader = resolve_embedded_loader(kind)?;
    loader
        .load()
        .map_err(|e| LinderaErrorKind::NotFound.with_error(e))
}

/// Load a dictionary from a URI (`embedded://<kind>`, `file://<path>`) or a
/// bare filesystem path, always doing a plain file read for filesystem
/// dictionaries (no memory mapping).
///
/// # Arguments
///
/// * `uri` - A dictionary URI or bare filesystem path.
///
/// # Returns
///
/// A `Dictionary`, or an error if the URI is invalid or loading fails.
pub fn load_dictionary(uri: &str) -> LinderaResult<Dictionary> {
    load_dictionary_with_options(uri, cfg!(feature = "mmap"))
}

/// Load a dictionary from a URI (`embedded://<kind>`, `file://<path>`) or a
/// bare filesystem path, optionally via memory-mapped reads for filesystem
/// dictionaries. `use_mmap` is silently ignored for `embedded://` URIs,
/// since embedded dictionary data is already a static, zero-copy byte slice
/// baked into the binary.
///
/// # Arguments
///
/// * `uri` - A dictionary URI or bare filesystem path.
/// * `use_mmap` - Whether to route filesystem-loaded dictionaries' connection
///   cost matrix and prefix dictionary through memory-mapped reads.
///
/// # Returns
///
/// A `Dictionary`, or an error if the URI is invalid or loading fails.
pub fn load_dictionary_with_options(uri: &str, use_mmap: bool) -> LinderaResult<Dictionary> {
    // Try to parse as URI first, but only if it looks like a URI
    // (contains "://" or starts with known schemes)
    if uri.contains("://") {
        match Url::parse(uri) {
            Ok(parsed_uri) => {
                // Parse the URI and return the appropriate dictionary
                let scheme = DictionaryScheme::from_str(parsed_uri.scheme()).map_err(|err| {
                    LinderaErrorKind::Dictionary
                        .with_error(anyhow::anyhow!("Invalid dictionary scheme: {err}"))
                })?;

                match scheme {
                    #[cfg(any(
                        feature = "embed-ipadic",
                        feature = "embed-ipadic-neologd",
                        feature = "embed-unidic",
                        feature = "embed-sudachidict",
                        feature = "embed-ko-dic",
                        feature = "embed-cc-cedict",
                        feature = "embed-jieba",
                    ))]
                    DictionaryScheme::Embedded => {
                        let kind = DictionaryKind::from_str(parsed_uri.host_str().unwrap_or(""))
                            .map_err(|err| LinderaErrorKind::Dictionary.with_error(err))?;

                        // Load the embedded dictionary
                        load_embedded_dictionary(kind)
                    }
                    DictionaryScheme::File => {
                        // Extract path from file:// URL manually
                        let path_str = parsed_uri.path();

                        // Handle Windows paths that might start with /C:/ etc.
                        let path_str =
                            if cfg!(windows) && path_str.len() > 1 && path_str.starts_with('/') {
                                &path_str[1..]
                            } else {
                                path_str
                            };

                        // Decode percent-encoded characters
                        let decoded_path =
                            percent_decode_str(path_str).decode_utf8().map_err(|e| {
                                LinderaErrorKind::Dictionary
                                    .with_error(anyhow::anyhow!("Invalid UTF-8 in path: {e}"))
                            })?;

                        let path = Path::new(decoded_path.as_ref());

                        // Load the file-based dictionary
                        load_fs_dictionary_with_options(path, use_mmap)
                    }
                }
            }
            Err(e) => {
                Err(LinderaErrorKind::Dictionary
                    .with_error(anyhow::anyhow!("Invalid URI format: {e}")))
            }
        }
    } else {
        // Treat it as a file path directly
        let path = Path::new(uri);
        load_fs_dictionary_with_options(path, use_mmap)
    }
}

pub fn load_user_dictionary_from_csv(
    metadata: &Metadata,
    path: &Path,
) -> LinderaResult<UserDictionary> {
    let builder = DictionaryBuilder::new(metadata.clone());
    UserDictionaryLoader::load_from_csv(builder, path)
}

pub fn load_user_dictionary_from_bin(path: &Path) -> LinderaResult<UserDictionary> {
    UserDictionaryLoader::load_from_bin(path)
}

pub fn load_user_dictionary(uri: &str, metadata: &Metadata) -> LinderaResult<UserDictionary> {
    // Try to parse as URI first, but only if it looks like a URI
    // (contains "://" or starts with known schemes)
    let path = if uri.contains("://") {
        match Url::parse(uri) {
            Ok(parsed_uri) => {
                // Parse the URI and return the appropriate dictionary
                let scheme = DictionaryScheme::from_str(parsed_uri.scheme()).map_err(|err| {
                    LinderaErrorKind::Dictionary
                        .with_error(anyhow::anyhow!("Invalid dictionary scheme: {err}"))
                })?;

                match scheme {
                    DictionaryScheme::File => {
                        // Extract path from file:// URL manually
                        let path_str = parsed_uri.path();

                        // Handle Windows paths that might start with /C:/ etc.
                        let path_str =
                            if cfg!(windows) && path_str.len() > 1 && path_str.starts_with('/') {
                                &path_str[1..]
                            } else {
                                path_str
                            };

                        // Decode percent-encoded characters
                        let decoded_path =
                            percent_decode_str(path_str).decode_utf8().map_err(|e| {
                                LinderaErrorKind::Dictionary
                                    .with_error(anyhow::anyhow!("Invalid UTF-8 in path: {e}"))
                            })?;

                        PathBuf::from(decoded_path.as_ref())
                    }
                    #[cfg(any(
                        feature = "embed-ipadic",
                        feature = "embed-ipadic-neologd",
                        feature = "embed-unidic",
                        feature = "embed-sudachidict",
                        feature = "embed-ko-dic",
                        feature = "embed-cc-cedict",
                        feature = "embed-jieba",
                    ))]
                    _ => {
                        // Unsupported dictionary scheme
                        return Err(LinderaErrorKind::Dictionary
                            .with_error(anyhow::anyhow!("Unsupported dictionary scheme")));
                    }
                }
            }
            Err(e) => {
                return Err(LinderaErrorKind::Dictionary
                    .with_error(anyhow::anyhow!("Invalid URI format: {e}")));
            }
        }
    } else {
        // Treat it as a file path directly
        PathBuf::from(uri)
    };

    // extract file extension
    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .ok_or_else(|| {
            LinderaErrorKind::Args
                .with_error(anyhow::anyhow!("Invalid user dictionary source file"))
        })?;

    match extension {
        "csv" => load_user_dictionary_from_csv(metadata, &path),
        "bin" => load_user_dictionary_from_bin(&path),
        _ => Err(LinderaErrorKind::Args.with_error(anyhow::anyhow!(
            "Invalid user dictionary source file extension"
        ))),
    }
}