Dictionary Management

The functions and the types of lindera.h for the dictionaries themselves: building a dictionary and a user dictionary, the metadata of a dictionary, and its schema. Loading a dictionary for a tokenizer is in Tokenizer API. The rules the functions share (who frees an object, how an error is returned, how text is passed) 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. A path is text.

Building a dictionary

LinderaStatus lindera_dictionary_build(const uint8_t *input_dir, size_t input_dir_len,
                                       const uint8_t *output_dir, size_t output_dir_len,
                                       const LinderaMetadata *metadata,
                                       const uint8_t *context_id_freq, size_t context_id_freq_len,
                                       LinderaError **error);

lindera_dictionary_build builds a dictionary from its source files, as lindera dictionary build does. input_dir is the directory of the source files (the lexicons as CSV, matrix.def, char.def, unk.def), and output_dir the directory the dictionary is written to, which is made if it is not there. metadata says how the source files are read. It is normally read from the metadata.json of the dictionary, with lindera_metadata_from_json_file.

context_id_freq is the path of a histogram of the context IDs, such as the context_id_freq.txt of a dictionary crate, or the empty text (NULL, 0) for none. It is read only when the metadata turns connection_id_mapping on, as the metadata.json of ko-dic and of UniDic does. The build then relabels the context IDs of the connection matrix by how often they are read: by the counts of the histogram or, without one, by the count of the entries. The relabelling changes the speed of tokenizing, never its result.

The call fails with LINDERA_STATUS_INVALID_ARGUMENT when metadata is NULL, and with LINDERA_STATUS_IO when the source directory or the histogram cannot be read. The message starts with Failed to build dictionary:.

The program below is lindera-c/examples/build_dictionary.c. It reads a metadata, builds a dictionary, loads it, and tokenizes a text with it:

/* Builds a dictionary from its source files, as `lindera dictionary build`
 * does, loads it, and tokenizes a text with it.
 *
 *     build_dictionary <source directory> <metadata.json> <output directory> [<text>]
 *
 * <source directory> holds the lexicons (CSV), matrix.def, char.def and
 * unk.def. <metadata.json> describes them. The dictionary is written to
 * <output directory>. <text> is UTF-8.
 */

#include <stdio.h>
#include <string.h>

#include "lindera.h"

/* Prints what failed with the message of the error, frees the error, and
 * returns the exit code of a failure. */
static int fail(const char *what, LinderaStatus status, LinderaError *error) {
    LinderaStr message = lindera_error_message(error);

    fprintf(stderr, "%s: %s: %.*s\n", what, lindera_status_name(status), (int)message.len,
            (const char *)message.ptr);
    lindera_error_free(error);
    return 1;
}

int main(int argc, char **argv) {
    const char *text = argc > 4 ? argv[4] : "東京都";
    const char *source;
    const char *output;
    LinderaMetadata *metadata = NULL;
    LinderaSchema *schema;
    LinderaDictionary *dictionary = NULL;
    LinderaTokenizer *tokenizer = NULL;
    LinderaResult *result = NULL;
    LinderaTokens tokens;
    LinderaStrs fields;
    LinderaStr name;
    LinderaError *error = NULL;
    LinderaStatus status;
    size_t i;
    size_t j;

    if (argc < 4) {
        fprintf(stderr, "usage: build_dictionary <source directory> <metadata.json> <output directory> [<text>]\n");
        return 2;
    }
    source = argv[1];
    output = argv[3];

    /* The metadata says how the source files are read: their encoding and
     * the fields of their rows. */
    status = lindera_metadata_from_json_file((const uint8_t *)argv[2], strlen(argv[2]), &metadata, &error);
    if (status != LINDERA_STATUS_OK) {
        return fail("lindera_metadata_from_json_file", status, error);
    }
    name = lindera_metadata_name(metadata);
    /* The schema is a copy, which this program frees. */
    schema = lindera_metadata_dictionary_schema(metadata);
    fields = lindera_schema_fields(schema);
    printf("%.*s:", (int)name.len, (const char *)name.ptr);
    for (i = 0; i < fields.len; i++) {
        printf(" %.*s", (int)fields.ptr[i].len, (const char *)fields.ptr[i].ptr);
    }
    printf("\n");
    lindera_schema_free(schema);

    /* No histogram of the context IDs: the last two arguments before the
     * error are an empty text. */
    status = lindera_dictionary_build((const uint8_t *)source, strlen(source), (const uint8_t *)output,
                                      strlen(output), metadata, NULL, 0, &error);
    lindera_metadata_free(metadata);
    if (status != LINDERA_STATUS_OK) {
        return fail("lindera_dictionary_build", status, error);
    }

    /* The directory that was written is a dictionary like any other. */
    status = lindera_dictionary_load((const uint8_t *)output, strlen(output), &dictionary, &error);
    if (status != LINDERA_STATUS_OK) {
        return fail("lindera_dictionary_load", status, error);
    }
    status = lindera_tokenizer_new(dictionary, NULL, NULL, NULL, 0, &tokenizer, &error);
    lindera_dictionary_free(dictionary);
    if (status != LINDERA_STATUS_OK) {
        return fail("lindera_tokenizer_new", status, error);
    }

    status = lindera_tokenizer_tokenize(tokenizer, (const uint8_t *)text, strlen(text), &result,
                                        &tokens, &error);
    if (status != LINDERA_STATUS_OK) {
        lindera_tokenizer_free(tokenizer);
        return fail("lindera_tokenizer_tokenize", status, error);
    }
    for (i = 0; i < tokens.len; i++) {
        const LinderaToken *token = &tokens.tokens[i];

        printf("%.*s\t", (int)token->surface.len, (const char *)token->surface.ptr);
        for (j = 0; j < token->details_len; j++) {
            printf("%s%.*s", j == 0 ? "" : ",", (int)token->details[j].len,
                   (const char *)token->details[j].ptr);
        }
        printf("\n");
    }
    printf("EOS\n");

    lindera_result_free(result);
    lindera_tokenizer_free(tokenizer);
    return 0;
}

Compile it against an installed library (see Installation) and run it with the source of a dictionary. The repository has the source of a small one, with one entry (東京), for its tests:

export PKG_CONFIG_PATH="$PWD/dist/lib/pkgconfig"
cc -o build_dictionary lindera-c/examples/build_dictionary.c $(pkg-config --cflags --libs lindera)
LD_LIBRARY_PATH="$PWD/dist/lib" ./build_dictionary resources/connection_id_mapping/source \
    resources/connection_id_mapping/metadata.json /tmp/lindera-example-dictionary

Expected output:

connection_id_mapping: surface left_context_id right_context_id cost part_of_speech part_of_speech_subcategory_1 part_of_speech_subcategory_2 part_of_speech_subcategory_3 conjugation_type conjugation_form base_form reading pronunciation
東京    名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トウキョウ
都    名詞,一般,*,*,*,*,*,*,*
EOS

Building a user dictionary

LinderaStatus lindera_user_dictionary_build(const uint8_t *input_file, size_t input_file_len,
                                            const uint8_t *output_file, size_t output_file_len,
                                            const LinderaMetadata *metadata, LinderaError **error);
LinderaStatus lindera_user_dictionary_build_for(const uint8_t *input_file, size_t input_file_len,
                                                const uint8_t *output_file, size_t output_file_len,
                                                const LinderaDictionary *dictionary,
                                                LinderaError **error);
LinderaStatus lindera_user_dictionary_load(const uint8_t *uri, size_t uri_len,
                                           const LinderaMetadata *metadata,
                                           LinderaUserDictionary **out, LinderaError **error);

lindera_user_dictionary_build and lindera_user_dictionary_build_for build a user dictionary from the CSV file input_file and write it to output_file. The functions that load a user dictionary choose how to read a file by its extension, so output_file should end with .bin. Its directory is made if it is not there.

FunctionBuilds withThe context IDs of a row
lindera_user_dictionary_build_forThe metadata of dictionaryChecked against the connection matrix of the dictionary as the CSV is built. A row outside the matrix fails the call with LINDERA_STATUS_PARSE, the message names its line and its surface (line 2 (surface: '東京スカイツリー')), and no file is written
lindera_user_dictionary_buildmetadata; NULL is the default metadataNot checked here. A tokenizer checks them when it is made with the user dictionary, and names an entry outside the matrix by its word ID

Both fail with LINDERA_STATUS_IO when the CSV cannot be read. The message starts with Failed to build user dictionary:.

lindera_user_dictionary_load loads a user dictionary (a .csv or a .bin file) with a metadata, as lindera_user_dictionary_load_for loads one for a dictionary. As lindera_user_dictionary_build, it does not check the context IDs of a CSV. With a dictionary that is loaded, the two functions that end in _for are the ones to use:

LinderaDictionary *dictionary = NULL;
LinderaUserDictionary *user_dictionary = NULL;

lindera_dictionary_load(uri, uri_len, &dictionary, &error);
if (lindera_user_dictionary_build_for(csv, csv_len, bin, bin_len, dictionary, &error) ==
    LINDERA_STATUS_OK) {
    lindera_user_dictionary_load_for(bin, bin_len, dictionary, &user_dictionary, &error);
}

LinderaMetadata

The metadata of a dictionary: what its metadata.json holds.

LinderaMetadata *lindera_metadata_new(void);
LinderaStatus lindera_metadata_from_json_file(const uint8_t *path, size_t path_len,
                                              LinderaMetadata **out, LinderaError **error);
LinderaMetadata *lindera_dictionary_metadata(const LinderaDictionary *dictionary);
void lindera_metadata_free(LinderaMetadata *metadata);

lindera_metadata_new makes a metadata with the default values. lindera_metadata_from_json_file reads one from a JSON file, such as the metadata.json of a dictionary: it fails with LINDERA_STATUS_IO when the file cannot be read, and with LINDERA_STATUS_PARSE when it is not the JSON of a metadata. lindera_dictionary_metadata gives a copy of the metadata of a dictionary that is loaded (NULL for NULL). The caller frees each of them with lindera_metadata_free.

Each value has a function that reads it, lindera_metadata_<value>, and one that sets it, lindera_metadata_set_<value>, which returns a LinderaStatus. A value that is text is read as a LinderaStr, which is valid until the value is set again or the metadata is freed, and set as a pointer and a length.

ValueTypeDefaultWhat it is
nametextdefaultThe name of the dictionary
encodingtextUTF-8The character encoding of the source files
default_word_costint16_t-10000The cost of a simple entry of a user dictionary, which gives none
default_left_context_iduint16_t1288The left context ID of a simple entry of a user dictionary
default_right_context_iduint16_t1288The right context ID of a simple entry of a user dictionary
default_field_valuetext*The value of the fields a simple entry of a user dictionary lacks
flexible_csvboolfalseWhether the rows of the CSV files may have a varying number of columns
skip_invalid_cost_or_idboolfalseWhether a build skips the rows with an invalid cost or context ID, instead of failing
LinderaMetadata *metadata = lindera_metadata_new();
LinderaStr name;

lindera_metadata_set_name(metadata, (const uint8_t *)"my-dictionary", 13, &error);
lindera_metadata_set_default_word_cost(metadata, -5000, &error);
name = lindera_metadata_name(metadata); /* "my-dictionary", until it is set again */
lindera_metadata_free(metadata);

The two schemas of a metadata, and the left-space penalty rules it ships:

LinderaSchema *lindera_metadata_dictionary_schema(const LinderaMetadata *metadata);
LinderaStatus lindera_metadata_set_dictionary_schema(LinderaMetadata *metadata,
                                                     const LinderaSchema *schema,
                                                     LinderaError **error);
LinderaSchema *lindera_metadata_user_dictionary_schema(const LinderaMetadata *metadata);
LinderaStatus lindera_metadata_set_user_dictionary_schema(LinderaMetadata *metadata,
                                                          const LinderaSchema *schema,
                                                          LinderaError **error);
LinderaStr lindera_metadata_space_penalty_json(const LinderaMetadata *metadata);

lindera_metadata_dictionary_schema gives a copy of the schema of the dictionary (the fields of the rows of its lexicons), and lindera_metadata_user_dictionary_schema a copy of the schema of the user dictionaries (the fields of a simple entry: surface, reading and pronunciation by default). The caller frees a copy with lindera_schema_free. The two functions that set a schema copy it, so the caller still frees its own.

lindera_metadata_space_penalty_json returns the left-space penalty rules the metadata ships, as JSON text ({"rules":[{"pos":["JKS"],"cost":6000}]}): what lindera_tokenizer_builder_set_space_penalty takes. It is valid until the metadata is freed. A metadata without rules, as all but that of ko-dic are, gives no string (ptr is NULL).

A metadata that is read from a file keeps the settings of the file that have no function here: the left-space penalty rules, connection_id_mapping, and the formats of the source files. A dictionary built with it is built as lindera dictionary build builds it.

LinderaSchema

The schema of a dictionary: the names of the fields of its entries, in the order of the columns of its CSV. A schema does not change once it is made.

LinderaStatus lindera_schema_new(const LinderaStr *fields, size_t fields_len, LinderaSchema **out,
                                 LinderaError **error);
LinderaSchema *lindera_schema_default(void);
void lindera_schema_free(LinderaSchema *schema);

lindera_schema_new makes a schema from an array of fields_len names, which it copies. fields[i] is a LinderaStr: a pointer and a length. lindera_schema_default makes the default schema, of 13 fields: surface, left_context_id, right_context_id, cost, major_pos, pos_detail_1, pos_detail_2, pos_detail_3, conjugation_type, conjugation_form, base_form, reading and pronunciation.

The first four fields of a schema are the surface, the left context ID, the right context ID and the cost, whatever their names. The fields after them are the dictionary's own, the custom fields: they are what a token gives as its details.

FunctionReturns
lindera_schema_field_countThe number of fields
lindera_schema_fieldsThe names of the fields, as a LinderaStrs
lindera_schema_custom_fieldsThe names of the fields after the first four, as a LinderaStrs
lindera_schema_field_nameThe name of the field at an index, or no string for an index the schema does not have
lindera_schema_field_indextrue, with the index of a field in *out_index, when the schema has a field of that name
lindera_schema_field_by_nameThe definition of the field of a name, or NULL

A LinderaStrs is ptr (const LinderaStr *, NULL when len is 0) and len. The strings are valid until the schema is freed.

static const char *const NAMES[] = {"surface", "left_context_id", "right_context_id", "cost",
                                    "pos", "reading"};
LinderaStr fields[6];
LinderaSchema *schema = NULL;
LinderaStrs custom;
size_t index;
size_t i;

for (i = 0; i < 6; i++) {
    fields[i].ptr = (const uint8_t *)NAMES[i];
    fields[i].len = strlen(NAMES[i]);
}
if (lindera_schema_new(fields, 6, &schema, &error) == LINDERA_STATUS_OK) {
    custom = lindera_schema_custom_fields(schema); /* "pos", "reading" */
    if (lindera_schema_field_index(schema, (const uint8_t *)"reading", 7, &index)) {
        /* index is 5 */
    }
    lindera_schema_free(schema);
}
LinderaStatus lindera_schema_validate_record(const LinderaSchema *schema, const LinderaStr *record,
                                             size_t record_len, LinderaError **error);

lindera_schema_validate_record checks the values of one entry (a row of a CSV) against the schema. It fails with LINDERA_STATUS_VALIDATION when the record has fewer values than the schema has fields (CSV row has 2 fields but schema requires 5 fields), or when a value of a field of the schema is empty (Field reading is missing or empty). The context IDs and the cost may not be blank either.

LinderaFieldDefinition and LinderaFieldType

The definition of one field of a schema: its index, its name, what it holds, and a description.

LinderaFieldDefinition *lindera_schema_field_by_name(const LinderaSchema *schema,
                                                     const uint8_t *name, size_t name_len);
LinderaStatus lindera_field_definition_new(size_t index, const uint8_t *name, size_t name_len,
                                           LinderaFieldType field_type,
                                           const uint8_t *description, size_t description_len,
                                           LinderaFieldDefinition **out, LinderaError **error);
void lindera_field_definition_free(LinderaFieldDefinition *field_definition);

lindera_schema_field_by_name gives the definition of a field of a schema, without a description. lindera_field_definition_new makes one from its values: description is NULL for a definition without a description, and a field_type that is none of the constants fails with LINDERA_STATUS_INVALID_ARGUMENT. The caller frees a definition with lindera_field_definition_free.

FunctionReturns
lindera_field_definition_indexThe index of the field in its schema, from 0
lindera_field_definition_nameThe name of the field
lindera_field_definition_field_typeWhat the field holds: a LinderaFieldType
lindera_field_definition_descriptionThe description, or no string when there is none
lindera_field_type_nameThe name of a LinderaFieldType, as static text

A LinderaFieldType is a uint32_t with one of these values:

ConstantValueNameThe field
LINDERA_FIELD_TYPE_SURFACE0surfaceThe first: the surface of the word
LINDERA_FIELD_TYPE_LEFT_CONTEXT_ID1left_context_idThe second: the left context ID
LINDERA_FIELD_TYPE_RIGHT_CONTEXT_ID2right_context_idThe third: the right context ID
LINDERA_FIELD_TYPE_COST3costThe fourth: the cost of the word
LINDERA_FIELD_TYPE_CUSTOM4customEvery field after the fourth