iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐍

Building a Japanese Word Segmentation API for Use with Other Languages

に公開

Morphological Analysis (morphological analysis)

Japanese does not use spaces between words like English. However, in practice, there are many cases where we want to convert a sentence into a sequence of words, such as for document analysis or search. Morphological analyzers are the software that excel in these situations.

By using a morphological analyzer, you can split Japanese sentences into word units.

"私はエンジニアです"

[
	"私",
	"は",
	"エンジニア",
	"です",
]

In addition to word segmentation, morphological analyzers can provide part-of-speech (POS) tagging and lemmatization (restoring words to their base forms).

One use case for lemmatization is measuring the frequency of words with inflections. For example, if you segment "走る" (hashiru - to run) and "走らない" (hashiranai - not run) as they are, they become "走る" and "走ら". By restoring the base form, you can recognize them as the same word even if they are inflected.

Currently, in addition to dictionary-based segmentation methods, there are also methods using neural networks. The sample code in this article uses a dictionary-based method.

Dictionary-based morphological analyzers

Neural network (RNN-based) morphological analyzers

Supplement: n-gram and Challenges

n-gram is a simple approach. It involves defining a window and splitting the text into that specific length.

1-gram

"私はエンジニアです"

[
	"私",
	"は",
	"エ",
	"ン",
	"ジ",
	"ニ",
	"ア",
	"で",
	"す",
]

2-gram

"私はエンジニアです"

[
	"私は",
	"はエ",
	"エン",
	"ンジ",
	"ジニ",
	"ニア",
	"アで",
	"です",
]

3-gram

"私はエンジニアです"

[
	"私はエ",
	"はエン",
	"エンジ",
	"ンジニ",
	"ジニア",
	"ニアで",
	"アです",
]

As shown, n-gram is easy to use due to its simple algorithm, but it also has challenges.

One issue is that the vocabulary size for 2-grams can become excessively large, negatively impacting search performance.

Even with a small corpus limited to 50 Hiragana characters, there would be 50 * 50 = 2,500 possible vocabulary items.

Consider a larger corpus. In the Unicode BMP (Basic Multilingual Plane), the range is from 0x0000 to 0xFFFF, allowing for a maximum of 65,536 characters. Although some parts are unassigned, it is said that over 50,000 characters exist. Assuming 50,000 characters, there would be roughly 50,000 * 50,000 = 2,500,000,000 combinations. In reality, it could be even larger because variants such as old Japanese character forms reside outside the BMP range.

For these reasons, even 1-grams and 2-grams alone can lead to an enormous vocabulary, which affects search speed.

Further supplement: CJK(V) Unified Ideographs Extension A is within the BMP, but Extensions B through F are outside the BMP.

  1. hiragana (U+3040 to U+309F): Hiragana PDF
  2. katakana (U+30A0 to U+30FF): Katakana PDF
  3. katakana_half_width (U+FF65 to U+FF9F): Half-width Katakana PDF
  4. katakana_phonetic_extensions (U+31F0 to U+31FF): Katakana Phonetic Extensions PDF
  5. cjk_unified_ideographs (U+4E00 to U+9FFF): CJK Unified Ideographs PDF
  6. cjk_ideographs_extension_a (U+3400 to U+4DBF): CJK Extension A PDF
  7. cjk_ideographs_extension_b (U+20000 to U+2A6DF): CJK Extension B PDF
  8. cjk_ideographs_extension_c (U+2A700 to U+2B73F): CJK Extension C PDF
  9. cjk_ideographs_extension_d (U+2B740 to U+2b81F: CJK Extension D PDF
  10. cjk_ideographs_extension_e (U+2B820 to U+2CEAF): CJK Extension E PDF
  11. cjk_ideographs_extension_f (U+2CEB0 to U+2EBEF): CJK Extension F PDF
  12. japanese_punctuation (U+3000 to U+303F): Japanese Punctuation PDF

https://zenn.dev/shundeveloper/articles/b5cc85b4d1e7eb

Wanting to use Morphological Analysis Libraries in other languages

If you are using C++ or Java, you can implement your solution by using these libraries directly. However, for other languages, while wrapper libraries exist, there are concerns about whether they will be maintained, or you might even need to create a wrapper library yourself.

If the code is only intended for a short-term use, using such wrappers might not be a significant issue. However, for long-term use, it is preferable to use libraries that are actively maintained.

Using a Morphological Analyzer

While morphological analysis can be left to the language that already has the libraries, the challenge lies in how they interact with each other. Although it is possible to simply place them in the same environment, it is generally better to avoid creating a complex environment where the dependencies between software components become unclear.

If you want to keep the environment for the morphological analysis separate from the language environment using it, one approach is to communicate between systems via an API. Below is a demo of setting up two containers using Docker. A request is made from PHP to a Python API, utilizing morphological analysis in PHP.

For production, you should consider request limits and using a reverse proxy, but this demo is designed with a simple structure for illustrative purposes.

  • compose.yml
services:
  php:
    build: ./php
    tty: true
    volumes:
    - ./php/src:/root/opt/src
    working_dir: /root/opt/src
    command: ["sh"]

  python:
    build: ./python
    tty: true
    volumes:
    - ./python/src:/root/opt/src
    working_dir: /root/opt/src
    command: ["sh", "/root/opt/src/api/entrypoint.sh"]
  • app.py
from typing import List

from fastapi import FastAPI

from api.dto.tokenize_request_dto import TokenizeRequestDTO
from api.dto.tokenize_service_input_dto import TokenizeServiceInputDTO
from api.tokenize_service import run_tokenize_service

app: FastAPI = FastAPI()

@app.post("/tokenize")
def handler(dto: TokenizeRequestDTO) -> dict[str, list[list[str]]]:
    service_dto: TokenizeServiceInputDTO = TokenizeServiceInputDTO(
        sentences=dto.sentences
    )
    tokenized_sentences: List[List[str]] = run_tokenize_service(
        dto=service_dto
    ).tokenized_sentences
    return {"tokenized_sentences": tokenized_sentences}
  • tokenize_service.py
from api.dto.tokenize_service_input_dto import TokenizeServiceInputDTO
from api.dto.tokenize_service_output_dto import TokenizeServiceOutputDTO
from api.tokenize_repository import TokenizeRepository

def run_tokenize_service(dto: TokenizeServiceInputDTO) -> TokenizeServiceOutputDTO:
    tokenizer = TokenizeRepository(sentences=dto.sentences)
    return TokenizeServiceOutputDTO(tokenized_sentences=tokenizer.tokenize())
  • tokenize_repository.py

Finally, add a wrapper class for the library.

Here, we use a morphological analysis library called Janome. Janome is recommended for those who want to try it out immediately because the environment is ready just by running pip install janome. *1

from typing import List

from janome.tokenizer import Tokenizer
from pydantic import BaseModel, ConfigDict, Field

class TokenizeRepository(BaseModel):
    tokenizer: Tokenizer = Field(default_factory=Tokenizer)
    sentences: List[str]

    model_config = ConfigDict(arbitrary_types_allowed=True)

    def tokenize(self) -> List[List[str]]:
        res = [
            [str(token) for token in self.tokenizer.tokenize(text, wakati=True)]
            for text in self.sentences
        ]
        return res
  • While Janome is superior to other libraries in terms of environment setup, it has a drawback: slow execution speed. Therefore, it is not necessarily always the best choice. For example, if you are using a reasonably large scale of data for machine learning, using mecab-python3 would be more suitable as it runs faster. Please choose according to your requirements.

The DTOs are grouped together since they only carry data.

from typing import List

from pydantic import BaseModel

class TokenizeRequestDTO(BaseModel):
    sentences: List[str]

class TokenizeServiceInputDTO(BaseModel):
    sentences: List[str]

class TokenizeServiceOutputDTO(BaseModel):
    tokenized_sentences: List[List[str]]

PHP: Service Layer

<?php

declare(strict_types=1);

namespace Root\Src\Service\Tokenizer;

use RuntimeException;
use Root\Src\Infrastructure\FileReader\FileReader;
use Root\Src\Infrastructure\Fetcher\SendRequestToPythonApi;

final readonly class Tokenizer {
    /**
     * @var array<string> $sentences
     */
    public array $sentences;

    /**
     * @var array<array<string>> $tokenized_sentences
     */
    public array $tokenized_sentences;

    public function __construct(string $file_path) {
        $this->sentences = FileReader::readFileContents($file_path);
        $this->tokenized_sentences = $this->setTokenizedSentences();
    }

    /**
     * Send a POST request to the Python API to tokenize sentences.
     *
     * @return array<array<string>>
     * @throws RuntimeException If the request fails or the response format is invalid.
     */
    public function setTokenizedSentences(): array
    {
        return SendRequestToPythonApi::tokenize($this->sentences);
    }
}

PHP: Infrastructure Layer

<?php

declare(strict_types=1);

namespace Root\Src\Infrastructure\Fetcher;

use RuntimeException;

class SendRequestToPythonApi
{

    /**
     * Send a POST request to the Python API to tokenize sentences.
     *
     * @param array<string> $sentences Array of sentences to be tokenized.
     * @return array<array<string>> The response from the Python API containing tokenized sentences.
     * @throws RuntimeException If the request fails or the response format is invalid.
     */
    final public static function tokenize(array $sentences): array
    {
        // API endpoint
        $url = 'http://python:8000/tokenize';

        // Convert request data to JSON
        $data = json_encode(['sentences' => $sentences]);
        if ($data === false) {
            throw new RuntimeException('Failed to encode JSON.');
        }

        // Initialize cURL session
        $ch = curl_init($url);
        if ($ch === false) {
            throw new RuntimeException('Failed to initialize cURL session.');
        }

        // Set cURL options
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ]);

        // Execute request and get response
        $response = curl_exec($ch);

        // Check for errors
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('Request Error: ' . $error);
        }

        // Close the session
        curl_close($ch);

        // Check if response is a string
        if (!is_string($response)) {
            throw new RuntimeException('Response is not a valid string.');
        }

        // Decode and return the response
        $decodedResponse = json_decode($response, true);
        if ($decodedResponse === null) {
            throw new RuntimeException('Failed to decode JSON response.');
        }

        if (!is_array($decodedResponse) || !isset($decodedResponse['tokenized_sentences']) || !is_array($decodedResponse['tokenized_sentences'])) {
            throw new RuntimeException('Invalid response format.');
        }

        foreach ($decodedResponse['tokenized_sentences'] as $tokenizedSentence) {
            if (!is_array($tokenizedSentence) || array_filter($tokenizedSentence, 'is_string') !== $tokenizedSentence) {
                throw new RuntimeException('Invalid response format.');
            }
        }

        return $decodedResponse['tokenized_sentences'];
    }
}

Let's actually try morphological analysis in PHP.

$raw_file_path = __DIR__ . '/../data/raw/sentences.txt';
$tokenizer = new Tokenizer(file_path: $raw_file_path);

print_r(value: $tokenizer->sentences[0] . "\n");
print_r(value: $tokenizer->tokenized_sentences[0]);

You can see that it is successfully segmented into word units.

青い空に白い雲が浮かんでいるのを見て、気持ちが落ち着いた。
Array
(
    [0] => 青い
    [1] => 空
    [2] => に
    [3] => 白い
    [4] => 雲
    [5] => が
    [6] => 浮かん
    [7] => で
    [8] => いる
    [9] => の
    [10] => を
    [11] => 見
    [12] => て
    [13] => 、
    [14] => 気持ち
    [15] => が
    [16] => 落ち着い
    [17] => た
    [18] => 。
)

Discussion