Sudachi Japanese Morphological Analyzer

repository·develop·Indexed 21 days ago

https://github.com/worksapplications/sudachi

A high-performance Japanese morphological analyzer providing segmentation, part-of-speech tagging, and normalization. It features three splitting modes (A, B, and C) to control tokenization granularity and supports multiple dictionary types: Small, Core, and Full. Sudachi can be used as a standalone JAR via CLI or integrated into Java projects as a Maven dependency. It includes a plugin system for custom text normalization and unknown word handling.

Tokens
11.6K
Snippets
41
Records
57
Agent score
74%

What's inside Sudachi

  1. Overview of Works Applications NLP Resources

    develop

    Works Applications provides a suite of software and linguistic resources for Natural Language Processing (NLP), primarily focused on Japanese.

    Software

    • Sudachi: A Japanese morphological analyzer.
    • SudachiPy: The Python implementation of Sudachi.
    • elasticsearch-sudachi: A plugin for integrating Sudachi with Elasticsearch.
    • Kintoki: A dependency parser.
    • jdartsclone: A Trie data structure implementation using double arrays.

    Linguistic Resources

    • SudachiDict: Japanese morphological dictionaries.
    • SudachiDict Synonym: A Japanese synonym dictionary.
    • chiVe: Pre-trained Japanese word vectors.
    • chiTra: Pre-trained Japanese language models.
  2. Manage Dictionary Form IDs and Splitting Information

    develop

    Dictionary Form (Index 13)

    For inflected words, specify the dictionary (lemma) form.

    • Using Row IDs: Use the 0-based row index of the target word in the CSV file. Warning: Do not sort or insert rows after setting these IDs, as it will break the references.
    • Using Word Info: Provide a comma-separated string of 見出し (解析結果表示用),品詞1,品詞2,品詞3,品詞4,品詞 (活用型),品詞 (活用形),読み. This string must be enclosed in double quotes (").
    • Non-inflected words: Use *.

    Splitting (Indices 14, 15, 16)

    Used to define how words are split into A, B, or C units.

    • Index 14 (Type): Specify A, B, or C. Use * if no splitting is needed.
    • Index 15 (A-unit info): For types B or C. List component word IDs or word info strings separated by /.
      • To reference a user dictionary word, prefix the row ID with U (e.g., U5).
      • Word info strings must be enclosed in double quotes (").
    • Index 16 (B-unit info): For type C. Follows the same format as Index 15.

    Note: If a word is intended to be used only as a component for splitting and should not appear as a standalone word, set its connection IDs to -1.

    # Example of a word with splitting info (Type B)
    # モゲラ東京 is split into モゲラ and 東京
    モゲラ東京,5144,4792,4561,モゲラ東京,名詞,固有名詞,一般,*,*,*,モゲラトウキョウ,モゲラ東京,*,*,B,"U5/東京,名詞,固有名詞,地名,一般,*,*,トウキョウ",*,*
  3. Use chiTra for large-scale pre-trained language models

    develop

    chiTra is a library designed to use large-scale pre-trained language models in conjunction with the Sudachi tokenizer (specifically via SudachiPy). It is used for advanced NLP tasks requiring high-capacity models like NWJC.

    Available versions:

    • v1.0: Uses NWJC (148GB) and is compatible with Sudachi 0.6.2 and SudachiDict 20211220-core.
    • v1.1: Uses NWJC with additional cleaning (79GB) and is compatible with Sudachi 0.6.6 and SudachiDict 20220729-core.
  4. Extend Sudachi with Plugins

    develop

    Sudachi provides a plugin mechanism that allows you to hook into various stages of the morphological analysis process. This enables custom logic for text normalization, unknown word handling, and more.

    Common Plugin Hooks:

    • Input Text Correction: e.g., handling variant characters or orthographic correction.
    • Unknown Word Processing: e.g., adjusting handling based on character types.
    • Word Connection Processing: e.g., enforcing POS connection constraints or overriding costs.
    • Output Solution Correction: e.g., person name processing or adjusting splitting granularity.

    System-Provided Plugins include:

    • DefaultInputTextPlugin: Performs lowercase conversion and Unicode NFKC normalization.
    • String Normalization: Handles full-width/half-width, casing, and variant characters.
    • Long Vowel Normalization: Normalizes continuous long vowel symbols.
    • Reading Removal: Removes readings in parentheses.
    • Katakana Unknown Word Aggregation: Groups unknown Katakana words.
    • Person Name Correction: Estimates person names based on honorifics and context.
  5. Registering Headwords (TRIE) with Character Normalization

    develop

    When defining the headword (Index 0) for the TRIE, you must register it in its normalized form.

    Sudachi performs character normalization (lowercase conversion and Unicode NFKC normalization) before looking up the headword. If you register a word using a form that does not appear after normalization (e.g., using uppercase Latin characters), it will never match because Sudachi will look for the lowercase version internally.

    Note: Sudachi does not automatically apply normalization to the user dictionary headwords during loading; the creator must manually ensure the headwords are already in their normalized state.

  6. How character normalization works in Sudachi

    develop

    Sudachi performs character normalization to handle variations in text. The DefaultInputTextPlugin follows this order:

    1. Lowercase conversion via Character.toLowerCase().
    2. Unicode normalization using NFKC.

    Customizing normalization via rewrite.def: You can define custom rules in a rewrite.def file:

    • Ignore: Skip specific characters (e.g., # single code point: this character is skipped in character normalization\n髙).
    • Replace: Define mapping rules (e.g., # rewrite rule: <target> <replacement>\nA' Ā).

    Note: If normalization increases the character count, Sudachi may output morphemes with length 0 relative to the original input.

  7. Understand Sudachi Splitting Modes (A, B, and C)

    develop

    Sudachi supports three splitting modes that allow you to control the granularity of tokenization. This is useful for balancing precision and recall in search applications (e.g., using A and C together).

    • Mode A: Shortest units (equivalent to UniDic short units).
    • Mode B: Intermediate units.
    • Mode C: Longest units (equivalent to named entity/proper noun units).

    Example Comparison (Core Dictionary):

    • A: 選挙/管理/委員/会 (Election/Management/Committee)
    • B: 選挙/管理/委員会
    • C: 選挙管理委員会 (Election Management Committee)

    Example Comparison (Full Dictionary):

    • A: さっぽろ/テレビ/塔
    • B: さっぽろ/テレビ塔
    • C: さっぽろテレビ塔
  8. Configure Out-of-Vocabulary (OOV) handlers in Sudachi

    develop

    Sudachi uses OOV handlers to process words not present in the dictionary. A valid Sudachi configuration must include at least one OOV handler, or dictionary initialization will fail.

    Crucial Requirement: The last OOV handler in your oovPlugins list must be capable of producing a node for a boundary where no other words were found. The SimpleOovProviderPlugin is typically used for this purpose.

    You can reorder or override OOV plugins by specifying their class names in the oovPlugins array within your configuration file.

    {
      "oovPlugins": [
        {
          "class": "com.worksap.nlp.sudachi.SimpleOovProviderPlugin"
        },
        {
          "class" : "com.worksap.nlp.sudachi.MeCabOovProviderPlugin"
        }
      ]
    }
  9. Quickstart: Run Sudachi using pre-built binaries

    develop

    To run Sudachi without building from source, you need to download both the executable JAR and a dictionary file, then place the dictionary in the same directory as the JAR.

    Dictionary Types

    Sudachi provides three dictionary sizes:

    • full: Large
    • core: Medium
    • small: Small

    Setup Steps

    1. Download the Executable: Get the latest sudachi-[version]-executable.zip from the Sudachi Releases page and extract it.
    2. Download a Dictionary: Get a dictionary zip (e.g., sudachi-dictionary-[date]-core.zip) from the Sudachi Dictionary repository.
    3. Prepare the Dictionary: Extract the dictionary zip and move the .dic file (e.g., system_core.dic) into the folder where you extracted the Sudachi executable.
    4. Run: Execute the JAR using the Java runtime.

    Execution Examples

    Interactive mode:

    java -jar sudachi-[version].jar

    Piped input mode:

    echo "国会議事堂" | java -jar sudachi-[version].jar
    # Example for Linux/macOS
    $ unzip sudachi-0.7.3-executable.zip
    $ unzip sudachi-dictionary-20240409-core.zip
    $ mv sudachi-dictionary-20240409/system_core.dic ./
    $ java -jar sudachi-0.7.3.jar
    
    # Example for Windows Command Prompt
    # 1. Extract executable zip
    # 2. Extract dictionary zip
    # 3. Move system_core.dic into the executable folder
    # 4. Run:
    > java -jar sudachi-0.7.3.jar
  10. Run Sudachi Benchmark with multiple threads

    develop

    Use benchmark_multithread.sh to execute analysis using multiple threads simultaneously. Each thread is assigned an individual tokenizer instance generated from a single dictionary instance.

    • The analysis output is redirected to /dev/null.
    • Metadata including the target file and start/end timestamps is appended to data/benchmark.log.

    Usage:

    ./benchmark_multithread.sh corpus_file [num_thread [dict_type]]
    • corpus_file: The path to the text file you want to analyze.
    • num_thread: The number of threads to create (default: 3).
    • dict_type: The dictionary type to use (default: small).
    ./benchmark_multithread.sh my_corpus.txt 8 full
  11. Set up Sudachi Benchmark environment

    develop

    Use benchmark_setup.sh to build Sudachi and the Sudachi dictionaries. This script performs the following actions:

    1. Builds Sudachi and extracts the resulting sudachi-executable-[VERSION].zip into ../build/distributions/sudachi/.
    2. Builds the following dictionary files in the data/ directory: system_small.dic, system_core.dic, and system_full.dic.

    Note: You must place the downloaded Sudachi dictionary data in data/dictdata/ before running this script.

    Usage:

    ./benchmark_setup.sh [dict_version]
    • dict_version: The version of the Sudachi dictionary to use (default: 20240716).
    ./benchmark_setup.sh 20240716