From e694a506729fcc945a4df68d852844f7dcf2a0dc Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 23:40:25 +0100 Subject: [PATCH 1/2] Add missing docstrings and enforce D1 Add missing docstrings and enforce D1 - Add 273 docstrings to public modules, classes, methods, and functions - Remove three `pass` lines made redundant by the new docstrings - Enable the ruff D1 rules for `pythainlp/` (tests, notebooks, examples, build_tools, and docs are exempt) - Log docstring and code mismatches found in the ROADMAP Signed-off-by: Arthit Suriyawongkul --- pyproject.toml | 9 ++- pythainlp/__init__.py | 3 + pythainlp/__main__.py | 3 + pythainlp/ancient/aksonhan.py | 2 + pythainlp/ancient/currency.py | 2 + pythainlp/augment/lm/fasttext.py | 2 + pythainlp/augment/lm/phayathaibert.py | 16 ++++ pythainlp/augment/lm/wangchanberta.py | 13 ++++ pythainlp/augment/word2vec/bpemb_wv.py | 9 +++ pythainlp/augment/word2vec/core.py | 4 + pythainlp/augment/word2vec/ltw2v.py | 3 + pythainlp/augment/word2vec/thai2fit.py | 3 + pythainlp/augment/wordnet.py | 2 +- pythainlp/benchmarks/word_tokenization.py | 3 + pythainlp/chat/core.py | 4 + pythainlp/chunk/crfchunk.py | 5 ++ pythainlp/classify/param_free.py | 16 ++++ pythainlp/cli/__init__.py | 7 ++ pythainlp/cli/benchmark.py | 15 ++++ pythainlp/cli/data.py | 10 +++ pythainlp/cli/misspell.py | 7 ++ pythainlp/cli/soundex.py | 7 ++ pythainlp/cli/tag.py | 18 +++++ pythainlp/cli/tokenize.py | 24 ++++++ pythainlp/coref/core.py | 2 + pythainlp/coref/han_coref.py | 12 +++ pythainlp/corpus/common.py | 8 ++ pythainlp/el/core.py | 4 + pythainlp/generate/core.py | 3 + pythainlp/generate/wangchanglm.py | 13 ++++ pythainlp/khavee/__init__.py | 2 + pythainlp/khavee/core.py | 2 + pythainlp/lm/__init__.py | 1 + pythainlp/lm/qwen3.py | 2 + pythainlp/lm/text_util.py | 2 + pythainlp/morpheme/word_formation.py | 2 + pythainlp/parse/attaparse_engine.py | 13 ++++ pythainlp/parse/core.py | 2 + pythainlp/parse/esupar_engine.py | 17 ++++ pythainlp/parse/spacy_thai_engine.py | 17 ++++ pythainlp/parse/transformers_ud.py | 20 +++++ pythainlp/parse/ud_goeswith.py | 20 +++++ pythainlp/phayathaibert/core.py | 26 +++++++ pythainlp/soundex/complete_soundex.py | 1 + pythainlp/soundex/sound.py | 2 + pythainlp/spell/phunspell.py | 15 ++++ pythainlp/spell/pn.py | 2 + pythainlp/spell/symspellpy.py | 33 ++++++++ pythainlp/spell/tltk.py | 7 ++ .../spell/wanchanberta_thai_grammarly.py | 38 +++++++++ pythainlp/spell/words_spelling_correction.py | 3 + pythainlp/summarize/freq.py | 17 ++++ pythainlp/summarize/keybert.py | 7 ++ pythainlp/summarize/mt5.py | 9 +++ pythainlp/tag/blackboard.py | 2 + pythainlp/tag/crfchunk.py | 5 ++ pythainlp/tag/named_entity.py | 22 ++++++ pythainlp/tag/orchid.py | 8 ++ pythainlp/tag/pos_tag.py | 2 + pythainlp/tag/tltk.py | 12 +++ pythainlp/tag/wangchanberta_onnx.py | 37 +++++++++ pythainlp/tokenize/attacut.py | 14 ++++ pythainlp/tokenize/han_solo.py | 34 ++++++++ pythainlp/tokenize/longest.py | 14 ++++ pythainlp/tokenize/multi_cut.py | 15 ++++ pythainlp/tokenize/nlpo3.py | 2 + pythainlp/tokenize/ssg.py | 2 + pythainlp/tokenize/thai2fit.py | 1 + pythainlp/tokenize/thaisumcut.py | 24 ++++++ pythainlp/tokenize/tltk.py | 23 ++++++ pythainlp/tokenize/wtsplit.py | 11 +++ pythainlp/tools/__init__.py | 3 + pythainlp/tools/misspell.py | 6 ++ pythainlp/translate/core.py | 1 + pythainlp/translate/en_th.py | 10 +++ pythainlp/translate/small100.py | 9 +++ pythainlp/translate/th_fr.py | 7 ++ pythainlp/translate/tokenization_small100.py | 71 +++++++++++++++++ pythainlp/translate/word2word_translate.py | 2 + pythainlp/translate/zh_th.py | 14 ++++ pythainlp/transliterate/core.py | 2 + pythainlp/transliterate/ipa.py | 21 +++++ pythainlp/transliterate/pali.py | 2 + pythainlp/transliterate/spoonerism.py | 2 + pythainlp/transliterate/thai2rom.py | 71 +++++++++++++++++ pythainlp/transliterate/thai2rom_onnx.py | 23 ++++++ pythainlp/transliterate/thaig2p.py | 77 +++++++++++++++++++ pythainlp/transliterate/thaig2p_v2.py | 20 +++++ pythainlp/transliterate/tltk.py | 16 ++++ pythainlp/transliterate/umt5_thaig2p.py | 20 +++++ pythainlp/transliterate/w2p.py | 14 ++++ pythainlp/transliterate/wunsen.py | 1 + pythainlp/ulmfit/tokenizer.py | 29 ++++++- pythainlp/util/encoding.py | 2 + pythainlp/util/keywords.py | 2 + pythainlp/util/lcs.py | 2 + pythainlp/util/morse.py | 2 + pythainlp/util/pronounce.py | 2 + pythainlp/util/spell_words.py | 2 + pythainlp/util/thai_lunar_date.py | 28 +++++++ pythainlp/util/trie.py | 28 +++++++ pythainlp/wangchanberta/core.py | 6 ++ pythainlp/word_vector/core.py | 7 ++ pythainlp/wsd/core.py | 2 + working-docs/ROADMAP.md | 22 ++++-- 105 files changed, 1233 insertions(+), 10 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5ae061be5..648bf2c98 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,6 +434,7 @@ skip-magic-trailing-comma = false # `# phase2-todo`. mccabe.max-complexity = 10 select = [ + "D1", "E", "F", "I", @@ -471,8 +472,12 @@ extend-ignore = ["B905", "E501", "RET504", "SIM108", "SIM117"] "pythainlp/tokenize/__init__.py" = ["E402"] # S101 (assert) is not allowed in production code. Tests and notebooks may use it. # B010 (setattr) is for attributes that tests set on purpose. -"tests/**" = ["B010", "S101"] -"notebooks/**" = ["S101"] +# D1 (missing docstring) applies to the pythainlp package only. +"tests/**" = ["B010", "D1", "S101"] +"notebooks/**" = ["D1", "S101"] +"examples/**" = ["D1"] +"build_tools/**" = ["D1"] +"docs/**" = ["D1"] [tool.tox] env_list = ["py39", "py310", "py311", "py312", "py313", "py314", "pypy310", "pypy311", "ruff", "flake8", "mypy"] diff --git a/pythainlp/__init__.py b/pythainlp/__init__.py index 397fe7fcf..9a8aa568b 100644 --- a/pythainlp/__init__.py +++ b/pythainlp/__init__.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""PyThaiNLP, a Thai natural language processing library.""" + __version__ = "5.3.8" thai_consonants: str = ( diff --git a/pythainlp/__main__.py b/pythainlp/__main__.py index 98bb0ab66..9b1140f09 100644 --- a/pythainlp/__main__.py +++ b/pythainlp/__main__.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""Run the PyThaiNLP command line with ``python -m pythainlp``.""" + from __future__ import annotations import argparse diff --git a/pythainlp/ancient/aksonhan.py b/pythainlp/ancient/aksonhan.py index 4c5d21b08..77a705714 100644 --- a/pythainlp/ancient/aksonhan.py +++ b/pythainlp/ancient/aksonhan.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Convert AksonHan (อักษรหัน) words to current Thai spelling.""" + from __future__ import annotations from itertools import chain diff --git a/pythainlp/ancient/currency.py b/pythainlp/ancient/currency.py index 1e3cdfd6f..96ab841a8 100644 --- a/pythainlp/ancient/currency.py +++ b/pythainlp/ancient/currency.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Convert values between ancient Thai currency units.""" + from __future__ import annotations diff --git a/pythainlp/augment/lm/fasttext.py b/pythainlp/augment/lm/fasttext.py index c0f9a4dea..33c7594d4 100644 --- a/pythainlp/augment/lm/fasttext.py +++ b/pythainlp/augment/lm/fasttext.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using fastText.""" + from __future__ import annotations import itertools diff --git a/pythainlp/augment/lm/phayathaibert.py b/pythainlp/augment/lm/phayathaibert.py index 634bc26d1..cbe3008e7 100644 --- a/pythainlp/augment/lm/phayathaibert.py +++ b/pythainlp/augment/lm/phayathaibert.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using PhayaThaiBERT.""" + from __future__ import annotations import random @@ -16,12 +18,15 @@ class ThaiTextAugmenter: + """Augment Thai text using PhayaThaiBERT.""" + tokenizer: "AutoTokenizer" model_for_masked_lm: "AutoModelForMaskedLM" model: "Pipeline" processor: "ThaiTextProcessor" def __init__(self) -> None: + """Initialize the PhayaThaiBERT fill-mask pipeline.""" from transformers import ( AutoModelForMaskedLM, AutoTokenizer, @@ -48,6 +53,17 @@ def generate( max_length: int = 3, sample: bool = False, ) -> str: + """ + Generate text by repeatedly filling a mask token. + + :param str sample_text: text to start from + :param int word_rank: rank of the predicted word to use in each step + :param int max_length: number of mask-filling steps + :param bool sample: pick a random one of the top five predictions + instead of the one at ``word_rank`` + :return: generated text + :rtype: str + """ sample_txt = sample_text final_text = "" diff --git a/pythainlp/augment/lm/wangchanberta.py b/pythainlp/augment/lm/wangchanberta.py index 2e19b29ea..8357296ca 100644 --- a/pythainlp/augment/lm/wangchanberta.py +++ b/pythainlp/augment/lm/wangchanberta.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using WangchanBERTa.""" + from __future__ import annotations from typing import TYPE_CHECKING @@ -12,6 +14,8 @@ class Thai2transformersAug: + """Augment Thai text using WangchanBERTa.""" + model_name: str target_tokenizer: type["CamembertTokenizer"] tokenizer: "CamembertTokenizer" @@ -20,6 +24,7 @@ class Thai2transformersAug: input_text: str def __init__(self) -> None: + """Initialize the WangchanBERTa tokenizer and fill-mask pipeline.""" from transformers import ( CamembertTokenizer, pipeline, @@ -49,6 +54,14 @@ def __init__(self) -> None: def generate( self, sentence: str, num_replace_tokens: int = 3 ) -> list[str]: + """ + Generate sentences by filling masked tokens. + + :param str sentence: Thai text to augment + :param int num_replace_tokens: number of tokens to replace + :return: list of generated sentences + :rtype: list[str] + """ sent2: list[str] = [] self.input_text: str = sentence sent = [ diff --git a/pythainlp/augment/word2vec/bpemb_wv.py b/pythainlp/augment/word2vec/bpemb_wv.py index 6ca208b24..61206e1f1 100644 --- a/pythainlp/augment/word2vec/bpemb_wv.py +++ b/pythainlp/augment/word2vec/bpemb_wv.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using word2vec from BPEmb.""" + from __future__ import annotations from typing import TYPE_CHECKING, cast @@ -31,6 +33,13 @@ class BPEmbAug: def __init__( self, lang: str = "th", vs: int = 100000, dim: int = 300 ) -> None: + """ + Initialize the BPEmb word2vec augmenter. + + :param str lang: language code + :param int vs: vocabulary size + :param int dim: embedding dimension + """ from bpemb import BPEmb self.bpemb_temp: BPEmb = BPEmb(lang=lang, dim=dim, vs=vs) diff --git a/pythainlp/augment/word2vec/core.py b/pythainlp/augment/word2vec/core.py index d95a3264b..b82704f5b 100644 --- a/pythainlp/augment/word2vec/core.py +++ b/pythainlp/augment/word2vec/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment text using word2vec word vectors.""" + from __future__ import annotations import itertools @@ -19,6 +21,8 @@ def filter(self, record: logging.LogRecord) -> bool: class Word2VecAug: + """Augment text using word2vec word vectors.""" + tokenizer: Callable[[str], list[str]] model: "KeyedVectors" dict_wv: list[str] diff --git a/pythainlp/augment/word2vec/ltw2v.py b/pythainlp/augment/word2vec/ltw2v.py index e0e9c8d56..83bf2a5dd 100644 --- a/pythainlp/augment/word2vec/ltw2v.py +++ b/pythainlp/augment/word2vec/ltw2v.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using word2vec from LTW2V.""" + from __future__ import annotations from typing import Optional @@ -23,6 +25,7 @@ class LTW2VAug: aug: Word2VecAug def __init__(self) -> None: + """Initialize the LTW2V word2vec augmenter.""" self.ltw2v_wv: Optional[str] = get_corpus_path("ltw2v") self.load_w2v() diff --git a/pythainlp/augment/word2vec/thai2fit.py b/pythainlp/augment/word2vec/thai2fit.py index d3dbe9e9d..eee7a4e26 100644 --- a/pythainlp/augment/word2vec/thai2fit.py +++ b/pythainlp/augment/word2vec/thai2fit.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Augment Thai text using word2vec from Thai2Fit.""" + from __future__ import annotations from typing import Optional @@ -22,6 +24,7 @@ class Thai2fitAug: aug: Word2VecAug def __init__(self) -> None: + """Initialize the Thai2Fit word2vec augmenter.""" self.thai2fit_wv: Optional[str] = get_corpus_path("thai2fit_wv") self.load_w2v() diff --git a/pythainlp/augment/wordnet.py b/pythainlp/augment/wordnet.py index 95136ed18..f8f00490d 100644 --- a/pythainlp/augment/wordnet.py +++ b/pythainlp/augment/wordnet.py @@ -142,7 +142,7 @@ class WordNetAug: temp: list[str] def __init__(self) -> None: - pass + """Initialize the WordNet augmenter.""" def find_synonyms( self, diff --git a/pythainlp/benchmarks/word_tokenization.py b/pythainlp/benchmarks/word_tokenization.py index 88d599d31..3700b4b47 100644 --- a/pythainlp/benchmarks/word_tokenization.py +++ b/pythainlp/benchmarks/word_tokenization.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""Benchmark metrics for word tokenization.""" + from __future__ import annotations import re diff --git a/pythainlp/chat/core.py b/pythainlp/chat/core.py index 3465bb053..7383128b4 100644 --- a/pythainlp/chat/core.py +++ b/pythainlp/chat/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Chatbot using the WangChanGLM model.""" + from __future__ import annotations from typing import TYPE_CHECKING, Optional @@ -14,6 +16,8 @@ class ChatBotModel: + """Chat with the WangChanGLM model.""" + history: list[tuple[str, str]] model: "WangChanGLM" diff --git a/pythainlp/chunk/crfchunk.py b/pythainlp/chunk/crfchunk.py index da9938aaf..4b71b904c 100644 --- a/pythainlp/chunk/crfchunk.py +++ b/pythainlp/chunk/crfchunk.py @@ -103,6 +103,11 @@ class CRFChunkParser: xseq: list[dict[str, Union[str, bool]]] def __init__(self, corpus: str = "orchidpp") -> None: + """ + Initialize the chunker. + + :param str corpus: corpus for the CRF model + """ self.corpus = corpus self._model_file_ctx = None self.load_model(self.corpus) diff --git a/pythainlp/classify/param_free.py b/pythainlp/classify/param_free.py index 2197ce473..df874d766 100644 --- a/pythainlp/classify/param_free.py +++ b/pythainlp/classify/param_free.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""Parameter-free text classification.""" + from __future__ import annotations import gzip @@ -33,6 +36,13 @@ def __init__( training_data: Optional[list[tuple[str, str]]] = None, model_path: str = "", ) -> None: + """ + Initialize the model. + + :param Optional[list[tuple[str, str]]] training_data: list of + (text, label) tuples + :param str model_path: path to load a saved model from + """ import numpy as np if model_path: @@ -42,6 +52,12 @@ def __init__( self.cx2_list = self.train() def train(self) -> list[int]: + """ + Compute the compressed length of each training text. + + :return: compressed length of each training text + :rtype: list[int] + """ temp_list = [] for i in range(len(self.training_data)): temp_list.append( diff --git a/pythainlp/cli/__init__.py b/pythainlp/cli/__init__.py index 4a966d05e..0753551f0 100644 --- a/pythainlp/cli/__init__.py +++ b/pythainlp/cli/__init__.py @@ -27,6 +27,13 @@ def make_usage(command: str) -> dict[str, str]: + """ + Build the usage arguments of a command. + + :param str command: command name + :return: ``prog`` and ``usage`` strings for argparse + :rtype: dict[str, str] + """ prog = f"{CLI_NAME} {command}" return {"prog": prog, "usage": f"{prog} [options]"} diff --git a/pythainlp/cli/benchmark.py b/pythainlp/cli/benchmark.py index 3b7945da6..e43afd548 100644 --- a/pythainlp/cli/benchmark.py +++ b/pythainlp/cli/benchmark.py @@ -24,7 +24,14 @@ def _read_file(path: str) -> list[str]: class App: + """Parse and run the ``benchmark`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="benchmark", description=( @@ -51,7 +58,15 @@ def __init__(self, argv: Sequence[str]) -> None: class WordTokenizationBenchmark: + """Parse and run the word tokenization benchmark.""" + def __init__(self, name: str, argv: Sequence[str]) -> None: + """ + Initialize the benchmark. + + :param str name: task name + :param Sequence[str] argv: task options + """ parser = argparse.ArgumentParser(**cli.make_usage("benchmark " + name)) # type: ignore[arg-type] parser.add_argument( diff --git a/pythainlp/cli/data.py b/pythainlp/cli/data.py index c8a2483a2..0e60e7bc5 100644 --- a/pythainlp/cli/data.py +++ b/pythainlp/cli/data.py @@ -16,7 +16,14 @@ class App: + """Parse and run the ``data`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="data", description="Manage dataset/corpus.", @@ -50,6 +57,7 @@ def __init__(self, argv: Sequence[str]) -> None: getattr(self, args.subcommand)(argv) def get(self, argv: Sequence[str]) -> None: + """Download a dataset.""" parser = argparse.ArgumentParser( description="Download a dataset", usage="thainlp data get ", @@ -66,6 +74,7 @@ def get(self, argv: Sequence[str]) -> None: print("Not found.") def rm(self, argv: Sequence[str]) -> None: + """Remove a dataset.""" parser = argparse.ArgumentParser( description="Remove a dataset", usage="thainlp data rm ", @@ -82,6 +91,7 @@ def rm(self, argv: Sequence[str]) -> None: print("Not found.") def info(self, argv: Sequence[str]) -> None: + """Print information about a dataset.""" parser = argparse.ArgumentParser( description="Print information about a dataset", usage="thainlp data info ", diff --git a/pythainlp/cli/misspell.py b/pythainlp/cli/misspell.py index 871295860..5b6bc9ca1 100644 --- a/pythainlp/cli/misspell.py +++ b/pythainlp/cli/misspell.py @@ -17,7 +17,14 @@ class App: + """Parse and run the ``misspell`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="misspell", description="Generate misspelled texts from a given file.", diff --git a/pythainlp/cli/soundex.py b/pythainlp/cli/soundex.py index fc820d96e..e50160c1f 100644 --- a/pythainlp/cli/soundex.py +++ b/pythainlp/cli/soundex.py @@ -20,7 +20,14 @@ class App: + """Parse and run the ``soundex`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="soundex", description="Convert a text to its sound-based index.", diff --git a/pythainlp/cli/tag.py b/pythainlp/cli/tag.py index c41ba8a3f..ba99a7978 100644 --- a/pythainlp/cli/tag.py +++ b/pythainlp/cli/tag.py @@ -17,11 +17,19 @@ class SubAppBase: + """Base class of tagging commands.""" + separator: str run: Callable[[list[str]], list[tuple[str, str]]] args: argparse.Namespace def __init__(self, name: str, argv: Sequence[str]) -> None: + """ + Initialize the tagging command. + + :param str name: tagging type name + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser(**cli.make_usage("tag " + name)) # type: ignore[arg-type] parser.add_argument( "text", @@ -48,10 +56,13 @@ def __init__(self, name: str, argv: Sequence[str]) -> None: class POSTaggingApp(SubAppBase): + """Parse and run the part-of-speech tagging command.""" + separator: str run: Callable[[list[str]], list[tuple[str, str]]] def __init__(self, *args: str, **kwargs: str) -> None: + """Initialize the command.""" self.separator: str = "|" self.run: Callable[[list[str]], list[tuple[str, str]]] = pos_tag @@ -59,7 +70,14 @@ def __init__(self, *args: str, **kwargs: str) -> None: class App: + """Parse and run the ``tag`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="tag", description="Annotate a text with linguistic information", diff --git a/pythainlp/cli/tokenize.py b/pythainlp/cli/tokenize.py index 214f68f0e..74964c6ff 100644 --- a/pythainlp/cli/tokenize.py +++ b/pythainlp/cli/tokenize.py @@ -29,6 +29,8 @@ class SubAppBase: + """Base class of tokenization commands.""" + separator: str algorithm: str run: Callable[..., Any] @@ -36,6 +38,12 @@ class SubAppBase: args: argparse.Namespace def __init__(self, name: str, argv: Sequence[str]) -> None: + """ + Initialize the tokenization command. + + :param str name: tokenization type name + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser(**cli.make_usage("tokenize " + name)) # type: ignore[arg-type] parser.add_argument( "text", @@ -86,7 +94,10 @@ def __init__(self, name: str, argv: Sequence[str]) -> None: class WordTokenizationApp(SubAppBase): + """Parse and run the word tokenization command.""" + def __init__(self, *args: str, **kwargs: str) -> None: + """Initialize the command.""" self.keep_whitespace: bool = True self.algorithm: str = DEFAULT_WORD_TOKENIZE_ENGINE self.separator: str = DEFAULT_WORD_TOKEN_SEPARATOR @@ -95,7 +106,10 @@ def __init__(self, *args: str, **kwargs: str) -> None: class SentenceTokenizationApp(SubAppBase): + """Parse and run the sentence tokenization command.""" + def __init__(self, *args: str, **kwargs: str) -> None: + """Initialize the command.""" self.keep_whitespace: bool = True self.algorithm: str = DEFAULT_SENT_TOKENIZE_ENGINE self.separator: str = DEFAULT_SENT_TOKEN_SEPARATOR @@ -104,7 +118,10 @@ def __init__(self, *args: str, **kwargs: str) -> None: class SubwordTokenizationApp(SubAppBase): + """Parse and run the subword tokenization command.""" + def __init__(self, *args: str, **kwargs: str) -> None: + """Initialize the command.""" self.keep_whitespace: bool = True self.algorithm: str = DEFAULT_SUBWORD_TOKENIZE_ENGINE self.separator: str = DEFAULT_SUBWORD_TOKEN_SEPARATOR @@ -113,7 +130,14 @@ def __init__(self, *args: str, **kwargs: str) -> None: class App: + """Parse and run the ``tokenize`` command.""" + def __init__(self, argv: Sequence[str]) -> None: + """ + Initialize the command. + + :param Sequence[str] argv: command line arguments + """ parser = argparse.ArgumentParser( prog="tokenize", description="Break a text into small units (tokens).", diff --git a/pythainlp/coref/core.py b/pythainlp/coref/core.py index f7c5e5fd6..89d5341f5 100644 --- a/pythainlp/coref/core.py +++ b/pythainlp/coref/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Coreference resolution for Thai text.""" + from __future__ import annotations from typing import Any, Union, cast diff --git a/pythainlp/coref/han_coref.py b/pythainlp/coref/han_coref.py index 6d2b0e94f..6f9a23ac2 100644 --- a/pythainlp/coref/han_coref.py +++ b/pythainlp/coref/han_coref.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Han-Coref: Thai coreference resolution model.""" + from __future__ import annotations from typing import TYPE_CHECKING, Optional @@ -12,9 +14,19 @@ class HanCoref(FastCoref): + """Coreference resolver using the Han-Coref model.""" + def __init__( self, device: str = "cpu", nlp: Optional[Language] = None ) -> None: + """ + Initialize the Han-Coref resolver. + + :param str device: device to run the model on + ("cpu", "cuda", and others) + :param Optional[spacy.language.Language] nlp: spaCy pipeline to use; + a blank Thai pipeline is created if ``None`` + """ super().__init__( model_name="pythainlp/han-coref-v1.0", device=device, nlp=nlp ) diff --git a/pythainlp/corpus/common.py b/pythainlp/corpus/common.py index 41f6c9009..afcfcd6b5 100644 --- a/pythainlp/corpus/common.py +++ b/pythainlp/corpus/common.py @@ -464,6 +464,14 @@ def thai_synonyms() -> dict[str, Union[list[str], list[list[str]]]]: def thai_synonym() -> dict[str, Union[list[str], list[list[str]]]]: + """ + Return Thai synonyms (deprecated). + + Use :func:`thai_synonyms` instead. + + :return: words, parts of speech, and synonym groups + :rtype: dict[str, Union[list[str], list[list[str]]]] + """ warn_deprecation( "pythainlp.corpus.thai_synonym", "pythainlp.corpus.thai_synonyms", diff --git a/pythainlp/el/core.py b/pythainlp/el/core.py index fc18744cc..6798c9b37 100644 --- a/pythainlp/el/core.py +++ b/pythainlp/el/core.py @@ -1,12 +1,16 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Entity linking.""" + from __future__ import annotations from typing import Any, Union class EntityLinker: + """Link entities in Thai text to a knowledge base.""" + def __init__( self, model_name: str = "bela", diff --git a/pythainlp/generate/core.py b/pythainlp/generate/core.py index 33b52cdd2..16572a177 100644 --- a/pythainlp/generate/core.py +++ b/pythainlp/generate/core.py @@ -67,6 +67,7 @@ class Unigram: _word_prob: dict[str, float] def __init__(self, name: str = "tnc") -> None: + """Initialize the unigram model.""" if name == "tnc": self.counts: dict[str, int] = tnc_word_freqs_unigram() elif name == "ttc": @@ -166,6 +167,7 @@ class Bigram: words: list[str] def __init__(self, name: str = "tnc") -> None: + """Initialize the bigram model.""" if name == "tnc": self.uni: dict[str, int] = tnc_word_freqs_unigram() self.bi: dict[tuple[str, str], int] = tnc_word_freqs_bigram() @@ -265,6 +267,7 @@ class Trigram: words: list[str] def __init__(self, name: str = "tnc") -> None: + """Initialize the trigram model.""" if name == "tnc": self.uni: dict[str, int] = tnc_word_freqs_unigram() self.bi: dict[tuple[str, str], int] = tnc_word_freqs_bigram() diff --git a/pythainlp/generate/wangchanglm.py b/pythainlp/generate/wangchanglm.py index 708ed1cf7..214bbf088 100644 --- a/pythainlp/generate/wangchanglm.py +++ b/pythainlp/generate/wangchanglm.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Generate Thai text using the WangChanGLM model.""" + from __future__ import annotations import re @@ -15,6 +17,8 @@ class WangChanGLM: + """Generate Thai text using the WangChanGLM model.""" + exclude_pattern: "re.Pattern[str]" stop_token: str PROMPT_DICT: dict[str, str] @@ -27,6 +31,7 @@ class WangChanGLM: exclude_ids: list[int] def __init__(self) -> None: + """Initialize the WangChanGLM settings.""" warn_deprecation( "pythainlp.generate.wangchanglm.WangChanGLM", deprecated_version="5.3.8", @@ -43,6 +48,14 @@ def __init__(self) -> None: } def is_exclude(self, text: str) -> bool: + """ + Check whether text contains a non-Thai character. + + :param str text: text to check + :return: ``True`` if the text contains a character outside the Thai + range, otherwise ``False`` + :rtype: bool + """ return bool(self.exclude_pattern.search(text)) def load_model( diff --git a/pythainlp/khavee/__init__.py b/pythainlp/khavee/__init__.py index 158125ddc..561c5ccb2 100644 --- a/pythainlp/khavee/__init__.py +++ b/pythainlp/khavee/__init__.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Verification of Thai poetry (khavee) rules.""" + __all__: list[str] = ["KhaveeVerifier"] from pythainlp.khavee.core import KhaveeVerifier diff --git a/pythainlp/khavee/core.py b/pythainlp/khavee/core.py index ac0883d88..f9aa99d31 100644 --- a/pythainlp/khavee/core.py +++ b/pythainlp/khavee/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Verifier for Thai poetry (khavee) principles.""" + from __future__ import annotations from typing import Optional, Union diff --git a/pythainlp/lm/__init__.py b/pythainlp/lm/__init__.py index f09558359..18ea18ad5 100644 --- a/pythainlp/lm/__init__.py +++ b/pythainlp/lm/__init__.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Language model utilities for Thai text.""" __all__: list[str] = [ "calculate_ngram_counts", diff --git a/pythainlp/lm/qwen3.py b/pythainlp/lm/qwen3.py index e379a6d8d..83ec38130 100644 --- a/pythainlp/lm/qwen3.py +++ b/pythainlp/lm/qwen3.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Generate Thai text using the Qwen3 language model.""" from __future__ import annotations @@ -21,6 +22,7 @@ class Qwen3: """ def __init__(self) -> None: + """Initialize Qwen3 without a loaded model.""" self.model: Optional["PreTrainedModel"] = None self.tokenizer: Optional["PreTrainedTokenizerBase"] = None self.device: Optional[str] = None diff --git a/pythainlp/lm/text_util.py b/pythainlp/lm/text_util.py index 290a8b5bb..0cc83c1d5 100644 --- a/pythainlp/lm/text_util.py +++ b/pythainlp/lm/text_util.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Count and remove repeated n-grams in lists of words.""" + from __future__ import annotations diff --git a/pythainlp/morpheme/word_formation.py b/pythainlp/morpheme/word_formation.py index c8d8e59f4..880f193f4 100644 --- a/pythainlp/morpheme/word_formation.py +++ b/pythainlp/morpheme/word_formation.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Thai word formation functions.""" + from __future__ import annotations from typing import Optional diff --git a/pythainlp/parse/attaparse_engine.py b/pythainlp/parse/attaparse_engine.py index 9a96c7120..dba383ff0 100644 --- a/pythainlp/parse/attaparse_engine.py +++ b/pythainlp/parse/attaparse_engine.py @@ -23,12 +23,25 @@ class Parse: + """Dependency parser using Attaparse.""" + def __init__(self) -> None: + """Initialize the Attaparse model.""" self.nlp: Pipeline = load_model() def __call__( # noqa: CCR001 # phase2-todo self, text: str, tag: str = "str" ) -> Union[List[List[str]], str]: + """ + Parse the dependency structure of a text. + + :param str text: text to be parsed + :param str tag: output type, ``"str"`` (CoNLL-U text, default) + or ``"list"`` + :return: CoNLL-U text if ``tag`` is ``"str"``, otherwise a list of + lists of fields + :rtype: Union[List[List[str]], str] + """ doc = depparse(text, self.nlp) rows = [] for sent in doc.sentences: diff --git a/pythainlp/parse/core.py b/pythainlp/parse/core.py index 21c34db29..0177b7f9f 100644 --- a/pythainlp/parse/core.py +++ b/pythainlp/parse/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Dependency parsing for Thai text.""" + from __future__ import annotations from typing import Any, List, Optional, Union diff --git a/pythainlp/parse/esupar_engine.py b/pythainlp/parse/esupar_engine.py index 814757514..e53d778eb 100644 --- a/pythainlp/parse/esupar_engine.py +++ b/pythainlp/parse/esupar_engine.py @@ -22,7 +22,14 @@ class Parse: + """Dependency parser using esupar.""" + def __init__(self, model: Optional[str] = "th") -> None: + """ + Initialize the esupar model. + + :param Optional[str] model: model to load; ``"th"`` if ``None`` + """ if model is None: model = "th" self.nlp: Model = esupar.load(model) @@ -30,6 +37,16 @@ def __init__(self, model: Optional[str] = "th") -> None: def __call__( self, text: str, tag: str = "str" ) -> Union[List[List[str]], str]: + """ + Parse the dependency structure of a text. + + :param str text: text to be parsed + :param str tag: output type, ``"str"`` (CoNLL-U text, default) + or ``"list"`` + :return: CoNLL-U text if ``tag`` is ``"str"``, otherwise a list of + lists of fields + :rtype: Union[List[List[str]], str] + """ _data = str(self.nlp(text)) if tag == "list": _temp = _data.splitlines() diff --git a/pythainlp/parse/spacy_thai_engine.py b/pythainlp/parse/spacy_thai_engine.py index 9b0c5c5c2..9d24fe9ac 100644 --- a/pythainlp/parse/spacy_thai_engine.py +++ b/pythainlp/parse/spacy_thai_engine.py @@ -17,12 +17,29 @@ class Parse: + """Dependency parser using spacy_thai.""" + def __init__(self, model: str = "th") -> None: + """ + Initialize the spacy_thai model. + + :param str model: model name; not used, the default model is loaded + """ self.nlp: Language = spacy_thai.load() def __call__( self, text: str, tag: str = "str" ) -> Union[List[List[str]], str]: + """ + Parse the dependency structure of a text. + + :param str text: text to be parsed + :param str tag: output type, ``"str"`` (CoNLL-U text, default) + or ``"list"`` + :return: CoNLL-U text if ``tag`` is ``"str"``, otherwise a list of + lists of fields + :rtype: Union[List[List[str]], str] + """ doc = self.nlp(text) _text = [] if tag == "list": diff --git a/pythainlp/parse/transformers_ud.py b/pythainlp/parse/transformers_ud.py index 6c72f1642..9fc765638 100644 --- a/pythainlp/parse/transformers_ud.py +++ b/pythainlp/parse/transformers_ud.py @@ -26,11 +26,21 @@ class Parse: + """Dependency parser using TransformersUD.""" + def __init__( self, model: Optional[str] = "KoichiYasuoka/deberta-base-thai-ud-head", revision: Optional[str] = None, ) -> None: + """ + Initialize the TransformersUD models. + + :param Optional[str] model: model name or path; the default model + is used if ``None`` + :param Optional[str] revision: git revision id (branch, tag, or + commit hash) + """ from transformers import ( AutoConfig, AutoModelForQuestionAnswering, @@ -85,6 +95,16 @@ def __init__( def __call__( # noqa: CCR001 # phase2-todo self, text: str, tag: str = "str" ) -> Union[list[list[str]], str]: + """ + Parse the dependency structure of a text. + + :param str text: text to be parsed + :param str tag: output type, ``"str"`` (CoNLL-U text, default) + or ``"list"`` + :return: CoNLL-U text if ``tag`` is ``"str"``, otherwise a list of + lists of fields + :rtype: Union[list[list[str]], str] + """ import numpy import torch import ufal.chu_liu_edmonds diff --git a/pythainlp/parse/ud_goeswith.py b/pythainlp/parse/ud_goeswith.py index 2acf05be7..0ed9206a8 100644 --- a/pythainlp/parse/ud_goeswith.py +++ b/pythainlp/parse/ud_goeswith.py @@ -18,11 +18,21 @@ class Parse: + """Dependency parser using UDgoeswith.""" + def __init__( self, model: Optional[str] = "KoichiYasuoka/deberta-base-thai-ud-goeswith", revision: Optional[str] = None, ) -> None: + """ + Initialize the UDgoeswith model. + + :param Optional[str] model: model name; the default model is used + if ``None`` + :param Optional[str] revision: git revision id (branch, tag, or + commit hash) + """ if model is None: model = "KoichiYasuoka/deberta-base-thai-ud-goeswith" self.tokenizer: AutoTokenizer = AutoTokenizer.from_pretrained( @@ -37,6 +47,16 @@ def __init__( def __call__( # noqa: CCR001 # phase2-todo self, text: str, tag: str = "str" ) -> Union[List[List[str]], str]: + """ + Parse the dependency structure of a text. + + :param str text: text to be parsed + :param str tag: output type, ``"str"`` (CoNLL-U text, default) + or ``"list"`` + :return: CoNLL-U text if ``tag`` is ``"str"``, otherwise a list of + lists of fields + :rtype: Union[List[List[str]], str] + """ import numpy as np import torch import ufal.chu_liu_edmonds diff --git a/pythainlp/phayathaibert/core.py b/pythainlp/phayathaibert/core.py index 65b2de4c4..8120f1cb2 100644 --- a/pythainlp/phayathaibert/core.py +++ b/pythainlp/phayathaibert/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""PhayaThaiBERT text processing, augmentation, and tagging.""" + from __future__ import annotations import random @@ -34,7 +36,10 @@ class ThaiTextProcessor: + """Preprocess Thai text for PhayaThaiBERT.""" + def __init__(self) -> None: + """Initialize the text processor.""" ( self._TK_UNK, self._TK_REP, @@ -262,7 +267,10 @@ def preprocess( class ThaiTextAugmenter: + """Augment Thai text using PhayaThaiBERT masked language model.""" + def __init__(self) -> None: + """Initialize the text augmenter.""" from transformers import ( AutoModelForMaskedLM, AutoTokenizer, @@ -373,11 +381,20 @@ def augment( class PartOfSpeechTagger: + """Tag part-of-speech (POS) in Thai text using PhayaThaiBERT.""" + def __init__( self, model: str = "lunarlist/pos_thai_phayathai", revision: Optional[str] = None, ) -> None: + """ + Initialize the POS tagger. + + :param str model: name of the model to load + :param Optional[str] revision: git revision id (branch, tag, or + commit hash) + """ # Load model directly from transformers import ( AutoModelForTokenClassification, @@ -431,11 +448,20 @@ def get_tag( class NamedEntityTagger: + """Tag named entities in Thai text using PhayaThaiBERT.""" + def __init__( self, model: str = "Pavarissy/phayathaibert-thainer", revision: Optional[str] = None, ) -> None: + """ + Initialize the named entity tagger. + + :param str model: name of the model to load + :param Optional[str] revision: git revision id (branch, tag, or + commit hash) + """ from transformers import ( AutoModelForTokenClassification, AutoTokenizer, diff --git a/pythainlp/soundex/complete_soundex.py b/pythainlp/soundex/complete_soundex.py index 698d39e12..8603818da 100644 --- a/pythainlp/soundex/complete_soundex.py +++ b/pythainlp/soundex/complete_soundex.py @@ -52,6 +52,7 @@ class CompleteSoundex: """ def __init__(self) -> None: + """Initialize the Complete Soundex lookup tables.""" self.thai_consonants: str = ( "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬฮอ" ) diff --git a/pythainlp/soundex/sound.py b/pythainlp/soundex/sound.py index 37feab275..5296f0cb5 100644 --- a/pythainlp/soundex/sound.py +++ b/pythainlp/soundex/sound.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Phonetic similarity of Thai words, based on IPA sounds.""" + from __future__ import annotations from typing import cast diff --git a/pythainlp/spell/phunspell.py b/pythainlp/spell/phunspell.py index 55b9e60b9..04091baa8 100644 --- a/pythainlp/spell/phunspell.py +++ b/pythainlp/spell/phunspell.py @@ -28,8 +28,23 @@ def spell(text: str) -> list[str]: + """ + Return possible correct spellings of a word. + + :param str text: word to be checked + :return: list of suggested spellings + :rtype: list[str] + """ return list(pspell.suggest(text)) def correct(text: str) -> str: + """ + Correct the spelling of a word. + + :param str text: word to be corrected + :return: first suggested spelling + :rtype: str + :raises IndexError: if there is no suggested spelling + """ return cast("str", list(pspell.suggest(text))[0]) diff --git a/pythainlp/spell/pn.py b/pythainlp/spell/pn.py index 28d5468d3..0ae7b1d3b 100644 --- a/pythainlp/spell/pn.py +++ b/pythainlp/spell/pn.py @@ -167,6 +167,8 @@ def _convert_custom_dict( class NorvigSpellChecker: + """Check and correct spelling using Peter Norvig's algorithm.""" + def __init__( self, custom_dict: Optional[ diff --git a/pythainlp/spell/symspellpy.py b/pythainlp/spell/symspellpy.py index 04b42e7c4..4a4548f65 100644 --- a/pythainlp/spell/symspellpy.py +++ b/pythainlp/spell/symspellpy.py @@ -89,6 +89,14 @@ def _get_sym_spell() -> SymSpell: def spell(text: str, max_edit_distance: int = 2) -> list[str]: + """ + Return possible correct spellings of a word. + + :param str text: word to be checked + :param int max_edit_distance: maximum edit distance of a suggestion + :return: list of suggested spellings + :rtype: list[str] + """ sym_spell = _get_sym_spell() return [ str(i).split(",", maxsplit=1)[0] @@ -101,12 +109,29 @@ def spell(text: str, max_edit_distance: int = 2) -> list[str]: def correct(text: str, max_edit_distance: int = 1) -> str: + """ + Correct the spelling of a word. + + :param str text: word to be corrected + :param int max_edit_distance: maximum edit distance of a suggestion + :return: first suggested spelling + :rtype: str + :raises IndexError: if there is no suggested spelling + """ return spell(text, max_edit_distance=max_edit_distance)[0] def spell_sent( list_words: list[str], max_edit_distance: int = 2 ) -> list[list[str]]: + """ + Return possible correct spellings of a list of words. + + :param list[str] list_words: list of words to be checked + :param int max_edit_distance: maximum edit distance of a suggestion + :return: list of words of each suggested spelling + :rtype: list[list[str]] + """ sym_spell = _get_sym_spell() temp = [ str(i).split(",", maxsplit=1)[0].split(" ") @@ -128,6 +153,14 @@ def spell_sent( def correct_sent( list_words: list[str], max_edit_distance: int = 1 ) -> list[str]: + """ + Correct the spelling of a list of words. + + :param list[str] list_words: list of words to be corrected + :param int max_edit_distance: maximum edit distance of a suggestion + :return: list of corrected words + :rtype: list[str] + """ return [ i[0] for i in spell_sent(list_words, max_edit_distance=max_edit_distance) diff --git a/pythainlp/spell/tltk.py b/pythainlp/spell/tltk.py index fbd933ea0..3c41cfc41 100644 --- a/pythainlp/spell/tltk.py +++ b/pythainlp/spell/tltk.py @@ -23,4 +23,11 @@ def spell(text: str) -> list[str]: + """ + Return possible correct spellings of a word. + + :param str text: word to be checked + :return: list of suggested spellings + :rtype: list[str] + """ return cast("list[str]", spell_candidates(text)) diff --git a/pythainlp/spell/wanchanberta_thai_grammarly.py b/pythainlp/spell/wanchanberta_thai_grammarly.py index 611c8bf73..450aae640 100644 --- a/pythainlp/spell/wanchanberta_thai_grammarly.py +++ b/pythainlp/spell/wanchanberta_thai_grammarly.py @@ -33,7 +33,10 @@ class BertModel(torch.nn.Module): # type: ignore[misc] + """Tag misspelled tokens with the WangchanBERTa token classifier.""" + def __init__(self) -> None: + """Initialize the WangchanBERTa token classification model.""" super().__init__() self.bert: BertForTokenClassification = ( BertForTokenClassification.from_pretrained( @@ -47,6 +50,16 @@ def forward( mask: torch.Tensor, label: Optional[torch.Tensor], ) -> Any: + """ + Compute the forward pass of the token classification model. + + :param torch.Tensor input_id: token ids + :param torch.Tensor mask: attention mask + :param Optional[torch.Tensor] label: token labels + :return: model output, which is a tuple that starts with the logits + (and the loss if ``label`` is given) + :rtype: Any + """ output = self.bert( input_ids=input_id, attention_mask=mask, @@ -63,6 +76,14 @@ def forward( def align_word_ids(texts: str) -> list[int]: + """ + Create the label ids of a text for token classification. + + :param str texts: text to tokenize + :return: list of label ids, ``-100`` for a special or padding token + and ``2`` for others + :rtype: list[int] + """ tokenized_inputs = tokenizer( texts, padding="max_length", max_length=512, truncation=True ) @@ -78,6 +99,16 @@ def align_word_ids(texts: str) -> list[int]: def evaluate_one_text(model: BertModel, sentence: str) -> list[str]: + """ + Predict the label of each token in a sentence. + + :param BertModel model: token classification model (not used, the + module-level tagging model is always used) + :param str sentence: sentence to tag + :return: list of labels, ``"i"`` for a misspelled token and ``"f"`` + for a correct one + :rtype: list[str] + """ text = tokenizer( sentence, padding="max_length", @@ -105,6 +136,13 @@ def evaluate_one_text(model: BertModel, sentence: str) -> list[str]: def correct(text: str) -> str: + """ + Correct the spelling of a text. + + :param str text: text to be corrected + :return: corrected text + :rtype: str + """ ans = [] i_f = evaluate_one_text(tagging_model, text) a = tokenizer(text) diff --git a/pythainlp/spell/words_spelling_correction.py b/pythainlp/spell/words_spelling_correction.py index 86b1e4c19..f18dc8b56 100644 --- a/pythainlp/spell/words_spelling_correction.py +++ b/pythainlp/spell/words_spelling_correction.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Word-level spelling correction using FastText-like embeddings.""" + from __future__ import annotations from importlib import import_module @@ -329,6 +331,7 @@ class Words_Spelling_Correction(FastTextEncoder): list_word: list[str] def __init__(self) -> None: + """Initialize the word spelling correction model.""" self.model_name = "pythainlp/word-spelling-correction-char2vec" self.model_path = get_hf_hub(self.model_name) self.model_onnx = get_hf_hub(self.model_name, "nearest_neighbors.onnx") diff --git a/pythainlp/summarize/freq.py b/pythainlp/summarize/freq.py index 1035f6de9..c47ea0c85 100644 --- a/pythainlp/summarize/freq.py +++ b/pythainlp/summarize/freq.py @@ -17,12 +17,20 @@ class FrequencySummarizer: + """Summarize text by word frequency.""" + __min_cut: float __max_cut: float __stopwords: set[str] __freq: dict[str, float] def __init__(self, min_cut: float = 0.1, max_cut: float = 0.9) -> None: + """ + Initialize the frequency summarizer. + + :param float min_cut: minimum normalized word frequency to count + :param float max_cut: maximum normalized word frequency to count + """ self.__min_cut: float = min_cut self.__max_cut: float = max_cut self.__stopwords: set[str] = set(punctuation).union(_STOPWORDS) @@ -50,6 +58,15 @@ def __compute_frequencies( def summarize( self, text: str, n: int, tokenizer: str = "newmm" ) -> list[str]: + """ + Summarize text by selecting the highest scoring sentences. + + :param str text: text to summarize + :param int n: number of sentences in the summary + :param str tokenizer: engine to tokenize text with + :return: list of selected sentences + :rtype: list[str] + """ # sent_tokenize with str input returns list[str] sents = cast( "list[str]", sent_tokenize(text, engine="whitespace+newline") diff --git a/pythainlp/summarize/keybert.py b/pythainlp/summarize/keybert.py index d4a6db895..8d522992e 100644 --- a/pythainlp/summarize/keybert.py +++ b/pythainlp/summarize/keybert.py @@ -28,11 +28,18 @@ class KeyBERT: + """Extract keywords and keyphrases with the KeyBERT algorithm.""" + ft_pipeline: "Pipeline" def __init__( self, model_name: str = "airesearch/wangchanberta-base-att-spm-uncased" ) -> None: + """ + Initialize the KeyBERT feature extraction pipeline. + + :param str model_name: name of the model to extract features with + """ from transformers import pipeline self.ft_pipeline: "Pipeline" = pipeline( diff --git a/pythainlp/summarize/mt5.py b/pythainlp/summarize/mt5.py index f1f254455..6ab7fcd58 100644 --- a/pythainlp/summarize/mt5.py +++ b/pythainlp/summarize/mt5.py @@ -11,6 +11,8 @@ class mT5Summarizer: + """Summarize text using the mT5 model.""" + def __init__( self, model_size: str = "small", @@ -72,6 +74,13 @@ def __init__( self.skip_special_tokens: bool = skip_special_tokens def summarize(self, text: str) -> list[str]: + """ + Summarize text. + + :param str text: text to summarize + :return: list that contains the summary + :rtype: list[str] + """ preprocess_text = text.strip().replace("\n", "") if self.model_name == f"thanathorn/{CPE_KMUTT_THAI_SENTENCE_SUM}": t5_prepared_Text = "simplify: " + preprocess_text diff --git a/pythainlp/tag/blackboard.py b/pythainlp/tag/blackboard.py index 23de892c8..b274ba82c 100644 --- a/pythainlp/tag/blackboard.py +++ b/pythainlp/tag/blackboard.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Constants for the Blackboard treebank POS tag set.""" + from __future__ import annotations # defined strings for special characters diff --git a/pythainlp/tag/crfchunk.py b/pythainlp/tag/crfchunk.py index 6a6bbe575..829b728b3 100644 --- a/pythainlp/tag/crfchunk.py +++ b/pythainlp/tag/crfchunk.py @@ -25,6 +25,11 @@ class CRFchunk(CRFChunkParser): """ def __init__(self, corpus: str = "orchidpp") -> None: + """ + Initialize the chunk parser. + + :param str corpus: corpus used to train the chunk parser model + """ warn_deprecation( "pythainlp.tag.crfchunk.CRFchunk", "pythainlp.chunk.CRFChunkParser", diff --git a/pythainlp/tag/named_entity.py b/pythainlp/tag/named_entity.py index 8cc875aca..fbbe7ab32 100644 --- a/pythainlp/tag/named_entity.py +++ b/pythainlp/tag/named_entity.py @@ -71,9 +71,21 @@ class NER: def __init__( self, engine: str = "thainer-v2", corpus: str = "thainer" ) -> None: + """ + Initialize the named entity recognizer. + + :param str engine: engine to use for recognition + :param str corpus: corpus used to train the engine model + """ self.load_engine(engine=engine, corpus=corpus) def load_engine(self, engine: str, corpus: str) -> None: + """ + Load the named entity recognition engine. + + :param str engine: engine to use for recognition + :param str corpus: corpus used to train the engine model + """ self.name_engine = engine self.engine = None @@ -166,9 +178,19 @@ class NNER: engine: "ThaiNNER" def __init__(self, engine: str = "thai_nner") -> None: + """ + Initialize the nested named entity recognizer. + + :param str engine: engine to use for recognition + """ self.load_engine(engine) def load_engine(self, engine: str = "thai_nner") -> None: + """ + Load the nested named entity recognition engine. + + :param str engine: engine to use for recognition + """ from pythainlp.tag.thai_nner import ThaiNNER self.engine = ThaiNNER() diff --git a/pythainlp/tag/orchid.py b/pythainlp/tag/orchid.py index 7b61423cf..06cf13020 100644 --- a/pythainlp/tag/orchid.py +++ b/pythainlp/tag/orchid.py @@ -118,6 +118,14 @@ def ud_exception(w: str, tag: str) -> str: + """ + Return NOUN for the words การ and ความ, otherwise the given tag. + + :param str w: word + :param str tag: Universal POS tag of the word + :return: ``"NOUN"`` if the word is การ or ความ, otherwise ``tag`` + :rtype: str + """ if w in ("การ", "ความ"): return "NOUN" diff --git a/pythainlp/tag/pos_tag.py b/pythainlp/tag/pos_tag.py index e589103fc..fed0b652f 100644 --- a/pythainlp/tag/pos_tag.py +++ b/pythainlp/tag/pos_tag.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Part-of-speech (POS) tagging for Thai text.""" + from __future__ import annotations from typing import Optional diff --git a/pythainlp/tag/tltk.py b/pythainlp/tag/tltk.py index c8a8a0eb7..93b7d454e 100644 --- a/pythainlp/tag/tltk.py +++ b/pythainlp/tag/tltk.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Thai NLP functions using TLTK.""" + from __future__ import annotations from typing import Union, cast @@ -19,6 +21,16 @@ def pos_tag(words: list[str], corpus: str = "tnc") -> list[tuple[str, str]]: + """ + Tag part-of-speech (POS) in a list of words using **TLTK**. + + :param list[str] words: list of words + :param str corpus: corpus used to train the tagger; only + ``"tnc"`` is supported + :return: list of tuples (word, POS tag) + :rtype: list[tuple[str, str]] + :raises ValueError: if the corpus is not supported + """ if corpus != "tnc": raise ValueError(f"tltk not support {corpus!r} corpus.") return cast("list[tuple[str, str]]", nlp.pos_tag_wordlist(words)) diff --git a/pythainlp/tag/wangchanberta_onnx.py b/pythainlp/tag/wangchanberta_onnx.py index 5967be2f0..988dd2f73 100644 --- a/pythainlp/tag/wangchanberta_onnx.py +++ b/pythainlp/tag/wangchanberta_onnx.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""WangchanBERTa named entity recognizer with ONNX Runtime.""" + from __future__ import annotations import json @@ -36,6 +38,16 @@ def __init__( file_onnx: str, providers: Optional[list[str]] = None, ) -> None: + """ + Initialize the ONNX session and the tokenizer. + + :param str model_name: name of the corpus holding the model + :param str model_version: version of the model + :param str file_onnx: file name of the ONNX model + :param Optional[list[str]] providers: ONNX Runtime execution + providers; ``["CPUExecutionProvider"]`` if ``None`` + :raises FileNotFoundError: if the model is not found + """ import sentencepiece as spm from onnxruntime import ( GraphOptimizationLevel, @@ -111,11 +123,26 @@ def postprocess( def clean_output( self, list_text: list[tuple[str, str]] ) -> list[tuple[str, str]]: + """ + Return the list of tags unchanged. + + :param list[tuple[str, str]] list_text: list of tuples (word, tag) + :return: list of tuples (word, tag) + :rtype: list[tuple[str, str]] + """ return list_text def totag( self, post: "NDArray[np.float32]", sent: str ) -> list[tuple[str, str]]: + """ + Map each token of a sentence to its most probable tag. + + :param numpy.typing.NDArray[numpy.float32] post: probability scores + :param str sent: sentence to be tagged + :return: list of tuples (token, tag) + :rtype: list[tuple[str, str]] + """ tag = [] _s = self.sp.EncodeAsPieces(sent) for i in range(len(_s)): @@ -137,6 +164,16 @@ def _config( def get_ner( # noqa: CCR001 # phase2-todo self, text: str, tag: bool = False ) -> Union[str, list[tuple[str, str]]]: + """ + Tag named entities in text in IOB format. + + :param str text: text to be tagged + :param bool tag: return HTML-like tags in a string instead of a + list of tuples + :return: list of tuples (token, named entity tag), or a string + with HTML-like tags if ``tag`` is ``True`` + :rtype: Union[str, list[tuple[str, str]]] + """ self._s = self.build_tokenizer(text) logits_raw = self.session.run( output_names=[self.outputs_name], input_feed=self._s diff --git a/pythainlp/tokenize/attacut.py b/pythainlp/tokenize/attacut.py index 3526671e8..2a01104db 100644 --- a/pythainlp/tokenize/attacut.py +++ b/pythainlp/tokenize/attacut.py @@ -17,10 +17,17 @@ class AttacutTokenizer: + """Wrap the AttaCut tokenizer.""" + _MODEL_NAME: str _tokenizer: Tokenizer def __init__(self, model: str = "attacut-sc") -> None: + """ + Initialize the AttaCut tokenizer. + + :param str model: name of the AttaCut model (attacut-sc or attacut-c) + """ self._MODEL_NAME: str = "attacut-sc" if model == "attacut-c": @@ -29,6 +36,13 @@ def __init__(self, model: str = "attacut-sc") -> None: self._tokenizer: Tokenizer = Tokenizer(model=self._MODEL_NAME) def tokenize(self, text: str) -> list[str]: + """ + Tokenize text into words. + + :param str text: text to be tokenized + :return: list of words + :rtype: list[str] + """ return cast("list[str]", self._tokenizer.tokenize(text)) diff --git a/pythainlp/tokenize/han_solo.py b/pythainlp/tokenize/han_solo.py index a8aa39616..c23b68609 100644 --- a/pythainlp/tokenize/han_solo.py +++ b/pythainlp/tokenize/han_solo.py @@ -49,6 +49,8 @@ def _get_tagger() -> pycrfsuite.Tagger: class Featurizer: + """Extract character n-gram features for Han-solo.""" + # This class from ssg at https://github.com/ponrawee/ssg. N: int @@ -61,11 +63,26 @@ def __init__( sequence_size: int = 1, delimiter: Optional[str] = None, ) -> None: + """ + Initialize the featurizer. + + :param int N: size of the character n-gram + :param int sequence_size: size of the character sequence + :param Optional[str] delimiter: delimiter character in the text + """ self.N: int = N self.delimiter: Optional[str] = delimiter self.radius: int = N + sequence_size def pad(self, sentence: str, padder: str = "#") -> str: + """ + Pad a sentence with a padding character on both sides. + + :param str sentence: sentence to pad + :param str padder: padding character + :return: padded sentence + :rtype: str + """ return padder * (self.radius) + sentence + padder * (self.radius) def _skip_delimiter( @@ -131,6 +148,16 @@ def featurize( indiv_char: bool = True, return_type: str = "list", ) -> dict[str, list[Any]]: + """ + Extract features and labels from a sentence. + + :param str sentence: sentence to featurize + :param bool padding: pad the sentence first + :param bool indiv_char: include features of individual characters + :param str return_type: type of the features (list or dict) + :return: features (X) and labels (Y) + :rtype: dict[str, list[typing.Any]] + """ if padding: sentence = self.pad(sentence) all_features_list: list[list[str]] = [] @@ -169,6 +196,13 @@ def featurize( def segment(text: str) -> list[str]: + """ + Tokenize text into words with Han-solo. + + :param str text: text to be tokenized + :return: list of words + :rtype: list[str] + """ tagger = _get_tagger() x = _to_feature.featurize(text)["X"] y_pred = tagger.tag(x) diff --git a/pythainlp/tokenize/longest.py b/pythainlp/tokenize/longest.py index c50233bf7..8ab4709b8 100644 --- a/pythainlp/tokenize/longest.py +++ b/pythainlp/tokenize/longest.py @@ -82,9 +82,16 @@ def _group_spaces(tokens: list[str]) -> list[str]: class LongestMatchTokenizer: + """Tokenize text into words with dictionary-based longest matching.""" + __trie: Trie def __init__(self, trie: Trie) -> None: + """ + Initialize the tokenizer. + + :param pythainlp.util.Trie trie: dictionary trie + """ self.__trie: Trie = trie @staticmethod @@ -156,6 +163,13 @@ def __segment(self, text: str) -> list[str]: return _group_spaces(tokens) def tokenize(self, text: str) -> list[str]: + """ + Tokenize text into words. + + :param str text: text to be tokenized + :return: list of words + :rtype: list[str] + """ tokens = self.__segment(text) return tokens diff --git a/pythainlp/tokenize/multi_cut.py b/pythainlp/tokenize/multi_cut.py index 8268ed1ed..8d5821595 100644 --- a/pythainlp/tokenize/multi_cut.py +++ b/pythainlp/tokenize/multi_cut.py @@ -40,6 +40,7 @@ def __new__( multi: Optional[list[str]] = None, in_dict: bool = True, ) -> "LatticeString": + """Create a new lattice string from a value.""" return str.__new__(cls, value) def __init__( @@ -48,6 +49,13 @@ def __init__( multi: Optional[list[str]] = None, in_dict: bool = True, ) -> None: + """ + Initialize the lattice string. + + :param str value: string value + :param Optional[list[str]] multi: possible tokenizations of the value + :param bool in_dict: whether the value is in the dictionary + """ self.unique: bool = True if multi: self.multi: list[str] = list(multi) @@ -133,6 +141,13 @@ def _multicut( def mmcut(text: str) -> list[str]: + """ + Tokenize text into words with the minimum-cut selection. + + :param str text: text to be tokenized + :return: list of words + :rtype: list[str] + """ res = [] for w in _multicut(text): mm = min(w.multi, key=lambda x: x.count("/")) diff --git a/pythainlp/tokenize/nlpo3.py b/pythainlp/tokenize/nlpo3.py index 289307b27..de842880f 100644 --- a/pythainlp/tokenize/nlpo3.py +++ b/pythainlp/tokenize/nlpo3.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Wrap nlpo3, a Rust implementation of the Thai word tokenizer.""" + from __future__ import annotations import threading diff --git a/pythainlp/tokenize/ssg.py b/pythainlp/tokenize/ssg.py index f9f616a30..1c4c72737 100644 --- a/pythainlp/tokenize/ssg.py +++ b/pythainlp/tokenize/ssg.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Wrap ssg, a syllable tokenizer for Thai.""" + from __future__ import annotations from typing import cast diff --git a/pythainlp/tokenize/thai2fit.py b/pythainlp/tokenize/thai2fit.py index 1947b66cb..f93cfb523 100644 --- a/pythainlp/tokenize/thai2fit.py +++ b/pythainlp/tokenize/thai2fit.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Provide the Thai2Fit word tokenizer.""" from functools import lru_cache diff --git a/pythainlp/tokenize/thaisumcut.py b/pythainlp/tokenize/thaisumcut.py index de0a6a98a..f51e52a92 100644 --- a/pythainlp/tokenize/thaisumcut.py +++ b/pythainlp/tokenize/thaisumcut.py @@ -197,6 +197,13 @@ def list_to_string(list: list[str]) -> str: + """ + Join a list of strings and collapse the whitespace. + + :param list[str] list: list of strings + :return: joined string + :rtype: str + """ string = "".join(list) string = " ".join(string.split()) return string @@ -235,6 +242,13 @@ def _mark_middle_cuts(sentence: str, sentence_size: int) -> str: def middle_cut(sentences: list[str]) -> list[str]: + """ + Split long sentences at the space nearest to the middle. + + :param list[str] sentences: list of sentences + :return: list of sentences + :rtype: list[str] + """ result_parts = [] for sentence in sentences: sentence_size = len(word_tokenize(sentence, keep_whitespace=False)) @@ -332,9 +346,19 @@ def _mark_boundaries(text: str) -> str: class ThaiSentenceSegmentor: + """Tokenize Thai text into sentences.""" + def split_into_sentences( self, text: str, isMiddleCut: bool = False ) -> list[str]: + """ + Split text into sentences. + + :param str text: text to be tokenized + :param bool isMiddleCut: also cut long sentences at the middle + :return: list of sentences + :rtype: list[str] + """ text = f" {text} " text = text.replace("\n", " ") text = _replace_all(text, _PROTECT) diff --git a/pythainlp/tokenize/tltk.py b/pythainlp/tokenize/tltk.py index 8db3060bd..2d36ac499 100644 --- a/pythainlp/tokenize/tltk.py +++ b/pythainlp/tokenize/tltk.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Wrap tltk, a Thai language toolkit.""" + from __future__ import annotations try: @@ -13,6 +15,13 @@ def segment(text: str) -> list[str]: + """ + Tokenize text into words with tltk. + + :param str text: text to be tokenized + :return: list of words + :rtype: list[str] + """ if not text or not isinstance(text, str): return [] text = text.replace(" ", "") @@ -24,6 +33,13 @@ def segment(text: str) -> list[str]: def syllable_tokenize(text: str) -> list[str]: + """ + Tokenize text into syllables with tltk. + + :param str text: text to be tokenized + :return: list of syllables + :rtype: list[str] + """ if not text or not isinstance(text, str): return [] _temp: str = syl_segment(text) @@ -34,6 +50,13 @@ def syllable_tokenize(text: str) -> list[str]: def sent_tokenize(text: str) -> list[str]: + """ + Tokenize text into sentences with tltk. + + :param str text: text to be tokenized + :return: list of sentences + :rtype: list[str] + """ text = text.replace(" ", "") _temp: str = tltk_segment(text).replace("", " ").replace("|", "") _temp_list = _temp.split("") diff --git a/pythainlp/tokenize/wtsplit.py b/pythainlp/tokenize/wtsplit.py index 132cf1bac..43b74a2ac 100644 --- a/pythainlp/tokenize/wtsplit.py +++ b/pythainlp/tokenize/wtsplit.py @@ -101,6 +101,17 @@ def tokenize( paragraph_threshold: float = 0.5, style: str = "newline", ) -> list[str]: + """ + Tokenize text into sentences or paragraphs with wtpsplit. + + :param str text: text to be tokenized + :param str size: model size (tiny, mini, base, or large) + :param str tokenize: tokenization level (sentence or paragraph) + :param float paragraph_threshold: threshold for the paragraph boundary + :param str style: paragraph separator style (newline or newline-char) + :return: list of sentences or paragraphs + :rtype: list[str] + """ _model_load = "" if size == "tiny": _model_load = "wtp-bert-tiny" diff --git a/pythainlp/tools/__init__.py b/pythainlp/tools/__init__.py index cc718a93d..a450f665c 100644 --- a/pythainlp/tools/__init__.py +++ b/pythainlp/tools/__init__.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""Utility functions for paths, data directory, and runtime modes.""" + __all__: list[str] = [ "PYTHAINLP_DEFAULT_DATA_DIR", "get_full_data_path", diff --git a/pythainlp/tools/misspell.py b/pythainlp/tools/misspell.py index a86f25f92..33c1ce215 100644 --- a/pythainlp/tools/misspell.py +++ b/pythainlp/tools/misspell.py @@ -1,6 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 + +"""Generate misspelled Thai and English text from keyboard layouts.""" + from __future__ import annotations import math @@ -45,6 +48,7 @@ def search_location_of_character( char: str, ) -> Optional[tuple[int, int, int, int]]: + """Find the location of a character on the keyboard layouts.""" for language_ix in [0, 1]: for ix, row in enumerate(ALL_CHARACTERS[language_ix]): if char in row: @@ -57,6 +61,7 @@ def find_neighbour_locations( char: str, kernel: Optional[list[tuple[int, int]]] = None, ) -> list[tuple[int, int, int, int, str]]: + """Find the keyboard neighbors of a character location.""" if kernel is None: kernel = [(-1, -1), (-1, 0), (1, 1), (0, 1), (0, -1), (1, 0)] language_ix, is_shift, row, pos = loc @@ -75,6 +80,7 @@ def find_neighbour_locations( def find_misspell_candidates( char: str, verbose: bool = False ) -> Optional[list[str]]: + """Find characters that are neighbors of a character on the keyboard.""" loc = search_location_of_character(char) if loc is None: return None diff --git a/pythainlp/translate/core.py b/pythainlp/translate/core.py index 2de9969ff..f8f786ce5 100644 --- a/pythainlp/translate/core.py +++ b/pythainlp/translate/core.py @@ -181,6 +181,7 @@ def __init__( self.load_model() def load_model(self) -> None: + """Load the translation model for the language pair and engine.""" src_lang = self.src_lang target_lang = self.target_lang use_gpu = self.use_gpu diff --git a/pythainlp/translate/en_th.py b/pythainlp/translate/en_th.py index b3314a3b5..3b58062a5 100644 --- a/pythainlp/translate/en_th.py +++ b/pythainlp/translate/en_th.py @@ -74,6 +74,11 @@ class EnThTranslator: """ def __init__(self, use_gpu: bool = False) -> None: + """ + Initialize the English-to-Thai translator. + + :param bool use_gpu: load the model on a GPU + """ self._tokenizer: MosesTokenizer = MosesTokenizer("en") self._model_name: str = _EN_TH_MODEL_NAME @@ -155,6 +160,11 @@ class ThEnTranslator: """ def __init__(self, use_gpu: bool = False) -> None: + """ + Initialize the Thai-to-English translator. + + :param bool use_gpu: load the model on a GPU + """ self._model_name: str = _TH_EN_MODEL_NAME _download_install(self._model_name) diff --git a/pythainlp/translate/small100.py b/pythainlp/translate/small100.py index e48562a62..795125348 100644 --- a/pythainlp/translate/small100.py +++ b/pythainlp/translate/small100.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Translate text with the small100 model.""" + from __future__ import annotations from typing import TYPE_CHECKING, Optional @@ -33,6 +35,13 @@ def __init__( pretrained: str = "alirezamsh/small100", revision: Optional[str] = None, ) -> None: + """ + Initialize the small100 translator. + + :param bool use_gpu: load the model on a GPU + :param str pretrained: name of the pretrained model + :param Optional[str] revision: revision of the pretrained model + """ from transformers import M2M100ForConditionalGeneration self.pretrained: str = pretrained diff --git a/pythainlp/translate/th_fr.py b/pythainlp/translate/th_fr.py index 94bb4edef..2ee473827 100644 --- a/pythainlp/translate/th_fr.py +++ b/pythainlp/translate/th_fr.py @@ -45,6 +45,13 @@ def __init__( pretrained: str = "Helsinki-NLP/opus-mt-th-fr", revision: Optional[str] = None, ) -> None: + """ + Initialize the Thai-to-French translator. + + :param bool use_gpu: load the model on a GPU + :param str pretrained: name of the pretrained model + :param Optional[str] revision: revision of the pretrained model + """ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer self.tokenizer_thfr: AutoTokenizer = AutoTokenizer.from_pretrained( diff --git a/pythainlp/translate/tokenization_small100.py b/pythainlp/translate/tokenization_small100.py index 3235e0e32..4e910bdad 100644 --- a/pythainlp/translate/tokenization_small100.py +++ b/pythainlp/translate/tokenization_small100.py @@ -165,6 +165,17 @@ def __init__( num_madeup_words: int = 8, **kwargs: Any, ) -> None: + """ + Initialize the tokenizer. + + :param str vocab_file: path to the vocabulary file + :param str spm_file: path to the SentencePiece model file + :param Optional[str] tgt_lang: target language code + :param str language_codes: language code set (m2m100) + :param Optional[dict[str, str]] sp_model_kwargs: keyword arguments for + the SentencePiece processor + :param int num_madeup_words: number of made-up words + """ self.sp_model_kwargs: dict[str, str] = ( {} if sp_model_kwargs is None else sp_model_kwargs ) @@ -232,6 +243,7 @@ def __init__( @property def vocab_size(self) -> int: + """Return the vocabulary size.""" # Type ignore for external library dict operations return ( len(self.encoder) @@ -241,6 +253,7 @@ def vocab_size(self) -> int: @property def tgt_lang(self) -> str: + """Return the target language code.""" return self._tgt_lang @tgt_lang.setter @@ -348,6 +361,7 @@ def build_inputs_with_special_tokens( ) def get_vocab(self) -> dict[str, int]: + """Return the vocabulary as a token-to-id mapping.""" vocab = { self.convert_ids_to_tokens(i): i for i in range(self.vocab_size) } @@ -355,11 +369,13 @@ def get_vocab(self) -> dict[str, int]: return vocab def __getstate__(self) -> dict[str, Any]: + """Return the state for pickling, without the SentencePiece model.""" state = self.__dict__.copy() state["sp_model"] = None return state def __setstate__(self, d: dict[str, Any]) -> None: + """Restore the state and reload the SentencePiece model.""" self.__dict__: dict[str, Any] = d # for backward compatibility @@ -373,6 +389,15 @@ def __setstate__(self, d: dict[str, Any]) -> None: def save_vocabulary( self, save_directory: str, filename_prefix: Optional[str] = None ) -> tuple[str, str]: + """ + Save the vocabulary and the SentencePiece model files. + + :param str save_directory: directory to save the files to + :param Optional[str] filename_prefix: prefix of the file names + :return: paths of the vocabulary file and the SentencePiece model file + :rtype: tuple[str, str] + :raises OSError: if save_directory is not a directory + """ save_dir = Path(save_directory) if not save_dir.is_dir(): raise OSError(f"{save_directory} should be a directory") @@ -405,6 +430,15 @@ def prepare_seq2seq_batch( tgt_lang: str = "ro", **kwargs: Any, ) -> BatchEncoding: + """ + Prepare a batch of source and target texts for a seq2seq model. + + :param list[str] src_texts: list of source texts + :param Optional[list[str]] tgt_texts: list of target texts + :param str tgt_lang: target language code + :return: encoded batch + :rtype: transformers.BatchEncoding + """ self.tgt_lang: str = tgt_lang self.set_lang_special_tokens(self.tgt_lang) return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs) @@ -447,9 +481,23 @@ def set_lang_special_tokens(self, src_lang: str) -> None: self.suffix_tokens: list[int] = [self.eos_token_id] def get_lang_token(self, lang: str) -> str: + """ + Return the special token of a language. + + :param str lang: language code + :return: language token + :rtype: str + """ return self.lang_code_to_token[lang] def get_lang_id(self, lang: str) -> int: + """ + Return the token id of a language. + + :param str lang: language code + :return: language token id + :rtype: int + """ lang_token = self.get_lang_token(lang) return self.lang_token_to_id[lang_token] @@ -457,6 +505,15 @@ def get_lang_id(self, lang: str) -> int: def load_spm( path: str, sp_model_kwargs: dict[str, str] ) -> SentencePieceProcessor: + """ + Load a SentencePiece model from a file. + + :param str path: path to the model file + :param dict[str, str] sp_model_kwargs: keyword arguments for the + SentencePiece processor + :return: SentencePiece processor + :rtype: sentencepiece.SentencePieceProcessor + """ import sentencepiece spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs) @@ -465,6 +522,13 @@ def load_spm( def load_json(path: str) -> Union[dict[str, str], list[str]]: + """ + Load JSON data from a file. + + :param str path: path to the JSON file + :return: loaded data + :rtype: Union[dict[str, str], list[str]] + """ with open(path) as f: return cast("Union[dict[str, str], list[str]]", json.load(f)) @@ -472,5 +536,12 @@ def load_json(path: str) -> Union[dict[str, str], list[str]]: def save_json( data: Union[Mapping[str, Union[str, int]], list[str]], path: str ) -> None: + """ + Save data to a JSON file. + + :param data: data to save + :type data: Union[Mapping[str, Union[str, int]], list[str]] + :param str path: path to the JSON file + """ with open(path, "w") as f: json.dump(data, f, indent=2) diff --git a/pythainlp/translate/word2word_translate.py b/pythainlp/translate/word2word_translate.py index c6df6c8c2..216def7d5 100644 --- a/pythainlp/translate/word2word_translate.py +++ b/pythainlp/translate/word2word_translate.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Translate words with word2word.""" + from __future__ import annotations from typing import Optional, cast diff --git a/pythainlp/translate/zh_th.py b/pythainlp/translate/zh_th.py index 500312872..f540d5de9 100644 --- a/pythainlp/translate/zh_th.py +++ b/pythainlp/translate/zh_th.py @@ -39,6 +39,13 @@ def __init__( pretrained: str = "Lalita/marianmt-th-zh_cn", revision: Optional[str] = None, ) -> None: + """ + Initialize the Thai-to-Chinese translator. + + :param bool use_gpu: load the model on a GPU + :param str pretrained: name of the pretrained model + :param Optional[str] revision: revision of the pretrained model + """ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer self.tokenizer_thzh: AutoTokenizer = AutoTokenizer.from_pretrained( @@ -124,6 +131,13 @@ def __init__( pretrained: str = "Lalita/marianmt-zh_cn-th", revision: Optional[str] = None, ) -> None: + """ + Initialize the Chinese-to-Thai translator. + + :param bool use_gpu: load the model on a GPU + :param str pretrained: name of the pretrained model + :param Optional[str] revision: revision of the pretrained model + """ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer self.tokenizer_zhth: AutoTokenizer = AutoTokenizer.from_pretrained( diff --git a/pythainlp/transliterate/core.py b/pythainlp/transliterate/core.py index 64ebd56c5..0e09cc618 100644 --- a/pythainlp/transliterate/core.py +++ b/pythainlp/transliterate/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Romanization, transliteration, and pronunciation of Thai text.""" + from __future__ import annotations from typing import Callable diff --git a/pythainlp/transliterate/ipa.py b/pythainlp/transliterate/ipa.py index 7847d57eb..778b8de7b 100644 --- a/pythainlp/transliterate/ipa.py +++ b/pythainlp/transliterate/ipa.py @@ -18,12 +18,33 @@ def transliterate(text: str) -> str: + """ + Transliterate Thai text to International Phonetic Alphabet (IPA). + + :param str text: Thai text to be transliterated + :return: IPA text + :rtype: str + """ return cast("str", _EPI_THA.transliterate(text)) def trans_list(text: str) -> list[str]: + """ + Transliterate Thai text to a list of IPA segments. + + :param str text: Thai text to be transliterated + :return: list of IPA segments + :rtype: list[str] + """ return cast("list[str]", _EPI_THA.trans_list(text)) def xsampa_list(text: str) -> list[str]: + """ + Transliterate Thai text to a list of X-SAMPA segments. + + :param str text: Thai text to be transliterated + :return: list of X-SAMPA segments + :rtype: list[str] + """ return cast("list[str]", _EPI_THA.xsampa_list(text)) diff --git a/pythainlp/transliterate/pali.py b/pythainlp/transliterate/pali.py index 00096c512..ae70a478c 100644 --- a/pythainlp/transliterate/pali.py +++ b/pythainlp/transliterate/pali.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Thai pronunciation of Pali words.""" + import re diff --git a/pythainlp/transliterate/spoonerism.py b/pythainlp/transliterate/spoonerism.py index 012a1b064..a72486d2c 100644 --- a/pythainlp/transliterate/spoonerism.py +++ b/pythainlp/transliterate/spoonerism.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Spoonerism of Thai text.""" + from __future__ import annotations from typing import Optional diff --git a/pythainlp/transliterate/thai2rom.py b/pythainlp/transliterate/thai2rom.py index a40ffaa6f..1542aa9a5 100644 --- a/pythainlp/transliterate/thai2rom.py +++ b/pythainlp/transliterate/thai2rom.py @@ -31,6 +31,8 @@ class ThaiTransliterator: + """Romanize Thai words with a PyTorch model.""" + __model_filename: str _maxlength: int _char_to_ix: Dict[str, int] @@ -130,6 +132,8 @@ def romanize(self, text: str) -> str: class Encoder(nn.Module): # type: ignore[misc] + """Encode a sequence of characters with a bidirectional LSTM.""" + hidden_size: int character_embedding: nn.Embedding rnn: nn.LSTM @@ -160,6 +164,14 @@ def __init__( def forward( self, sequences: torch.Tensor, sequences_lengths: torch.Tensor ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Compute the forward pass of the encoder. + + :param torch.Tensor sequences: batch of encoded character sequences + :param torch.Tensor sequences_lengths: length of each sequence + :return: encoder outputs and the final hidden state + :rtype: tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]] + """ # sequences: (batch_size, sequence_length=MAX_LENGTH) # sequences_lengths: (batch_size) @@ -196,6 +208,13 @@ def forward( def init_hidden( self, batch_size: int ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Return a zero-filled initial hidden state. + + :param int batch_size: number of sequences in the batch + :return: initial hidden state and cell state + :rtype: tuple[torch.Tensor, torch.Tensor] + """ h_0 = torch.zeros( [2, batch_size, self.hidden_size // 2], requires_grad=True ).to(device) @@ -207,12 +226,20 @@ def init_hidden( class Attn(nn.Module): # type: ignore[misc] + """Compute attention weights over the encoder outputs.""" + method: str hidden_size: int attn: nn.Linear other: nn.Parameter def __init__(self, method: str, hidden_size: int) -> None: + """ + Initialize the attention layers. + + :param str method: scoring method, one of "dot", "general", or "concat" + :param int hidden_size: size of the hidden state + """ super().__init__() self.method = method @@ -231,6 +258,16 @@ def forward( encoder_outputs: torch.Tensor, mask: torch.Tensor, ) -> torch.Tensor: + """ + Compute the forward pass of the attention layer. + + :param torch.Tensor hidden: decoder hidden state + :param torch.Tensor encoder_outputs: encoder outputs + :param torch.Tensor mask: mask of non-padding positions + :return: attention weights, normalized to the range 0 to 1 + :rtype: torch.Tensor + :raises ValueError: if the attention method is not supported + """ # Calculate energies for each encoder output if self.method == "dot": attn_energies = torch.bmm( @@ -265,6 +302,8 @@ def forward( class AttentionDecoder(nn.Module): # type: ignore[misc] + """Decode a sequence of characters with an attention LSTM.""" + vocabulary_size: int hidden_size: int character_embedding: nn.Embedding @@ -333,6 +372,8 @@ def forward( class Seq2Seq(nn.Module): # type: ignore[misc] + """Sequence-to-sequence model of an encoder and an attention decoder.""" + encoder: Encoder decoder: AttentionDecoder pad_idx: int @@ -348,6 +389,17 @@ def __init__( target_end_token: int, max_length: int, ) -> None: + """ + Initialize the sequence-to-sequence model. + + :param Encoder encoder: encoder + :param AttentionDecoder decoder: attention decoder + :param int target_start_token: index of the target start token + :param int target_end_token: index of the target end token + :param int max_length: maximum sequence length + :raises ValueError: if the hidden sizes of the encoder and the + decoder differ + """ super().__init__() self.encoder: Encoder = encoder @@ -364,6 +416,13 @@ def __init__( ) def create_mask(self, source_seq: torch.Tensor) -> torch.Tensor: + """ + Create a boolean mask for non-padding positions. + + :param torch.Tensor source_seq: encoded source sequence + :return: boolean mask where True marks non-padding positions + :rtype: torch.Tensor + """ mask = source_seq != self.pad_idx return mask @@ -374,6 +433,18 @@ def forward( # noqa: CCR001 # phase2-todo target_seq: Optional[torch.Tensor], teacher_forcing_ratio: float = 0.5, ) -> torch.Tensor: + """ + Compute the forward pass of the sequence-to-sequence model. + + :param torch.Tensor source_seq: encoded source sequence + :param torch.Tensor source_seq_len: length of each source sequence + :param Optional[torch.Tensor] target_seq: encoded target sequence, + or None + :param float teacher_forcing_ratio: probability of feeding the target + token to the decoder + :return: output logits + :rtype: torch.Tensor + """ # source_seq: (batch_size, MAX_LENGTH) # source_seq_len: (batch_size, 1) # target_seq: (batch_size, MAX_LENGTH) diff --git a/pythainlp/transliterate/thai2rom_onnx.py b/pythainlp/transliterate/thai2rom_onnx.py index 053a91f39..8719a09ea 100644 --- a/pythainlp/transliterate/thai2rom_onnx.py +++ b/pythainlp/transliterate/thai2rom_onnx.py @@ -32,6 +32,8 @@ class ThaiTransliterator_ONNX: + """Transliterate Thai words to Latin (romanization) with an ONNX model.""" + def __init__(self) -> None: """ Initialize the transliterator of Thai words. @@ -149,6 +151,10 @@ def romanize(self, text: str) -> str: class Seq2Seq_ONNX: + """ + Sequence-to-sequence model that runs ONNX encoder and decoder sessions. + """ + encoder: InferenceSession decoder: InferenceSession pad_idx: int @@ -166,6 +172,16 @@ def __init__( max_length: int, target_vocab_size: int, ) -> None: + """ + Initialize the sequence-to-sequence model. + + :param onnxruntime.InferenceSession encoder: encoder session + :param onnxruntime.InferenceSession decoder: decoder session + :param int target_start_token: index of the target start token + :param int target_end_token: index of the target end token + :param int max_length: maximum sequence length + :param int target_vocab_size: size of the target vocabulary + """ super().__init__() self.encoder: "InferenceSession" = encoder @@ -291,4 +307,11 @@ def run( def romanize(text: str) -> str: + """ + Romanize Thai text to the Latin alphabet using the ONNX model. + + :param str text: Thai text to be romanized + :return: text rendered in the Latin alphabet + :rtype: str + """ return _THAI_TO_ROM_ONNX.romanize(text) diff --git a/pythainlp/transliterate/thaig2p.py b/pythainlp/transliterate/thaig2p.py index f04134442..709bfe2da 100644 --- a/pythainlp/transliterate/thaig2p.py +++ b/pythainlp/transliterate/thaig2p.py @@ -57,6 +57,7 @@ class ThaiG2P: _network: "Seq2Seq" def __init__(self) -> None: + """Initialize the Thai G2P model.""" self.__model_filename: str = get_corpus_path(_MODEL_NAME) # type: ignore[assignment] if not self.__model_filename: raise FileNotFoundError( @@ -144,6 +145,8 @@ def g2p(self, text: str) -> str: class Encoder(nn.Module): # type: ignore[misc] + """Encode a sequence of characters with a bidirectional LSTM.""" + hidden_size: int character_embedding: nn.Embedding rnn: nn.LSTM @@ -177,6 +180,14 @@ def forward( sequences: torch.Tensor, sequences_lengths: Union[NDArray[Any], list[int]], ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: + """ + Compute the forward pass of the encoder. + + :param torch.Tensor sequences: batch of encoded character sequences + :param torch.Tensor sequences_lengths: length of each sequence + :return: encoder outputs and the final hidden state + :rtype: tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]] + """ # sequences: (batch_size, sequence_length=MAX_LENGTH) # sequences_lengths: (batch_size) import numpy as np @@ -218,6 +229,13 @@ def forward( def init_hidden( self, batch_size: int ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Return a zero-filled initial hidden state. + + :param int batch_size: number of sequences in the batch + :return: initial hidden state and cell state + :rtype: tuple[torch.Tensor, torch.Tensor] + """ h_0 = torch.zeros( [2, batch_size, self.hidden_size // 2], requires_grad=True ).to(device) @@ -229,12 +247,20 @@ def init_hidden( class Attn(nn.Module): # type: ignore[misc] + """Compute attention weights over the encoder outputs.""" + method: str hidden_size: int attn: nn.Linear other: nn.Parameter def __init__(self, method: str, hidden_size: int) -> None: + """ + Initialize the attention layers. + + :param str method: scoring method, one of "dot", "general", or "concat" + :param int hidden_size: size of the hidden state + """ super().__init__() self.method: str = method @@ -255,6 +281,16 @@ def forward( encoder_outputs: torch.Tensor, mask: torch.Tensor, ) -> torch.Tensor: + """ + Compute the forward pass of the attention layer. + + :param torch.Tensor hidden: decoder hidden state + :param torch.Tensor encoder_outputs: encoder outputs + :param torch.Tensor mask: mask of non-padding positions + :return: attention weights, normalized to the range 0 to 1 + :rtype: torch.Tensor + :raises ValueError: if the attention method is not supported + """ # Calculate energies for each encoder output if self.method == "dot": attn_energies = torch.bmm( @@ -289,6 +325,8 @@ def forward( class AttentionDecoder(nn.Module): # type: ignore[misc] + """Decode a sequence of characters with an attention LSTM.""" + vocabulary_size: int hidden_size: int character_embedding: nn.Embedding @@ -357,6 +395,8 @@ def forward( class Seq2Seq(nn.Module): # type: ignore[misc] + """Sequence-to-sequence model of an encoder and an attention decoder.""" + encoder: Encoder decoder: AttentionDecoder pad_idx: int @@ -372,6 +412,17 @@ def __init__( target_end_token: int, max_length: int, ) -> None: + """ + Initialize the sequence-to-sequence model. + + :param Encoder encoder: encoder + :param AttentionDecoder decoder: attention decoder + :param int target_start_token: index of the target start token + :param int target_end_token: index of the target end token + :param int max_length: maximum sequence length + :raises ValueError: if the hidden sizes of the encoder and the + decoder differ + """ super().__init__() self.encoder: Encoder = encoder @@ -388,6 +439,13 @@ def __init__( ) def create_mask(self, source_seq: torch.Tensor) -> torch.Tensor: + """ + Create a boolean mask for non-padding positions. + + :param torch.Tensor source_seq: encoded source sequence + :return: boolean mask where True marks non-padding positions + :rtype: torch.Tensor + """ mask = source_seq != self.pad_idx return mask @@ -398,6 +456,18 @@ def forward( # noqa: CCR001 # phase2-todo target_seq: Optional[torch.Tensor], teacher_forcing_ratio: float = 0.5, ) -> torch.Tensor: + """ + Compute the forward pass of the sequence-to-sequence model. + + :param torch.Tensor source_seq: encoded source sequence + :param torch.Tensor source_seq_len: length of each source sequence + :param Optional[torch.Tensor] target_seq: encoded target sequence, + or None + :param float teacher_forcing_ratio: probability of feeding the target + token to the decoder + :return: output logits + :rtype: torch.Tensor + """ # source_seq: (batch_size, MAX_LENGTH) # source_seq_len: (batch_size, 1) # target_seq: (batch_size, MAX_LENGTH) @@ -482,4 +552,11 @@ def forward( # noqa: CCR001 # phase2-todo def transliterate(text: str) -> str: + """ + Convert Thai text to phonemes with the Thai G2P model. + + :param str text: Thai text to be converted + :return: phonemes of the text + :rtype: str + """ return _THAI_G2P.g2p(text) diff --git a/pythainlp/transliterate/thaig2p_v2.py b/pythainlp/transliterate/thaig2p_v2.py index 77a3c85ca..d3717fada 100644 --- a/pythainlp/transliterate/thaig2p_v2.py +++ b/pythainlp/transliterate/thaig2p_v2.py @@ -31,6 +31,11 @@ class ThaiG2P: pipe: Pipeline def __init__(self, device: str = "cpu") -> None: + """ + Initialize the text-to-text generation pipeline. + + :param str device: device to run the model on, such as "cpu" + """ from transformers import pipeline self.pipe: "Pipeline" = pipeline( @@ -40,6 +45,13 @@ def __init__(self, device: str = "cpu") -> None: ) def g2p(self, text: str) -> str: + """ + Convert Thai text to phonemes. + + :param str text: Thai text to be converted + :return: phonemes of the text + :rtype: str + """ outputs = cast("list[dict[str, str]]", self.pipe(text)) return outputs[0]["generated_text"] @@ -48,6 +60,14 @@ def g2p(self, text: str) -> str: def transliterate(text: str, device: str = "cpu") -> str: + """ + Convert Thai text to phonemes. + + :param str text: Thai text to be converted + :param str device: device to run the model on, such as "cpu" + :return: phonemes of the text + :rtype: str + """ global _THAI_G2P if _THAI_G2P is None: _THAI_G2P = ThaiG2P(device=device) diff --git a/pythainlp/transliterate/tltk.py b/pythainlp/transliterate/tltk.py index 28901cd48..1ed803c74 100644 --- a/pythainlp/transliterate/tltk.py +++ b/pythainlp/transliterate/tltk.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Romanization and phoneme conversion of Thai text, using tltk.""" + from __future__ import annotations from typing import cast @@ -28,6 +30,13 @@ def romanize(text: str) -> str: def tltk_g2p(text: str) -> str: + """ + Convert Thai text to phonemes using tltk. + + :param str text: Thai text to be converted + :return: phonemes of the text + :rtype: str + """ # Replace ฅ with ค to avoid KeyError in tltk (out-of-vocabulary issue) text = text.replace("ฅ", "ค") _temp = ( @@ -40,6 +49,13 @@ def tltk_g2p(text: str) -> str: def tltk_ipa(text: str) -> str: + """ + Convert Thai text to IPA using tltk. + + :param str text: Thai text to be converted + :return: IPA text + :rtype: str + """ # Replace ฅ with ค to avoid KeyError in tltk (out-of-vocabulary issue) text = text.replace("ฅ", "ค") _temp = cast("str", th2ipa(text)) diff --git a/pythainlp/transliterate/umt5_thaig2p.py b/pythainlp/transliterate/umt5_thaig2p.py index 2312d26d3..4fa879c86 100644 --- a/pythainlp/transliterate/umt5_thaig2p.py +++ b/pythainlp/transliterate/umt5_thaig2p.py @@ -31,6 +31,11 @@ class Umt5ThaiG2P: pipe: Pipeline def __init__(self, device: str = "cpu") -> None: + """ + Initialize the text-to-text generation pipeline. + + :param str device: device to run the model on, such as "cpu" + """ from transformers import pipeline self.pipe: "Pipeline" = pipeline( @@ -40,6 +45,13 @@ def __init__(self, device: str = "cpu") -> None: ) def g2p(self, text: str) -> str: + """ + Convert Thai text to phonemes. + + :param str text: Thai text to be converted + :return: phonemes of the text + :rtype: str + """ outputs = cast("list[dict[str, str]]", self.pipe(text)) return outputs[0]["generated_text"] @@ -48,6 +60,14 @@ def g2p(self, text: str) -> str: def transliterate(text: str, device: str = "cpu") -> str: + """ + Convert Thai text to phonemes. + + :param str text: Thai text to be converted + :param str device: device to run the model on, such as "cpu" + :return: phonemes of the text + :rtype: str + """ global _THAI_G2P if _THAI_G2P is None: _THAI_G2P = Umt5ThaiG2P(device=device) diff --git a/pythainlp/transliterate/w2p.py b/pythainlp/transliterate/w2p.py index acd8cf5df..3f9d7f4d2 100644 --- a/pythainlp/transliterate/w2p.py +++ b/pythainlp/transliterate/w2p.py @@ -55,6 +55,8 @@ def _load_vocab() -> tuple[ class Thai_W2P: + """Convert Thai words to their pronunciation in Thai letters.""" + graphemes: list[str] phonemes: list[str] g2idx: dict[str, int] @@ -77,6 +79,11 @@ class Thai_W2P: word: str def __init__(self) -> None: + """ + Initialize the model and load its weights. + + :raises FileNotFoundError: if the model corpus is not found + """ super().__init__() self.graphemes: list[str] = hp.graphemes self.phonemes: list[str] = hp.phonemes @@ -321,6 +328,13 @@ def _predict(self, word: str) -> str: return "".join(preds_str) def __call__(self, word: str) -> str: + """ + Convert a Thai word to its pronunciation in Thai letters. + + :param str word: Thai word to be converted + :return: Thai letters indicating how the word is pronounced + :rtype: str + """ if not any(letter in word for letter in self.graphemes): pron_result = word else: # predict for oov diff --git a/pythainlp/transliterate/wunsen.py b/pythainlp/transliterate/wunsen.py index 10b9b6ef8..97356f803 100644 --- a/pythainlp/transliterate/wunsen.py +++ b/pythainlp/transliterate/wunsen.py @@ -32,6 +32,7 @@ class WunsenTransliterate: system: Optional[str] def __init__(self) -> None: + """Initialize the transliterator.""" self.thap_value: Optional[ThapSap] = None self.lang: Optional[str] = None self.jp_input: Optional[str] = None diff --git a/pythainlp/ulmfit/tokenizer.py b/pythainlp/ulmfit/tokenizer.py index da8da2956..28f87fe7c 100644 --- a/pythainlp/ulmfit/tokenizer.py +++ b/pythainlp/ulmfit/tokenizer.py @@ -19,13 +19,29 @@ class BaseTokenizer: lang: str def __init__(self, lang: str) -> None: + """ + Initialize the tokenizer. + + :param str lang: language code + """ self.lang: str = lang def tokenizer(self, t: str) -> list[str]: + """ + Tokenize text by splitting on spaces. + + :param str t: text to be tokenized + :return: list of words + :rtype: list[str] + """ return t.split(" ") def add_special_cases(self, toks: Collection[str]) -> None: - pass + """ + Add special cases to the tokenizer; do nothing. + + :param Collection[str] toks: special cases to be added + """ class ThaiTokenizer(BaseTokenizer): @@ -38,6 +54,11 @@ class ThaiTokenizer(BaseTokenizer): lang: str def __init__(self, lang: str = "th") -> None: + """ + Initialize the tokenizer. + + :param str lang: language code + """ self.lang: str = lang @staticmethod @@ -71,4 +92,8 @@ def tokenizer(text: str) -> list[str]: return thai2fit_tokenizer().word_tokenize(text) def add_special_cases(self, toks: Collection[str]) -> None: - pass + """ + Add special cases to the tokenizer; do nothing. + + :param Collection[str] toks: special cases to be added + """ diff --git a/pythainlp/util/encoding.py b/pythainlp/util/encoding.py index 7c163821e..8ec9426b3 100644 --- a/pythainlp/util/encoding.py +++ b/pythainlp/util/encoding.py @@ -2,6 +2,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Text encoding conversion functions.""" + from __future__ import annotations diff --git a/pythainlp/util/keywords.py b/pythainlp/util/keywords.py index b0d1b1053..fb068acfc 100644 --- a/pythainlp/util/keywords.py +++ b/pythainlp/util/keywords.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Keyword ranking functions for Thai text.""" + from __future__ import annotations from collections import Counter diff --git a/pythainlp/util/lcs.py b/pythainlp/util/lcs.py index cdbc7ff15..d041d3bc9 100644 --- a/pythainlp/util/lcs.py +++ b/pythainlp/util/lcs.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Longest common subsequence functions.""" + from __future__ import annotations from typing import TYPE_CHECKING diff --git a/pythainlp/util/morse.py b/pythainlp/util/morse.py index 7872de787..269f59860 100644 --- a/pythainlp/util/morse.py +++ b/pythainlp/util/morse.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Thai Morse code conversion functions.""" + from __future__ import annotations THAI_MORSE_CODE: dict[str, str] = { diff --git a/pythainlp/util/pronounce.py b/pythainlp/util/pronounce.py index 89bf455ea..ec1fc3762 100644 --- a/pythainlp/util/pronounce.py +++ b/pythainlp/util/pronounce.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Functions for finding rhymes of Thai words.""" + from __future__ import annotations import re diff --git a/pythainlp/util/spell_words.py b/pythainlp/util/spell_words.py index 8c749999b..72c573aee 100644 --- a/pythainlp/util/spell_words.py +++ b/pythainlp/util/spell_words.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Functions for spelling Thai words.""" + from __future__ import annotations import re diff --git a/pythainlp/util/thai_lunar_date.py b/pythainlp/util/thai_lunar_date.py index 417d123c3..2564d4b2e 100644 --- a/pythainlp/util/thai_lunar_date.py +++ b/pythainlp/util/thai_lunar_date.py @@ -251,11 +251,25 @@ def _calculate_f_year_f_dev(year: int) -> tuple[int, float]: def athikamas(year: int) -> bool: + """ + Check if a year is a leap month year (อธิกมาส). + + :param int year: year in the Buddhist Era or Common Era + :return: True if the year has an extra month + :rtype: bool + """ athi = ((year - 78) - 0.45222) % 2.7118886 return athi < 1 def athikavar(year: int) -> bool: + """ + Check if a year is a leap day year (อธิกวาร). + + :param int year: year in the Buddhist Era or Common Era + :return: True if the year has an extra day + :rtype: bool + """ if athikamas(year): return False @@ -267,6 +281,13 @@ def athikavar(year: int) -> bool: def deviation(year: int) -> float: + """ + Return the deviation of a year from the lunar calendar. + + :param int year: year in the Buddhist Era or Common Era + :return: deviation value of the year + :rtype: float + """ curr_dev = 0.0 last_dev = 0.0 f_year, f_dev = _calculate_f_year_f_dev(year) @@ -291,6 +312,13 @@ def deviation(year: int) -> float: def last_day_in_year(year: int) -> int: + """ + Return the number of days in a lunar year. + + :param int year: year in the Buddhist Era or Common Era + :return: number of days (354, 355, or 384) + :rtype: int + """ if athikamas(year): return 384 if athikavar(year): diff --git a/pythainlp/util/trie.py b/pythainlp/util/trie.py index c29d29dca..2b47fa94e 100644 --- a/pythainlp/util/trie.py +++ b/pythainlp/util/trie.py @@ -41,14 +41,22 @@ class Trie(Iterable[str]): _word_count: int class Node: + """Node of the trie.""" + __slots__: tuple[str, str] = ("end", "children") def __init__(self) -> None: + """Initialize an empty node.""" self.end: bool = False # Children dict is created on demand to reduce memory for leaf nodes. self.children: Optional[dict[str, Trie.Node]] = None def __init__(self, words: Iterable[str]) -> None: + """ + Initialize the trie with words. + + :param Iterable[str] words: words to initialize the trie with + """ self._word_count: int = 0 self.root: Trie.Node = Trie.Node() for word in words: @@ -136,6 +144,13 @@ def prefixes(self, text: str, start: int = 0) -> list[str]: return res def __contains__(self, key: str) -> bool: + """ + Check if a word is in the trie. + + :param str key: word to look for + :return: True if the word is in the trie + :rtype: bool + """ cur = self.root for ch in key: if cur.children is None: @@ -147,6 +162,13 @@ def __contains__(self, key: str) -> bool: return cur.end def __iter__(self) -> Iterator[str]: + """ + Iterate over all words in the trie. + + :return: iterator of words + :rtype: Iterator[str] + """ + # DFS through the trie to yield all stored words. # A shared mutable prefix list is appended/popped to avoid # O(k²) list copies that a stack-based approach would incur. @@ -162,6 +184,12 @@ def _dfs(node: Trie.Node, prefix: list[str]) -> Iterator[str]: yield from _dfs(self.root, []) def __len__(self) -> int: + """ + Return the number of words in the trie. + + :return: number of words + :rtype: int + """ return self._word_count diff --git a/pythainlp/wangchanberta/core.py b/pythainlp/wangchanberta/core.py index 4910cdd6f..5de38c402 100644 --- a/pythainlp/wangchanberta/core.py +++ b/pythainlp/wangchanberta/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Named entity recognition using WangchanBERTa.""" + from __future__ import annotations import re @@ -41,6 +43,8 @@ def _get_tokenizer() -> CamembertTokenizer: class ThaiNameTagger: + """Tag named entities in Thai text using WangchanBERTa.""" + dataset_name: str grouped_entities: bool classify_tokens: TokenClassificationPipeline @@ -168,6 +172,8 @@ def get_ner( # noqa: C901, CCR001 # phase2-todo class NamedEntityRecognition: + """Recognize named entities in Thai text using WangchanBERTa.""" + tokenizer: PreTrainedTokenizerBase model: PreTrainedModel diff --git a/pythainlp/word_vector/core.py b/pythainlp/word_vector/core.py index 165aaa7b5..ba52759cb 100644 --- a/pythainlp/word_vector/core.py +++ b/pythainlp/word_vector/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Provide Thai word vectors.""" + from __future__ import annotations import logging @@ -46,6 +48,11 @@ class WordVector: """ def __init__(self, model_name: str = "thai2fit_wv") -> None: + """ + Initialize the word vector. + + :param str model_name: name of the word vector model + """ self.model_name: str self.model: "Word2VecKeyedVectors" self.WV_DIM: int diff --git a/pythainlp/wsd/core.py b/pythainlp/wsd/core.py index 47dbddae7..b064345a0 100644 --- a/pythainlp/wsd/core.py +++ b/pythainlp/wsd/core.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 +"""Thai word sense disambiguation.""" + from __future__ import annotations from typing import Optional, Union, cast diff --git a/working-docs/ROADMAP.md b/working-docs/ROADMAP.md index 61686c4a7..eb4454cf4 100644 --- a/working-docs/ROADMAP.md +++ b/working-docs/ROADMAP.md @@ -258,11 +258,23 @@ the code disagree. The code was not changed. No test pins them. - `tag.thainer.ThaiNameTagger`: an unknown `version` does not raise. The CRF model is left unopened. `tag.tltk.get_ner` and `ThaiNameTagger.get_ner` ignore `pos` when `tag=True`. -- Many functions and `parse` `__call__` methods have no docstring. -- Missing docstrings: `augment.lm.phayathaibert.ThaiTextAugmenter.generate`, - `generate.wangchanglm` (`WangChanGLM`, `is_exclude`), `chat.ChatBotModel`, - the `transliterate.ipa` functions, `pali.py` (module), the helpers in - `tools.misspell` and `corpus.th_en_translit`. +- `cli.data.App.path`: the docstring says "print the path of a local + dataset"; the code prints the PyThaiNLP data directory. +- `wsd.get_score` returns `1 - cos_sim`, a distance, not a similarity. +- `spell.wanchanberta_thai_grammarly.evaluate_one_text`: the `model` + parameter is unused; the function calls the module-level `tagging_model`. +- `spell.phunspell.correct` and `spell.symspellpy.correct` raise + `IndexError` when there is no suggestion. +- `augment.lm.phayathaibert.ThaiTextAugmenter.generate`: with `sample=True` + the index is always 0 to 4 and `word_rank` is ignored. +- `augment.wordnet.WordNetAug.find_synonyms` iterates all synsets of the + word and ignores the POS-filtered `list_synsets`. +- `parse.spacy_thai_engine.Parse.__init__`: `model` is ignored; the code + always calls `spacy_thai.load()`. `parse.dependency_parsing` lists it. +- `tag.wangchanberta_onnx.WngchanBerta_ONNX`: the class name has a typo. +- `util.thai_lunar_date`: `athikamas`, `athikavar`, `deviation`, and + `last_day_in_year` do not state the era of `year` (the code uses + `year - 78`). - Missing `:raises:` for `TypeError` in `thai_digit_to_arabic_digit` and similar functions. - `phayathaibert.core.replace_newlines` and some other docstrings with `\n` From e8ed01c79dc5cb6839486f394cae6ffb4c21c8a9 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 23:49:29 +0100 Subject: [PATCH 2/2] Compact changelog; log complexity ranking and docstring issues Signed-off-by: Arthit Suriyawongkul --- CHANGELOG.md | 39 +++++++++----------- working-docs/ROADMAP.md | 79 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31bee0f15..a819036b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ and this project adheres to - `pythainlp.tokenize.deepcut`: built-in ONNX engine replaces the TensorFlow-based `deepcut`; `custom_dict` is no longer applied ([#1372]) - Improve guardrails in `check_sara()` and `nighit()` ([#1453]) +- `bleu_score()` raises `ValueError` on unequal reference and hypothesis + counts; `nighit()` requires `w1` to end with "ํ" ([#1548]) ### Fixed @@ -31,34 +33,25 @@ and this project adheres to `NameError`; `langs()` missing `tha` ([#1541]) - `check_klon()` and `get_corpus_db()` no longer swallow unexpected exceptions ([#1542]) -- `download()`: download and extract via temporary paths, so a failed - download keeps the installed corpus; handle empty `db.json` keys ([#1546]) -- `db.json` is written atomically and keeps its mode and symlink ([#1546]) -- `remove()` no longer downloads a missing corpus before deleting it ([#1546]) +- `download()` uses temporary paths, so a failed download keeps the installed + corpus; `remove()` no longer downloads a missing corpus ([#1546]) +- `db.json` is written atomically and keeps its mode and symlink; handle + empty keys ([#1546]) - `ThaiTextProcessor.preprocess()` no longer raises `TypeError` when `pre_rules` is not given ([#1547]) -- `sound_syllable()` and `tone_detector()` no longer raise `IndexError` for a - syllable without a consonant, such as "ฤๅ" ([#1548]) -- `thaiword_to_time()`: accept "ตีหก"; unknown hour words raise `ValueError`, - not `KeyError` ([#1548]) -- `convert_years()` accepts the same source and target era ([#1548]) -- `bleu_score()`: empty hypotheses give 0.0; unequal numbers of references - and hypotheses raise `ValueError` ([#1548]) -- `puan()` keeps syllables that have no initial consonant, and no longer - raises `IndexError` ([#1548]) -- `WunsenTransliterate.transliterate()` raises `NotImplementedError` for - `lang=None` ([#1548]) -- `check_klon()` no longer raises `IndexError` after a stanza with an empty - Wak 4 ([#1548]) -- `nighit()`: map ช to ญ; add ฆ, ญ, ฏ, ฒ, ต, ม; `w1` must - end with "ํ" ([#1548]) +- `sound_syllable()`, `tone_detector()`, `puan()`, `check_klon()`, + `thaiword_to_time()`: no `IndexError` or `KeyError` on valid input ([#1548]) +- `thaiword_to_time()` accepts "ตีหก"; `convert_years()` accepts the same + source and target era ([#1548]) +- `bleu_score()` gives 0.0 for an empty hypothesis; `WunsenTransliterate` + raises `NotImplementedError` for `lang=None` ([#1548]) +- `nighit()`: map ช to ญ; add ฆ, ญ, ฏ, ฒ, ต, ม ([#1548]) ### Security -- Tar and zip extraction rejects absolute and escaping links; unsafe tar - members raise `ValueError` ([#1546]) -- Without `tarfile.data_filter`, tar extraction rejects all links and special - files and drops owners ([#1546]) +- Tar and zip extraction rejects absolute and escaping links; without + `tarfile.data_filter`, tar extraction also rejects special files and drops + owners ([#1546]) [#1372]: https://github.com/PyThaiNLP/pythainlp/pull/1372 [#1453]: https://github.com/PyThaiNLP/pythainlp/pull/1453 diff --git a/working-docs/ROADMAP.md b/working-docs/ROADMAP.md index eb4454cf4..b67f52c02 100644 --- a/working-docs/ROADMAP.md +++ b/working-docs/ROADMAP.md @@ -35,6 +35,85 @@ They can use `pythainlp.tag._utils._iob_to_markup`: - `pythainlp/wangchanberta/core.py` (two copies) - `pythainlp/tag/wangchanberta_onnx.py` +### Complexity ranking + +Measured on 2026-10-06. No function is over the limits (McCabe 10, +cognitive 15). The totals add up the complexity of every function in a +file, so a high total means many functions, not one hard function. +The top 20 files are ranked by McCabe total plus cognitive total. + +| # | File | Lines | Functions | McCabe total | McCabe max | Cognitive total | Cognitive max | +|---|------|-------|-----------|--------------|------------|-----------------|---------------| +| 1 | `pythainlp/corpus/core.py` | 1276 | 49 | 152 | 10 | 143 | 15 | +| 2 | `pythainlp/khavee/core.py` | 1117 | 24 | 117 | 9 | 163 | 13 | +| 3 | `pythainlp/soundex/complete_soundex.py` | 708 | 20 | 77 | 7 | 104 | 14 | +| 4 | `pythainlp/util/time.py` | 395 | 17 | 70 | 8 | 87 | 12 | +| 5 | `pythainlp/tokenize/core.py` | 864 | 18 | 60 | 6 | 66 | 10 | +| 6 | `pythainlp/util/syllable.py` | 367 | 14 | 44 | 8 | 51 | 12 | +| 7 | `pythainlp/corpus/common.py` | 516 | 16 | 51 | 7 | 43 | 14 | +| 8 | `pythainlp/util/trie.py` | 228 | 10 | 39 | 9 | 50 | 15 | +| 9 | `pythainlp/benchmarks/metrics.py` | 518 | 13 | 39 | 7 | 44 | 12 | +| 10 | `pythainlp/util/thai_lunar_date.py` | 478 | 13 | 40 | 6 | 42 | 14 | +| 11 | `pythainlp/tokenize/newmm.py` | 272 | 7 | 34 | 6 | 47 | 11 | +| 12 | `pythainlp/generate/core.py` | 381 | 12 | 42 | 6 | 38 | 10 | +| 13 | `pythainlp/tag/_tag_perceptron.py` | 338 | 13 | 39 | 6 | 40 | 11 | +| 14 | `pythainlp/tokenize/multi_cut.py` | 210 | 9 | 32 | 6 | 43 | 13 | +| 15 | `pythainlp/transliterate/royin.py` | 342 | 9 | 29 | 8 | 44 | 14 | +| 16 | `pythainlp/util/wordtonum.py` | 232 | 8 | 31 | 10 | 40 | 11 | +| 17 | `pythainlp/util/thai.py` | 425 | 13 | 37 | 7 | 34 | 10 | +| 18 | `pythainlp/tokenize/longest.py` | 210 | 10 | 30 | 6 | 41 | 13 | +| 19 | `pythainlp/tokenize/thaisumcut.py` | 380 | 9 | 30 | 7 | 39 | 15 | +| 20 | `pythainlp/util/numtoword.py` | 236 | 5 | 29 | 9 | 38 | 11 | + +Functions at the cognitive limit (15): +`util/trie.py:87`, `tokenize/thaisumcut.py:268`, `corpus/core.py:1140`. + +Functions at the McCabe limit (10): `corpus.remove`, +`tag.named_entity.load_engine`, `tools.misspell.find_misspell_candidates`, +`util.spell_words._clean`, and `util.wordtonum.thaiword_to_num`. + +Commands: + +```bash +ruff check --isolated --select C901 \ + --config 'lint.mccabe.max-complexity=0' pythainlp +flake8 --isolated --select CCR001 --max-cognitive-complexity=1 pythainlp +``` + +### Lint tightening candidates + +Ranked by value for effort. Counts are from 2026-10-06, run with the project +config on `pythainlp`, `tests`, `examples`, and `notebooks` +(`ruff check --select --config pyproject.toml ...`). +Enable a rule in `[tool.ruff.lint]` in the same PR that fixes its findings. + +| # | Rule | Found | Fix | Note | +|---|------|-------|-----|------| +| 1 | `D213`, `D300`, `D2` subset (`D200`, `D205`, `D202`, `D209`, `D214`) | 0 + 42 | manual | `D213` is free now: it locks in the new docstring style. Keep `D203`, `D212` off. | +| 2 | `PLE` | 1 | auto | A zero-width space in `tests/core/test_util_time.py:281`; write it as `\u200b`. | +| 3 | `PGH003` | 12 | manual | Blanket `# type: ignore`; use `[code]`, as the style guide asks. | +| 4 | `RUF100`, `RUF102` | 84 + 8 | auto | Unused and invalid `noqa`. Set `lint.external = ["CCR"]` first, so flake8's `CCR001` is kept. | +| 5 | `UP015`, `UP031`, `UP033` | 4 + 6 + 5 | auto and manual | Redundant `open` mode, `%` formatting, `lru_cache(maxsize=None)`. | +| 6 | `RUF022` | 17 | auto | Sort `__all__`, as the style guide asks. | +| 7 | `UP037` | 140 | auto | Remove quotes from annotations. Needs `from __future__ import annotations` in each file. | +| 8 | `D415`, `D400`, `D401`, `D413` | 76 + 76 + 4 + 2 | manual | Summary ends with a period, in the imperative mood. The first two flag the same lines. | +| 9 | `EXE001`, `ICN001`, `INP001`, `SLOT000`, `PYI034`, `A002`, `FA100` | 13 | manual | One-off fixes, a few lines each. | +| 10 | `RUF012` | 17 | manual | Mutable class attribute without `ClassVar`. Can hide shared-state bugs. | +| 11 | `FLY002`, `RUF010`, `RUF015` | 22 | manual | Small readability fixes. | +| 12 | `PLW2901` | 15 | manual | A loop variable is reassigned in the loop body. | +| 13 | `BLE001` | 13 | manual | Blind `except`. Narrow it or add `# noqa: BLE001` with a reason. Related to PR 1542. | +| 14 | `UP006`, `UP035` | 27 + 19 | manual | `typing.List` and similar. Safe with `from __future__ import annotations`. | +| 15 | `RUF005` | 22 | manual | List concatenation; use unpacking. | +| 16 | `PERF401`, `PERF402`, `PERF403` | 16 | manual | Loop to comprehension. Readability can get worse. | +| 17 | `W505` (max 79) | 65 | manual | Doctest output and comment lines cannot always wrap. Needs `# noqa`. | +| 18 | `TID252` | 27 | manual | Relative imports. The package uses them on purpose. Decide first. | +| 19 | `T201`, `ERA001` | 75 + 132 | manual | `print` in the CLI and examples is intended. Many `ERA001` hits are false positives. | +| 20 | `DTZ`, `PLW0603`, `PLR2004`, `PLR0913` | 17 + 49 + 86 + 22 | manual | Naive datetimes, `global` for lazy loading, magic numbers, and many arguments are intended in this code. Skip. | + +Do not enable `RUF001` and `RUF002` (256 findings). They flag Thai and +look-alike characters on purpose. Skip `EM`, `TRY003`, and `N` rules: +they are style choices, and `N` renames would break the public API. + ## Follow-up bug fixes Bugs found while refactoring. Refactoring changes keep the current behavior.