Tokenizer API

The functions and the types of lindera.h for tokenizing: the dictionary and the user dictionary, the mode, the builder, the tokenizer and the tokens. The rules they share (who frees an object, how an error is returned, how text is passed, which thread may call what) are in Lindera C.

In the prototypes below, text is a pair of arguments, const uint8_t *ptr, size_t len: len bytes of UTF-8, with no NUL needed at the end.

Versions and features

const char *lindera_version(void);
uint32_t lindera_version_number(void);
uint32_t lindera_abi_version(void);
bool lindera_has_feature(const uint8_t *name, size_t name_len);
FunctionReturns
lindera_versionThe version of Lindera, as static text that ends with a NUL ("7.3.0")
lindera_version_numbermajor * 10000 + minor * 100 + patch (70300 for 7.3.0)
lindera_abi_versionThe version of the binary interface of the library, to compare with LINDERA_ABI_VERSION
lindera_has_featureWhether the library was built with a feature: "train", "dependency", "embed-<dictionary>" or "embed-dependency-<dictionary>". false for a name that is no feature

Errors

void lindera_error_free(LinderaError *error);
LinderaStatus lindera_error_status(const LinderaError *error);
LinderaStr lindera_error_message(const LinderaError *error);
const char *lindera_status_name(LinderaStatus status);
FunctionReturns
lindera_error_statusThe status the failed call returned; LINDERA_STATUS_OK for NULL
lindera_error_messageThe message, valid until the error is freed; no string (ptr is NULL) for NULL
lindera_status_nameThe name of a status in lower case, as static text: "ok", "invalid_argument", "dictionary", "build", "io", "parse", "validation", "runtime", "panic", or "unknown" for another value

lindera_error_free frees an error; NULL does nothing.

LinderaDictionary

A dictionary that is loaded.

LinderaStatus lindera_dictionary_load(const uint8_t *uri, size_t uri_len,
                                      LinderaDictionary **out, LinderaError **error);
void lindera_dictionary_free(LinderaDictionary *dictionary);
LinderaStr lindera_dictionary_metadata_name(const LinderaDictionary *dictionary);
LinderaStr lindera_dictionary_metadata_encoding(const LinderaDictionary *dictionary);

lindera_dictionary_load loads the dictionary at uri: the path of a directory that holds a built dictionary, or embedded://<name> (for example embedded://ipadic) for a dictionary the library was built with. It fails with LINDERA_STATUS_IO when the path does not exist, and with LINDERA_STATUS_DICTIONARY when the library was not built with the embedded dictionary.

lindera_dictionary_metadata_name and lindera_dictionary_metadata_encoding return the name ("ipadic") and the character encoding ("UTF-8") the metadata of the dictionary records. The strings are valid until the dictionary is freed.

A dictionary that is loaded makes a tokenizer with lindera_tokenizer_new, and a user dictionary is loaded for it. The whole metadata of a dictionary (lindera_dictionary_metadata), with its schema, and building a dictionary are in Dictionary Management.

LinderaUserDictionary

A user dictionary: words a program adds to those of a dictionary.

LinderaStatus lindera_user_dictionary_load_for(const uint8_t *uri, size_t uri_len,
                                               const LinderaDictionary *dictionary,
                                               LinderaUserDictionary **out,
                                               LinderaError **error);
void lindera_user_dictionary_free(LinderaUserDictionary *user_dictionary);

lindera_user_dictionary_load_for loads the file at uri for dictionary: a .csv file, which is built with the metadata of the dictionary and checked against its connection matrix, or a .bin file, a user dictionary that was built before. A line of a CSV that the dictionary cannot hold fails the call, and the message names the line and the surface (line 2 (surface: '東京スカイツリー')).

A line of the simplest CSV is a surface, a part of speech and a reading:

東京スカイツリー,カスタム名詞,トウキョウスカイツリー

With it, 東京スカイツリー is one token, whose first detail is カスタム名詞.

Building a user dictionary into a .bin file, and loading one with a metadata in place of a dictionary (lindera_user_dictionary_load), are in Dictionary Management.

LinderaPenalty and LinderaMode

A tokenizer runs in the normal mode, or in the decompose mode, which prefers the shorter words a long word is made of. The decompose mode has a penalty: a word of more characters than a threshold costs the penalty for each character over it, and words of kanji alone have a threshold and a penalty of their own.

LinderaPenalty *lindera_penalty_new(void);
void lindera_penalty_free(LinderaPenalty *penalty);

LinderaMode *lindera_mode_normal(void);
LinderaMode *lindera_mode_decompose(const LinderaPenalty *penalty);
LinderaStatus lindera_mode_from_str(const uint8_t *name, size_t name_len, LinderaMode **out,
                                    LinderaError **error);
void lindera_mode_free(LinderaMode *mode);

lindera_penalty_new makes a penalty with the default values. Each value has a function that reads it, lindera_penalty_<value>, and one that sets it, lindera_penalty_set_<value>, which returns a LinderaStatus:

ValueTypeDefaultWhat it is
kanji_penalty_length_thresholdsize_t2The number of characters over which a word of kanji alone is penalized
kanji_penalty_length_penaltyint32_t3000The cost of each character of such a word over the threshold
other_penalty_length_thresholdsize_t7The number of characters over which another word is penalized
other_penalty_length_penaltyint32_t1700The cost of each character of such a word over the threshold

lindera_mode_normal makes the normal mode and lindera_mode_decompose the decompose mode, with a copy of penalty; NULL is the default penalty. lindera_mode_from_str makes the mode a name stands for, "normal" or "decompose" (with the default penalty); another name is LINDERA_STATUS_INVALID_ARGUMENT.

FunctionReturns
lindera_mode_name"normal" or "decompose", as static text; NULL for NULL
lindera_mode_penaltyA copy of the penalty of a decompose mode, which the caller frees with lindera_penalty_free; NULL for the normal mode
lindera_mode_is_normal, lindera_mode_is_decomposeWhether the mode is that one
lindera_mode_equalsWhether two modes are both normal, or both decompose with the same penalty

With IPADIC, 関西国際空港限定トートバッグ gives:

ModeTokens
Normal関西国際空港 / 限定 / トートバッグ
Decompose, with the default penalty関西 / 国際 / 空港 / 限定 / トートバッグ
Decompose, with other_penalty_length_threshold 4 and other_penalty_length_penalty 3000関西 / 国際 / 空港 / 限定 / トー / トバッグ
Decompose, with both penalties 0関西国際空港 / 限定 / トートバッグ

LinderaTokenizerBuilder

A builder collects the settings of a tokenizer. The functions that change a builder must not run at the same time on the same builder.

Making and freeing

LinderaStatus lindera_tokenizer_builder_new(LinderaTokenizerBuilder **out, LinderaError **error);
LinderaStatus lindera_tokenizer_builder_from_file(const uint8_t *path, size_t path_len,
                                                  LinderaTokenizerBuilder **out,
                                                  LinderaError **error);
void lindera_tokenizer_builder_free(LinderaTokenizerBuilder *builder);

lindera_tokenizer_builder_new makes a builder with the default settings, and lindera_tokenizer_builder_from_file one from a YAML configuration file.

Settings

Each of these functions returns a LinderaStatus and takes LinderaError **error as its last argument.

FunctionArgumentsWhat it sets
lindera_tokenizer_builder_set_dictionaryuriThe dictionary: a path, or embedded://<name>. It is loaded when the tokenizer is built
lindera_tokenizer_builder_set_modeconst LinderaMode *modeThe mode, of which the builder takes a copy. The default is the normal mode
lindera_tokenizer_builder_set_user_dictionaryuriThe user dictionary: the path of a .csv or of a .bin file. It is loaded when the tokenizer is built
lindera_tokenizer_builder_set_space_penaltyjsonThe left-space penalty (Korean), as JSON text: null or an empty text for the default (the rules the dictionary ships, if any), false for no penalty, true for the rules of the dictionary, which must ship some, or an object such as {"rules":[{"pos":["JKS"],"cost":6000}]}
lindera_tokenizer_builder_set_keep_whitespacebool keep_whitespaceWhether whitespace tokens are in the output. Kept whitespace also stays in the lattice, so the other tokens can differ from those of the default output
lindera_tokenizer_builder_set_skip_whitespacebool skip_whitespaceWhether whitespace is skipped in the lattice: true connects the words on either side directly, as MeCab does; false keeps the whitespace as a node of its own, which is still left out of the output. It has no effect while whitespace tokens are kept
lindera_tokenizer_builder_reset_skip_whitespaceRemoves that setting, so that the default of the dictionary applies (skipping, except with SudachiDict)
lindera_tokenizer_builder_set_break_charactersbreak_charactersThe break characters: no unknown word, nor, in decompose mode, any word of the dictionary, crosses a boundary between one of them and another character. An empty text turns the rule off, which gives the segmentation of MeCab
lindera_tokenizer_builder_reset_break_charactersRemoves that setting, so that the default (・) applies
lindera_tokenizer_builder_append_character_filterkind, args_jsonAppends a character filter
lindera_tokenizer_builder_append_token_filterkind, args_jsonAppends a token filter

kind is the name of a filter, and args_json its arguments as a JSON object; an empty text (NULL, 0) is no arguments. Text that is not a JSON object is LINDERA_STATUS_INVALID_ARGUMENT. The filters run in the order they were appended. A name or arguments a filter does not accept are reported when the tokenizer is built. Text Processing Pipeline shows the filters at work, and all of them are listed with their arguments in Filters.

With IPADIC, the break characters and the skipping of whitespace give:

TextSettingTokens
レノン・ジョンDefault (・ is a break character)レノン / ・ / ジョン
レノン・ジョンset_break_characters with an empty textレノン・ジョン
Google が 新しいDefault (whitespace skipped)が is a particle (助詞)
Google が 新しいset_skip_whitespace(false)が is a conjunction (接続詞)

Building

LinderaStatus lindera_tokenizer_builder_build(const LinderaTokenizerBuilder *builder,
                                              LinderaTokenizer **out, LinderaError **error);

Builds a tokenizer from the settings. The builder is not changed and can build again; the tokenizer does not need it afterwards. It fails when no dictionary is set, when the dictionary cannot be loaded, or when a setting or a filter is not valid.

LinderaTokenizer

A tokenizer from a dictionary

LinderaStatus lindera_tokenizer_new(const LinderaDictionary *dictionary, const LinderaMode *mode,
                                    const LinderaUserDictionary *user_dictionary,
                                    const uint8_t *space_penalty_json,
                                    size_t space_penalty_json_len, LinderaTokenizer **out,
                                    LinderaError **error);

Makes a tokenizer from a dictionary that is loaded, without a builder. mode is the mode, and NULL the normal mode. user_dictionary is a user dictionary, and NULL none. space_penalty_json is the left-space penalty, in the forms lindera_tokenizer_builder_set_space_penalty takes; an empty text (NULL, 0) is the default of the dictionary. The tokenizer takes what it needs of the three objects, which the program still frees, before or after the tokenizer.

A tokenizer made this way has no filters; a builder makes one with filters.

LinderaDictionary *dictionary = NULL;
LinderaMode *mode = lindera_mode_decompose(NULL);
LinderaTokenizer *tokenizer = NULL;

lindera_dictionary_load(uri, uri_len, &dictionary, &error);
lindera_tokenizer_new(dictionary, mode, NULL, NULL, 0, &tokenizer, &error);
lindera_mode_free(mode);
lindera_dictionary_free(dictionary);

A copy of a tokenizer

LinderaStatus lindera_tokenizer_clone(const LinderaTokenizer *tokenizer, LinderaTokenizer **out,
                                      LinderaError **error);

Makes a tokenizer with the same dictionary, mode, filters and settings, which gives the same tokens. The calls on one tokenizer take turns, so threads that tokenize in parallel each need a tokenizer of their own, and a copy is one that does not load the dictionary again: it shares the dictionary of the tokenizer it was made from, and has a copy of its user dictionary. The program frees each of the two with lindera_tokenizer_free, in any order.

LinderaTokenizer *copy = NULL;

/* One for each thread. */
lindera_tokenizer_clone(tokenizer, &copy, &error);
/* ... */
lindera_tokenizer_free(copy);

Tokenizing

LinderaStatus lindera_tokenizer_tokenize(const LinderaTokenizer *tokenizer,
                                         const uint8_t *text, size_t text_len,
                                         LinderaResult **out_result, LinderaTokens *out_tokens,
                                         LinderaError **error);
void lindera_tokenizer_free(LinderaTokenizer *tokenizer);
void lindera_result_free(LinderaResult *result);

lindera_tokenizer_tokenize tokenizes text. On success it stores a result in out_result and fills out_tokens:

LinderaResult *result = NULL;
LinderaTokens tokens;

if (lindera_tokenizer_tokenize(tokenizer, text, text_len, &result, &tokens, &error) ==
    LINDERA_STATUS_OK) {
    for (size_t i = 0; i < tokens.len; i++) {
        const LinderaToken *token = &tokens.tokens[i];
        /* ... */
    }
    lindera_result_free(result);
}

Everything tokens points to (the tokens, their details, their strings) belongs to the result, and is valid until lindera_result_free. The program frees the result once; the result outlives the tokenizer. A text without a token gives a result whose len is 0. On a failure, *out_result is NULL and out_tokens->len is 0.

Several threads may call lindera_tokenizer_tokenize with the same tokenizer at the same time; the calls take turns. To tokenize in parallel, each thread has a copy.

The other forms

Every form gives one result, which owns all its arrays and is freed once with lindera_result_free, and fills one struct; on a failure the result is NULL and the len of the struct is 0.

FunctionArguments after the tokenizerFills
lindera_tokenizer_tokenizetextLinderaTokens
lindera_tokenizer_tokenize_surfacestextLinderaSurfaces
lindera_tokenizer_tokenize_nbesttext, size_t n, bool unique, const int64_t *cost_thresholdLinderaNbest
lindera_tokenizer_tokenize_batchconst LinderaStr *texts, size_t texts_len, size_t max_threadsLinderaTokensBatch
lindera_tokenizer_tokenize_surfaces_batchtexts, texts_len, max_threadsLinderaSurfacesBatch
lindera_tokenizer_tokenize_nbest_batchtexts, texts_len, n, unique, cost_threshold, max_threadsLinderaNbestBatch

Each takes LinderaResult **out_result, a pointer to the struct it fills and LinderaError **error as its last three arguments.

The surfaces alone. lindera_tokenizer_tokenize_surfaces gives the surface and the position of each token, without the details: the fast way for a program that needs the words and no part of speech. The surfaces are those lindera_tokenizer_tokenize gives.

The N best. lindera_tokenizer_tokenize_nbest gives up to n tokenizations, the best first, each with its cost. unique leaves out a tokenization whose word boundaries are those of one before it. cost_threshold is NULL, or points to a number: tokenizations that cost more than the best one plus that number are left out.

LinderaResult *result = NULL;
LinderaNbest nbest;

if (lindera_tokenizer_tokenize_nbest(tokenizer, text, text_len, 3, false, NULL, &result, &nbest,
                                     &error) == LINDERA_STATUS_OK) {
    for (size_t i = 0; i < nbest.len; i++) {
        const LinderaNbestResult *candidate = &nbest.results[i];
        /* candidate->cost, and candidate->tokens.tokens[j] for j < candidate->tokens.len */
    }
    lindera_result_free(result);
}

Several texts. The batch forms tokenize each of texts_len texts as the form for one text does, on up to max_threads threads; 0 is the number of threads the system reports. texts[i] is a LinderaStr, a pointer and a length. The struct they fill has one entry for each text, in the order of texts, and the first text that fails, in that order, fails the call.

LinderaStr texts[2] = {{first, first_len}, {second, second_len}};
LinderaResult *result = NULL;
LinderaTokensBatch batch;

if (lindera_tokenizer_tokenize_batch(tokenizer, texts, 2, 0, &result, &batch, &error) ==
    LINDERA_STATUS_OK) {
    for (size_t i = 0; i < batch.len; i++) {
        const LinderaTokens *tokens = &batch.texts[i];
        /* tokens->tokens[j] for j < tokens->len */
    }
    lindera_result_free(result);
}

LinderaTokens

FieldTypeWhat it is
tokensconst LinderaToken *The tokens, in the order of the text. NULL when len is 0
lensize_tThe number of tokens
arenaLinderaStrThe one block of bytes every string of the result points into. A program that copies the strings can copy this block once, and find each string by its distance from arena.ptr. The lists of one result (the texts of a batch, the tokenizations of an N-best result) give the same block, in which the bytes of one list are one run

LinderaToken

FieldTypeWhat it is
surfaceLinderaStrThe surface form
byte_startsize_tWhere the token starts in the text, in bytes
byte_endsize_tWhere the token ends in the text (exclusive), in bytes
positionsize_tThe position of the token among the tokens, from 0
detailsconst LinderaStr *The details: the fields of the word in the dictionary (the part of speech, the reading and so on)
details_lensize_tThe number of details
dependencyconst LinderaTokenDependency *The dependency of the token, or NULL unless the token filter japanese_dependency wrote one
word_iduint32_tThe ID of the word in the dictionary
flagsuint32_tBits. LINDERA_TOKEN_FLAG_UNKNOWN is set when the word is not in the dictionary

A word that is not in the dictionary has the details of its line of the unknown word definition (名詞,一般,*,*,*,*,*,*,* for a katakana word with IPADIC).

LinderaSurfaces and LinderaSurface

LinderaSurfaces has surfaces (const LinderaSurface *, NULL when len is 0), len and arena, as LinderaTokens has.

Field of LinderaSurfaceTypeWhat it is
surfaceLinderaStrThe surface form
byte_startsize_tWhere the token starts in the text, in bytes
byte_endsize_tWhere the token ends in the text (exclusive), in bytes

LinderaNbest and LinderaNbestResult

LinderaNbest has results (const LinderaNbestResult *, NULL when len is 0) and len.

Field of LinderaNbestResultTypeWhat it is
tokensLinderaTokensThe tokens of this tokenization
costint64_tIts cost: the lower, the better

The batches

LinderaTokensBatch, LinderaSurfacesBatch and LinderaNbestBatch have texts and len: texts[i] is the LinderaTokens, the LinderaSurfaces or the LinderaNbest of the text i. texts is NULL when len is 0.

LinderaTokenDependency

What the token filter japanese_dependency writes: the bunsetsu of a token, and the bunsetsu that one depends on. See Token Filter for the filter and its model.

FieldTypeWhat it is
scoredoubleThe score of the decision that attached the bunsetsu to its head
sentenceuint32_tThe number of the sentence in the text, from 0
bunsetsuuint32_tThe number of the bunsetsu of the token in its sentence, from 0
headuint32_tThe number of the bunsetsu that one depends on, or LINDERA_NO_HEAD for the last bunsetsu of a sentence
roleLinderaBunsetsuRoleWhat the token is in its bunsetsu: LINDERA_BUNSETSU_ROLE_HEAD, _FUNCTION, _HEAD_FUNCTION or _OTHER

lindera_bunsetsu_role_name returns the name of a role as static text: "head", "function", "head_function" or "other".

The filter takes the path of a model file as its argument:

static const char kind[] = "japanese_dependency";
static const char args[] = "{\"model\":\"/path/to/ipadic.model\"}";

lindera_tokenizer_builder_append_token_filter(builder, (const uint8_t *)kind, strlen(kind),
                                              (const uint8_t *)args, strlen(args), &error);

The layout of the structs

The structs of the header have a fixed layout, which is part of the binary interface: a program in another language reads them by their offsets. A change of a layout changes LINDERA_ABI_VERSION. On a 64-bit system their sizes are:

StructBytes
LinderaStr16
LinderaToken72
LinderaTokenDependency24
LinderaTokens, LinderaSurface, LinderaSurfaces32
LinderaNbestResult40
LinderaNbest, LinderaTokensBatch, LinderaSurfacesBatch, LinderaNbestBatch16