From e1f06550ce9c336e123711627727f21b7811e99a Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:18:14 +0100 Subject: [PATCH 1/8] Fix Codacy issues; tighten lint, tox, and AGENTS.md rules - Fix Codacy findings: docstrings, test `assert`/`random`/MD5 use, mutable test defaults; add `.pydocstyle.ini` - Enable ruff B, C4, ISC, PIE and S101 (tests/notebooks exempt); fix existing hits - Align tox and Makefile with CI (pins, test commands); add `make lint-md` - Sort `support_list`; add cross-platform, encoding, assert, and sorting rules to AGENTS.md Signed-off-by: Arthit Suriyawongkul --- .pydocstyle.ini | 5 + AGENTS.md | 12 +- Makefile | 9 +- notebooks/create_words.ipynb | 2 +- pyproject.toml | 19 ++- pythainlp/__init__.py | 2 +- pythainlp/augment/lm/wangchanberta.py | 2 +- pythainlp/augment/wordnet.py | 2 +- pythainlp/benchmarks/metrics.py | 4 +- pythainlp/braille/core.py | 4 +- pythainlp/corpus/core.py | 4 +- pythainlp/phayathaibert/core.py | 16 +-- pythainlp/spell/pn.py | 4 +- pythainlp/spell/words_spelling_correction.py | 2 +- pythainlp/tokenize/han_solo.py | 7 +- pythainlp/tokenize/newmm.py | 2 +- pythainlp/tokenize/thaisumcut.py | 4 +- pythainlp/tools/misspell.py | 11 +- pythainlp/translate/word2word_translate.py | 126 +++++++++---------- pythainlp/util/date.py | 2 +- pythainlp/util/thai_lunar_date.py | 2 +- tests/core/test_augment_wordnet.py | 4 + tests/core/test_benchmarks_error_rate.py | 5 +- tests/core/test_corpus_core_internals.py | 2 +- tests/core/test_generate_bigram.py | 8 +- tests/core/test_tag.py | 2 +- tests/core/test_tokenize.py | 8 +- tests/core/test_tokenize_core.py | 11 +- tests/core/test_tokenize_han_solo.py | 3 +- tests/core/test_transliterate_wunsen.py | 3 + tests/core/test_util_date_strptime.py | 7 +- 31 files changed, 162 insertions(+), 132 deletions(-) create mode 100644 .pydocstyle.ini diff --git a/.pydocstyle.ini b/.pydocstyle.ini new file mode 100644 index 000000000..34eefab4e --- /dev/null +++ b/.pydocstyle.ini @@ -0,0 +1,5 @@ +# Docstring checks run by Codacy (pydocstyle). +# Summary on the first line (D212) is the project style, so D213 is off. +# D211 is used over D203. +[pydocstyle] +ignore = D203, D213 diff --git a/AGENTS.md b/AGENTS.md index 86eda611a..082e491d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -384,8 +384,10 @@ PyThaiNLP targets Windows, Linux, and macOS. CI tests all three. runtime type inspection tools, documentation generators, and static analysis tools. For example, `typing.get_type_hints()` and `inspect` should work properly. -- [ ] Do not allow the use of assert in production code - (it is only allowed for testing and debugging). +- [ ] Do not use `assert` in production code: Python removes it under + `-O`, so it cannot enforce a check. Raise an exception + (`ValueError`, `TypeError`, ...) instead. + Ruff `S101` enforces this. `assert` is fine in tests. - [ ] Do not use mutable default arguments in function/method definitions. - [ ] Do not use wildcard imports (from module import *). - [ ] When reordering the imports, be careful not to (re-)introduce circular @@ -393,6 +395,12 @@ PyThaiNLP targets Windows, Linux, and macOS. CI tests all three. - [ ] Remove unused imports. - [ ] Remove any trailing whitespace in the Python file. - [ ] Make the package zip-safe if possible. +- [ ] Sort the members of a collection literal (list, set, tuple, dict + keys, `__all__`) when possible, so it is easier to read, compare, + and maintain, even if the collection is a set. + Keep the order when it matters at run time, including an order + that gives an early exit or an early hit for the common cases. + Add a short comment in that case. - [ ] Be mindful about choice of data structures. Prefer built-in data structures like list, dict, set, and tuple unless there is a specific need for specialized data structures. diff --git a/Makefile b/Makefile index f86a61b89..94145a8bf 100644 --- a/Makefile +++ b/Makefile @@ -49,14 +49,17 @@ clean-test: ## remove test and coverage artifacts lint: ## check style, formatting, cognitive complexity, and types (as in CI) tox -e ruff,flake8,mypy -test: ## run tests quickly with the default Python - python -m unittest discover +test: ## run the core tests quickly with the default Python + python -m unittest tests.core + +lint-md: ## check Markdown files (as in CI; needs Node.js) + npx markdownlint-cli2 "**/*.md" "#License.md" "#LICENSE.md" "#node_modules" test-all: ## run tests on every Python version with tox tox coverage: ## check code coverage quickly with the default Python - coverage run --source pythainlp -m unittest discover + coverage run -m unittest tests.core coverage report -m coverage html $(BROWSER) htmlcov/index.html diff --git a/notebooks/create_words.ipynb b/notebooks/create_words.ipynb index 718871d4b..7e867fa96 100644 --- a/notebooks/create_words.ipynb +++ b/notebooks/create_words.ipynb @@ -83,7 +83,7 @@ " raise NotImplementedError(f\"The function doesn't support {w1}.\")\n", " list_w1 = list(w1)\n", " list_w2 = list(w2)\n", - " newword = list()\n", + " newword = []\n", " newword.append(list_w1[0])\n", " newword.append(\"ั\")\n", " consonant_start = [i for i in list_w2 if i in set(thai_consonants)][0]\n", diff --git a/pyproject.toml b/pyproject.toml index b202be2c1..9fe41e893 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,10 @@ select = [ "W", "S", "TC", - "B028", + "B", + "C4", + "ISC", + "PIE", "C901", "F401", "F811", @@ -443,8 +446,14 @@ select = [ "W293", ] # Some rules are ignored for now; we can consider enabling them in the future. -# S101 is use of assert statement, should be an easy fix. -extend-ignore = ["E402", "E501", "E722", "S101", "S202", "S301", "S310"] +# B905 (zip strict=) needs Python 3.10. +# B010 (setattr) is for dynamic attributes that tests set on purpose. +extend-ignore = ["B905", "E402", "E501", "E722", "S202", "S301", "S310"] + +[tool.ruff.lint.per-file-ignores] +# S101 (assert) is not allowed in production code. Tests and notebooks may use it. +"tests/**" = ["B010", "S101"] +"notebooks/**" = ["S101"] [tool.tox] env_list = ["py39", "py310", "py311", "py312", "py313", "py314", "pypy310", "pypy311", "ruff", "flake8", "mypy"] @@ -467,13 +476,13 @@ commands = [ ["ruff", "check", "--config", "pyproject.toml", "pythainlp", "tests", "examples", "notebooks"], ["ruff", "format", "--check", "--config", "pyproject.toml", "pythainlp", "tests", "examples", "notebooks"], ] -deps = ["ruff>=0.16.10"] +deps = ["ruff==0.16.10"] skip_install = true [tool.tox.env.flake8] basepython = ["python"] commands = [["flake8", "pythainlp"]] -deps = ["flake8>=7.3.0", "flake8-cognitive-complexity>=0.1.0"] +deps = ["flake8==7.4.1", "flake8-cognitive-complexity==0.1.0"] skip_install = true [tool.tox.env.mypy] diff --git a/pythainlp/__init__.py b/pythainlp/__init__.py index b306bbc36..397fe7fcf 100644 --- a/pythainlp/__init__.py +++ b/pythainlp/__init__.py @@ -9,7 +9,7 @@ thai_vowels: str = ( "\u0e24\u0e26\u0e30\u0e31\u0e32\u0e33\u0e34\u0e35\u0e36\u0e37" - + "\u0e38\u0e39\u0e40\u0e41\u0e42\u0e43\u0e44\u0e45\u0e4d\u0e47" + "\u0e38\u0e39\u0e40\u0e41\u0e42\u0e43\u0e44\u0e45\u0e4d\u0e47" ) # 20 thai_lead_vowels: str = "\u0e40\u0e41\u0e42\u0e43\u0e44" # 5 thai_follow_vowels: str = "\u0e30\u0e32\u0e33\u0e45" # 4 diff --git a/pythainlp/augment/lm/wangchanberta.py b/pythainlp/augment/lm/wangchanberta.py index 48b3607b2..10e44c351 100644 --- a/pythainlp/augment/lm/wangchanberta.py +++ b/pythainlp/augment/lm/wangchanberta.py @@ -57,7 +57,7 @@ def generate( if len(sent) < num_replace_tokens: num_replace_tokens = len(sent) masked_text = self.input_text - for i in range(num_replace_tokens): + for _ in range(num_replace_tokens): masked_text = masked_text + self.MASK_TOKEN sent2 += [ str(j["sequence"]).replace(" ", "").replace("", "") diff --git a/pythainlp/augment/wordnet.py b/pythainlp/augment/wordnet.py index 51dc47e63..bae47e011 100644 --- a/pythainlp/augment/wordnet.py +++ b/pythainlp/augment/wordnet.py @@ -163,7 +163,7 @@ def find_synonyms( self.list_synsets: list[Synset] = wordnet.synsets(word) for self.synset in wordnet.synsets(word): - for self.syn in self.synset.lemma_names(lang="tha"): + for self.syn in self.synset.lemma_names(lang="tha"): # noqa: B020 self.synonyms.append(self.syn) self.synonyms_without_duplicates: list[str] = list( diff --git a/pythainlp/benchmarks/metrics.py b/pythainlp/benchmarks/metrics.py index 56767b931..ad2ca030c 100644 --- a/pythainlp/benchmarks/metrics.py +++ b/pythainlp/benchmarks/metrics.py @@ -90,9 +90,7 @@ def _lcs_length(x: Sequence[str], y: Sequence[str]) -> int: def _error_rate(ref: Sequence[str], hyp: Sequence[str]) -> float: - """ - Calculate the edit distance between two sequences, divided by the - reference length. + """Calculate the edit distance divided by the reference length. :param Sequence[str] ref: reference items :param Sequence[str] hyp: hypothesis items diff --git a/pythainlp/braille/core.py b/pythainlp/braille/core.py index 88a1ce0fa..4481651bd 100644 --- a/pythainlp/braille/core.py +++ b/pythainlp/braille/core.py @@ -256,11 +256,11 @@ def __init__(self, data: Union[list[list[str]], list[str], str]) -> None: nested_data[i] = sorted(item) self.data: Union[list[list[str]], list[str]] = nested_data elif len(data) == 1: - self.data = sorted(list(data[0])) + self.data = sorted(data[0]) else: self.data = [] else: - self.data = sorted(list(data)) if data else [] + self.data = sorted(data) if data else [] # International standard Braille mapping # Dots 1,2,3 = left column (top, middle, bottom) diff --git a/pythainlp/corpus/core.py b/pythainlp/corpus/core.py index 21fbd1eef..0581769ad 100644 --- a/pythainlp/corpus/core.py +++ b/pythainlp/corpus/core.py @@ -501,7 +501,7 @@ def _check_member_path(path: str, member_name: str, archive_type: str) -> None: except ValueError: raise ValueError( f"Attempted path traversal in {archive_type} file: {member_name}" - ) + ) from None def _link_error(member_name: str, link_target: str) -> ValueError: @@ -530,7 +530,7 @@ def _check_link_target( try: safe_path_join(path, base_dir, link_target) except ValueError: - raise _link_error(member_name, link_target) + raise _link_error(member_name, link_target) from None def _check_tar_member(path: str, member: tarfile.TarInfo) -> None: diff --git a/pythainlp/phayathaibert/core.py b/pythainlp/phayathaibert/core.py index a349f3b2d..add412af3 100644 --- a/pythainlp/phayathaibert/core.py +++ b/pythainlp/phayathaibert/core.py @@ -201,15 +201,17 @@ def remove_space(self, toks: list[str]) -> list[str]: def preprocess( self, text: str, - pre_rules: list[Callable[..., str]] = [ - rm_brackets, - replace_newlines, - rm_useless_spaces, - replace_spaces, - replace_rep_after, - ], + pre_rules: Optional[list[Callable[..., str]]] = None, tok_func: Callable[..., list[str]] = word_tokenize, ) -> str: + if pre_rules is None: + pre_rules = [ + self.rm_brackets, + self.replace_newlines, + self.rm_useless_spaces, + self.replace_spaces, + self.replace_rep_after, + ] text = text.lower() for rule in pre_rules: text = rule(text) diff --git a/pythainlp/spell/pn.py b/pythainlp/spell/pn.py index 65309ec16..734e1144d 100644 --- a/pythainlp/spell/pn.py +++ b/pythainlp/spell/pn.py @@ -78,7 +78,7 @@ def _edits1(word: str) -> set[str]: def _edits2(word: str) -> set[str]: """Returns a set of words with an edit distance of 2 from the input word""" - return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1)) + return {e2 for e1 in _edits1(word) for e2 in _edits1(e1)} def _convert_custom_dict( @@ -243,7 +243,7 @@ def known(self, words: Iterable[str]) -> list[str]: >>> checker.known([]) # doctest: +SKIP [] """ - return list(w for w in words if w in self.__WORDS) + return [w for w in words if w in self.__WORDS] def prob(self, word: str) -> float: """Returns the probability of an input word, diff --git a/pythainlp/spell/words_spelling_correction.py b/pythainlp/spell/words_spelling_correction.py index e96fd4b6d..5dac74b24 100644 --- a/pythainlp/spell/words_spelling_correction.py +++ b/pythainlp/spell/words_spelling_correction.py @@ -154,7 +154,7 @@ def _get_subwords(self, word: str) -> tuple[list[str], NDArray[np.int_]]: return _subwords, np.array(_subword_ids) # 2. Extract n-grams (subwords) and get their hash indices - for ngram_start in range(0, len(_word)): + for ngram_start in range(len(_word)): for ngram_length in range(self.minn, self.maxn + 1): if ngram_start + ngram_length <= len(_word): _candidate_subword = _word[ diff --git a/pythainlp/tokenize/han_solo.py b/pythainlp/tokenize/han_solo.py index dae942612..753ac0d27 100644 --- a/pythainlp/tokenize/han_solo.py +++ b/pythainlp/tokenize/han_solo.py @@ -69,8 +69,7 @@ def pad(self, sentence: str, padder: str = "#") -> str: def _skip_delimiter( self, sentence: str, abs_index: int, step: int ) -> tuple[int, str]: - """Move ``abs_index`` by ``step`` until the character is not - the delimiter. + """Skip the delimiter, moving ``abs_index`` by ``step``. :return: the new index and the character at that index """ @@ -113,7 +112,7 @@ def _context_features( features.append("|".join([str(counter), char_right])) chars = chars_left + chars_right - for i in range(0, len(chars) - self.N + 1): + for i in range(len(chars) - self.N + 1): ngram = chars[i : i + self.N] features.append("|".join([str(i - self.radius), ngram])) return features @@ -153,7 +152,7 @@ def featurize( else: return { "X": [ - {key: 1 for key in feature_list} + dict.fromkeys(feature_list, 1) for feature_list in all_features_list ], "Y": all_labels_int, diff --git a/pythainlp/tokenize/newmm.py b/pythainlp/tokenize/newmm.py index 50f2dfd60..afb3880e6 100644 --- a/pythainlp/tokenize/newmm.py +++ b/pythainlp/tokenize/newmm.py @@ -212,7 +212,7 @@ def _find_cut_pos(text: str, custom_dict: Trie) -> int: # choose the position that covers longest token cut_pos = _TEXT_SCAN_BEGIN - for i in range(0, token_max_idx): + for i in range(token_max_idx): cut_pos = cut_pos + len(tokens[i]) return cut_pos diff --git a/pythainlp/tokenize/thaisumcut.py b/pythainlp/tokenize/thaisumcut.py index a2e17bde8..1785bd797 100644 --- a/pythainlp/tokenize/thaisumcut.py +++ b/pythainlp/tokenize/thaisumcut.py @@ -196,7 +196,7 @@ def list_to_string(list: list[str]) -> str: def _remove_digit_spaces(sentence: str) -> str: """Remove a space before or after a digit.""" sentence_len = len(sentence) - for k in range(0, sentence_len): + for k in range(sentence_len): if k == 0 or k + 1 >= sentence_len: continue if sentence[k].isdigit() and sentence[k - 1] == " ": @@ -213,7 +213,7 @@ def _mark_middle_cuts(sentence: str, sentence_size: int) -> str: """Replace the spaces nearest to the partition points with "".""" partition = math.floor(sentence_size / _MIDDLE_CUT_WORDS) tokens = word_tokenize(sentence, keep_whitespace=True) - for i in range(0, partition): + for i in range(partition): middle_space = sentence_size / (partition + 1) * (i + 1) spaces = [j for j, tok in enumerate(tokens) if tok == " "] if spaces: diff --git a/pythainlp/tools/misspell.py b/pythainlp/tools/misspell.py index c8580e60e..b5f594a6c 100644 --- a/pythainlp/tools/misspell.py +++ b/pythainlp/tools/misspell.py @@ -55,15 +55,10 @@ def search_location_of_character( def find_neighbour_locations( loc: tuple[int, int, int, int], char: str, - kernel: list[tuple[int, int]] = [ - (-1, -1), - (-1, 0), - (1, 1), - (0, 1), - (0, -1), - (1, 0), - ], + kernel: Optional[list[tuple[int, int]]] = None, ) -> list[tuple[int, int, int, int, str]]: + if kernel is None: + kernel = [(-1, -1), (-1, 0), (1, 1), (0, 1), (0, -1), (1, 0)] language_ix, is_shift, row, pos = loc valid_neighbours = [] diff --git a/pythainlp/translate/word2word_translate.py b/pythainlp/translate/word2word_translate.py index 429568367..95e20d5c1 100644 --- a/pythainlp/translate/word2word_translate.py +++ b/pythainlp/translate/word2word_translate.py @@ -7,70 +7,68 @@ from word2word import Word2word -support_list: set[str] = set( - [ - "zh_tw", - "el", - "te", - "hu", - "eu", - "ko", - "ru", - "lv", - "bg", - "sk", - "vi", - "gl", - "et", - "ta", - "fa", - "it", - "ms", - "id", - "pt", - "fr", - "sr", - "mk", - "sv", - "si", - "en", - "ka", - "uk", - "sl", - "hi", - "ca", - "lt", - "es", - "no", - "de", - "he", - "cs", - "ze_zh", - "fi", - "pl", - "tl", - "is", - "ze_en", - "kk", - "bn", - "tr", - "ur", - "pt_br", - "ar", - "ro", - "bs", - "ml", - "zh_cn", - "da", - "hr", - "sq", - "af", - "eo", - "nl", - "ja", - "th", - ] -) +support_list: set[str] = { + "af", + "ar", + "bg", + "bn", + "bs", + "ca", + "cs", + "da", + "de", + "el", + "en", + "eo", + "es", + "et", + "eu", + "fa", + "fi", + "fr", + "gl", + "he", + "hi", + "hr", + "hu", + "id", + "is", + "it", + "ja", + "ka", + "kk", + "ko", + "lt", + "lv", + "mk", + "ml", + "ms", + "nl", + "no", + "pl", + "pt", + "pt_br", + "ro", + "ru", + "si", + "sk", + "sl", + "sq", + "sr", + "sv", + "ta", + "te", + "th", + "tl", + "tr", + "uk", + "ur", + "vi", + "ze_en", + "ze_zh", + "zh_cn", + "zh_tw", +} def translate(word: str, src: str, target: str) -> Optional[list[str]]: diff --git a/pythainlp/util/date.py b/pythainlp/util/date.py index 1dd614f79..a033250c9 100644 --- a/pythainlp/util/date.py +++ b/pythainlp/util/date.py @@ -216,7 +216,7 @@ def thai_strptime( fmt: str, year: str = "be", add_year: Optional[int] = None, - tzinfo: Optional[ZoneInfo] = ZoneInfo("Asia/Bangkok"), + tzinfo: Optional[ZoneInfo] = ZoneInfo("Asia/Bangkok"), # noqa: B008 ) -> datetime: """Thai strptime diff --git a/pythainlp/util/thai_lunar_date.py b/pythainlp/util/thai_lunar_date.py index eb9f7c1e2..fb8ef0281 100644 --- a/pythainlp/util/thai_lunar_date.py +++ b/pythainlp/util/thai_lunar_date.py @@ -313,7 +313,7 @@ def athikasurathin(year: int) -> bool: def number_day_in_year(year: int) -> int: - """Number of days (365 or 366) in a Gregorian year. CE (Common Era)""" + """Get the number of days (365 or 366) in a Gregorian year (CE).""" if athikasurathin(year): return 366 diff --git a/tests/core/test_augment_wordnet.py b/tests/core/test_augment_wordnet.py index e9faf404f..28fdb2772 100644 --- a/tests/core/test_augment_wordnet.py +++ b/tests/core/test_augment_wordnet.py @@ -39,7 +39,10 @@ class FakeSynset: + """Synset with a fixed list of lemma names.""" + def __init__(self, names: list[str]) -> None: + """Set the lemma names.""" self.names = names def lemma_names(self, lang: str = "eng") -> list[str]: @@ -50,6 +53,7 @@ class FakeWordNet: """Replacement for pythainlp.corpus.wordnet; records its calls.""" def __init__(self) -> None: + """Start with no recorded calls.""" self.calls: list[tuple[str, Any]] = [] def synsets(self, word: str, pos: Any = None) -> list[FakeSynset]: diff --git a/tests/core/test_benchmarks_error_rate.py b/tests/core/test_benchmarks_error_rate.py index dcb4b3617..900f20528 100644 --- a/tests/core/test_benchmarks_error_rate.py +++ b/tests/core/test_benchmarks_error_rate.py @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 -"""Characterization tests for the edit-distance and LCS helpers in -pythainlp.benchmarks.metrics. +"""Characterization tests for the edit-distance and LCS helpers. + +The helpers are in pythainlp.benchmarks.metrics. Golden cases were recorded from the code before the shared-helper refactor. Word tokenization is replaced with a whitespace split. diff --git a/tests/core/test_corpus_core_internals.py b/tests/core/test_corpus_core_internals.py index 7b4f89ceb..6367b7e10 100644 --- a/tests/core/test_corpus_core_internals.py +++ b/tests/core/test_corpus_core_internals.py @@ -102,7 +102,7 @@ def _zip_bytes(members: list[tuple[str, bytes, bool]]) -> bytes: def _md5(data: bytes) -> str: - return hashlib.md5(data).hexdigest() # noqa: S324 + return hashlib.md5(data, usedforsecurity=False).hexdigest() # noqa: S324 def _snapshot(root: Path) -> dict[str, bytes]: diff --git a/tests/core/test_generate_bigram.py b/tests/core/test_generate_bigram.py index 0cc4d78a2..11b386e56 100644 --- a/tests/core/test_generate_bigram.py +++ b/tests/core/test_generate_bigram.py @@ -138,15 +138,15 @@ def test_picks_candidate_that_passes_threshold(self) -> None: def test_consumes_one_random_choice(self) -> None: random.seed(7) _pick_next(["a", "b", "c"], [0.5, 0.6, 0.7], 0.0) - after = random.random() + after = random.random() # nosec B311 random.seed(7) - random.choice([0.5, 0.6, 0.7]) - self.assertEqual(random.random(), after) + random.choice([0.5, 0.6, 0.7]) # nosec B311 + self.assertEqual(random.random(), after) # nosec B311 def test_no_random_call_when_nothing_passes(self) -> None: random.seed(7) _pick_next(["a"], [0.1], 0.5) - after = random.random() + after = random.random() # nosec B311 random.seed(7) self.assertEqual(random.random(), after) diff --git a/tests/core/test_tag.py b/tests/core/test_tag.py index f38640a75..cf1bf55ad 100644 --- a/tests/core/test_tag.py +++ b/tests/core/test_tag.py @@ -407,7 +407,7 @@ def test_entities_to_html(self): class IobToMarkupTestCase(unittest.TestCase): - """Test pythainlp.tag._utils._iob_to_markup""" + """Test pythainlp.tag._utils._iob_to_markup.""" def test_iob_to_markup(self): cases = [ diff --git a/tests/core/test_tokenize.py b/tests/core/test_tokenize.py index 523054a21..93932dcd8 100644 --- a/tests/core/test_tokenize.py +++ b/tests/core/test_tokenize.py @@ -195,9 +195,9 @@ SENT_2_TOKS = ["วันนี้ฉันกินข้าว และโดดเรียน"] SENT_3 = ( "(1) บทความนี้ผู้เขียนสังเคราะห์ขึ้นมา" - + "จากผลงานวิจัยที่เคยทำมาในอดีต" - + " มิได้ทำการศึกษาค้นคว้าใหม่อย่างกว้างขวางแต่อย่างใด" - + " จึงใคร่ขออภัยในความบกพร่องทั้งปวงมา ณ ที่นี้" + "จากผลงานวิจัยที่เคยทำมาในอดีต" + " มิได้ทำการศึกษาค้นคว้าใหม่อย่างกว้างขวางแต่อย่างใด" + " จึงใคร่ขออภัยในความบกพร่องทั้งปวงมา ณ ที่นี้" ) SENT_3_TOKS = [ "(1) บทความนี้ผู้เขียนสังเคราะห์ขึ้นมา" + "จากผลงานวิจัยที่เคยทำมาในอดีต ", @@ -418,7 +418,7 @@ def test_etcc(self): self.assertIsNotNone( etcc.segment( "หมูแมวเหล่านี้ด้วยเหตุผลเชื่อมโยงทางกรรมพันธุ์" - + "สัตว์มีแขนขาหน้าหัวเราะเพราะแข็งขืน" + "สัตว์มีแขนขาหน้าหัวเราะเพราะแข็งขืน" ) ) diff --git a/tests/core/test_tokenize_core.py b/tests/core/test_tokenize_core.py index ac8bebf5d..235c9c98e 100644 --- a/tests/core/test_tokenize_core.py +++ b/tests/core/test_tokenize_core.py @@ -13,7 +13,7 @@ import types import unittest from contextlib import contextmanager -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Optional from pythainlp.tokenize import ( paragraph_tokenize, @@ -107,6 +107,7 @@ class Recorder: """Callable that records its calls and returns a copy of a result.""" def __init__(self, result: list[str]) -> None: + """Set the result to return.""" self.result: list[str] = result self.calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] @@ -136,16 +137,16 @@ def fake_module(name: str, **attrs: Any) -> Iterator[None]: @contextmanager def fake_engine( - module: str, func: str, result: list[str] = FAKE_RESULT + module: str, func: str, result: Optional[list[str]] = None ) -> Iterator[Recorder]: - recorder = Recorder(result) + recorder = Recorder(FAKE_RESULT if result is None else result) with fake_module(module, **{func: recorder}): yield recorder @contextmanager -def fake_thaisum(result: list[str] = FAKE_RESULT) -> Iterator[Recorder]: - recorder = Recorder(result) +def fake_thaisum(result: Optional[list[str]] = None) -> Iterator[Recorder]: + recorder = Recorder(FAKE_RESULT if result is None else result) class FakeSegmentor: def split_into_sentences(self, text: str) -> list[str]: diff --git a/tests/core/test_tokenize_han_solo.py b/tests/core/test_tokenize_han_solo.py index 05deb3b63..881d5150f 100644 --- a/tests/core/test_tokenize_han_solo.py +++ b/tests/core/test_tokenize_han_solo.py @@ -1600,7 +1600,8 @@ def test_import_error_without_pycrfsuite(self) -> None: spec = importlib.util.spec_from_file_location( "han_solo_no_crf", str(han_solo.__file__) ) - assert spec is not None and spec.loader is not None + if spec is None or spec.loader is None: + self.fail("cannot load han_solo.py") module = importlib.util.module_from_spec(spec) with mock.patch.dict(sys.modules, {"pycrfsuite": None}): with self.assertRaises(ImportError) as ctx: diff --git a/tests/core/test_transliterate_wunsen.py b/tests/core/test_transliterate_wunsen.py index f3f6f61df..c363921e3 100644 --- a/tests/core/test_transliterate_wunsen.py +++ b/tests/core/test_transliterate_wunsen.py @@ -21,9 +21,12 @@ class FakeThapSap: + """Replacement for wunsen.ThapSap; records its arguments.""" + created: list[tuple[str, dict[str, Any]]] = [] def __init__(self, lang: str, **kwargs: Any) -> None: + """Record the arguments.""" FakeThapSap.created.append((lang, kwargs)) self.lang = lang diff --git a/tests/core/test_util_date_strptime.py b/tests/core/test_util_date_strptime.py index ce90e97c9..ed280319c 100644 --- a/tests/core/test_util_date_strptime.py +++ b/tests/core/test_util_date_strptime.py @@ -19,8 +19,11 @@ class _AnyMessage: - """Matches any message. For text that comes from the standard library - and differs between Python versions.""" + """Match any message. + + For text that comes from the standard library + and differs between Python versions. + """ def __eq__(self, other: object) -> bool: return True From f80eb347e921877dc12502cf812a1e825897ed54 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:25:32 +0100 Subject: [PATCH 2/8] Add tests.core.test_phayathaibert_preprocess Signed-off-by: Arthit Suriyawongkul --- CHANGELOG.md | 3 + pyproject.toml | 2 +- pythainlp/phayathaibert/core.py | 10 +++ tests/core/__init__.py | 1 + tests/core/test_phayathaibert_preprocess.py | 78 +++++++++++++++++++++ 5 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 tests/core/test_phayathaibert_preprocess.py diff --git a/CHANGELOG.md b/CHANGELOG.md index aee792926..ea16f5337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ and this project adheres to 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]) +- `ThaiTextProcessor.preprocess()` no longer raises `TypeError` when + `pre_rules` is not given ([#1547]) ### Security @@ -48,6 +50,7 @@ and this project adheres to [#1541]: https://github.com/PyThaiNLP/pythainlp/pull/1541 [#1542]: https://github.com/PyThaiNLP/pythainlp/pull/1542 [#1546]: https://github.com/PyThaiNLP/pythainlp/pull/1546 +[#1547]: https://github.com/PyThaiNLP/pythainlp/pull/1547 ## [5.3.8] - 2026-09-25 diff --git a/pyproject.toml b/pyproject.toml index 9fe41e893..ea986c9ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -447,11 +447,11 @@ select = [ ] # Some rules are ignored for now; we can consider enabling them in the future. # B905 (zip strict=) needs Python 3.10. -# B010 (setattr) is for dynamic attributes that tests set on purpose. extend-ignore = ["B905", "E402", "E501", "E722", "S202", "S301", "S310"] [tool.ruff.lint.per-file-ignores] # 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"] diff --git a/pythainlp/phayathaibert/core.py b/pythainlp/phayathaibert/core.py index add412af3..f7a1a9f67 100644 --- a/pythainlp/phayathaibert/core.py +++ b/pythainlp/phayathaibert/core.py @@ -204,6 +204,16 @@ def preprocess( pre_rules: Optional[list[Callable[..., str]]] = None, tok_func: Callable[..., list[str]] = word_tokenize, ) -> str: + """Preprocess text: apply the rules, then tokenize and join. + + :param str text: text to preprocess + :param list[Callable[..., str]] pre_rules: rules applied in order + after lowercasing; the default is the text cleaning methods + of this class + :param Callable[..., list[str]] tok_func: tokenizer function + :return: preprocessed text + :rtype: str + """ if pre_rules is None: pre_rules = [ self.rm_brackets, diff --git a/tests/core/__init__.py b/tests/core/__init__.py index 91cb08672..1eed2fa6b 100644 --- a/tests/core/__init__.py +++ b/tests/core/__init__.py @@ -26,6 +26,7 @@ "tests.core.test_lm_text_util", "tests.core.test_morpheme", "tests.core.test_morpheme_word_formation", + "tests.core.test_phayathaibert_preprocess", "tests.core.test_security", "tests.core.test_soundex", "tests.core.test_soundex_engines", diff --git a/tests/core/test_phayathaibert_preprocess.py b/tests/core/test_phayathaibert_preprocess.py new file mode 100644 index 000000000..983387dcc --- /dev/null +++ b/tests/core/test_phayathaibert_preprocess.py @@ -0,0 +1,78 @@ +# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project +# SPDX-FileType: SOURCE +# SPDX-License-Identifier: Apache-2.0 +"""Regression test for ThaiTextProcessor.preprocess. + +The module is imported under a private name with a fake ``transformers`` +package, because importing it downloads the real tokenizer. +""" + +import importlib.util +import sys +import types +import unittest +from pathlib import Path +from typing import Any +from unittest import mock + +import pythainlp + + +def _import_phayathaibert() -> Any: + """Load phayathaibert/core.py with a fake ``transformers``. + + Neither ``sys.modules`` nor the ``pythainlp.phayathaibert`` package + attribute is changed. + """ + fake = types.ModuleType("transformers") + tokenizer_class = mock.Mock() + fake.CamembertTokenizer = tokenizer_class # type: ignore[attr-defined] + path = Path(pythainlp.__file__).parent / "phayathaibert" / "core.py" + spec = importlib.util.spec_from_file_location( + "phayathaibert_under_test", path + ) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load {path}") + module = importlib.util.module_from_spec(spec) + with mock.patch.dict(sys.modules, {"transformers": fake}): + spec.loader.exec_module(module) + return module + + +class ThaiTextProcessorPreprocessTestCase(unittest.TestCase): + processor: Any + + @classmethod + def setUpClass(cls) -> None: + cls.processor = _import_phayathaibert().ThaiTextProcessor() + + def test_default_rules(self) -> None: + # Before the fix, the default rules were unbound methods, and + # every call without pre_rules raised TypeError. + self.assertEqual( + self.processor.preprocess("Hey (what)\n\nUP"), "hey<_>(what)<_>up" + ) + + def test_default_rules_with_custom_tokenizer(self) -> None: + # The default rules lowercase, collapse spaces, and mark each + # space with "<_>" before the tokenizer runs. + result = self.processor.preprocess("A B", tok_func=lambda t: [t]) + self.assertEqual(result, "a<_>b") + + def test_custom_rules_and_tokenizer(self) -> None: + result = self.processor.preprocess( + "ab", + pre_rules=[str.upper, lambda t: t + "!"], + tok_func=list, + ) + self.assertEqual(result, "AB!") + + def test_empty_rules_keep_text(self) -> None: + self.assertEqual( + self.processor.preprocess("Ab", pre_rules=[], tok_func=list), + "ab", + ) + + +if __name__ == "__main__": + unittest.main() From 73ae993d9e31342ddb03e6fb49f04eb3342ebc02 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:31:38 +0100 Subject: [PATCH 3/8] Enable more ruff rules; fix ISC004 and stale ignores Signed-off-by: Arthit Suriyawongkul --- pyproject.toml | 15 +++- pythainlp/ancient/aksonhan.py | 4 +- pythainlp/augment/wordnet.py | 2 +- pythainlp/braille/core.py | 20 +++--- pythainlp/chunk/crfchunk.py | 5 +- pythainlp/cli/benchmark.py | 2 +- pythainlp/corpus/core.py | 14 ++-- pythainlp/el/core.py | 4 +- pythainlp/generate/core.py | 2 +- pythainlp/khavee/core.py | 11 ++- pythainlp/lm/qwen3.py | 13 ++-- pythainlp/morpheme/thaiwordcheck.py | 7 +- pythainlp/parse/attaparse_engine.py | 10 +-- pythainlp/parse/core.py | 10 +-- pythainlp/parse/ud_goeswith.py | 41 +++++------ pythainlp/phayathaibert/core.py | 2 +- pythainlp/soundex/complete_soundex.py | 33 +++++---- pythainlp/spell/words_spelling_correction.py | 2 +- pythainlp/summarize/keybert.py | 5 +- pythainlp/tag/_tag_perceptron.py | 7 +- pythainlp/tag/pos_tag.py | 4 +- pythainlp/tag/thai_nner.py | 5 +- pythainlp/tag/wangchanberta_onnx.py | 3 +- pythainlp/tokenize/_registry.py | 2 +- pythainlp/tokenize/core.py | 7 +- pythainlp/tokenize/han_solo.py | 15 ++-- pythainlp/tokenize/longest.py | 6 +- pythainlp/tokenize/thaisumcut.py | 11 +-- pythainlp/tokenize/wtsplit.py | 53 +++++++------- pythainlp/translate/core.py | 7 +- pythainlp/translate/tokenization_small100.py | 13 ++-- pythainlp/translate/word2word_translate.py | 2 +- pythainlp/transliterate/core.py | 13 ++-- pythainlp/util/morse.py | 10 ++- pythainlp/util/phoneme.py | 2 +- pythainlp/util/profanity.py | 6 +- pythainlp/util/pronounce.py | 15 ++-- pythainlp/util/syllable.py | 11 ++- pythainlp/util/thai.py | 7 +- pythainlp/util/thai_lunar_date.py | 8 +-- pythainlp/util/time.py | 5 +- pythainlp/util/wordtonum.py | 5 +- pythainlp/wangchanberta/core.py | 15 ++-- tests/core/test_corpus_core_internals.py | 6 +- tests/core/test_tokenize_newmm_internals.py | 52 ++++++++------ tests/core/test_util_strftime.py | 62 ++++++++++------ tests/core/test_util_thai.py | 8 ++- tests/extra/testx_khavee.py | 74 +++++++++++++------- tests/extra/testx_ulmfit.py | 2 +- 49 files changed, 328 insertions(+), 310 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ea986c9ce..4f7d64b6c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -436,8 +436,11 @@ select = [ "TC", "B", "C4", + "FURB", "ISC", "PIE", + "RET", + "SIM", "C901", "F401", "F811", @@ -447,9 +450,19 @@ select = [ ] # Some rules are ignored for now; we can consider enabling them in the future. # B905 (zip strict=) needs Python 3.10. -extend-ignore = ["B905", "E402", "E501", "E722", "S202", "S301", "S310"] +# RET504 (assign then return), SIM108 (ternary), and SIM117 (nested with) +# are style choices that often hurt readability. +extend-ignore = ["B905", "E501", "RET504", "SIM108", "SIM117"] [tool.ruff.lint.per-file-ignores] +# E402: these packages import in a fixed order to avoid circular imports. +"pythainlp/__init__.py" = ["E402"] +"pythainlp/corpus/__init__.py" = ["E402"] +"pythainlp/corpus/wordnet.py" = ["E402"] +"pythainlp/soundex/__init__.py" = ["E402"] +"pythainlp/spell/__init__.py" = ["E402"] +"pythainlp/summarize/__init__.py" = ["E402"] +"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"] diff --git a/pythainlp/ancient/aksonhan.py b/pythainlp/ancient/aksonhan.py index 36b3184c7..68c011584 100644 --- a/pythainlp/ancient/aksonhan.py +++ b/pythainlp/ancient/aksonhan.py @@ -51,9 +51,9 @@ def aksonhan_to_current(word: str) -> str: """ if len(word) < 3: return word - elif word in _set_aksonhan: + if word in _set_aksonhan: return _dict_aksonhan[word] - elif word in _dict_thai: # word in Thai words + if word in _dict_thai: # word in Thai words return word _seg = _tokenizer.word_tokenize(word) diff --git a/pythainlp/augment/wordnet.py b/pythainlp/augment/wordnet.py index bae47e011..a4c68c622 100644 --- a/pythainlp/augment/wordnet.py +++ b/pythainlp/augment/wordnet.py @@ -113,7 +113,7 @@ def postype2wordnet(pos: str, corpus: str) -> Optional[str]: **Options for corpus** * *orchid* - Orchid Corpus """ - if corpus not in ["orchid"]: + if corpus != "orchid": return None return orchid[pos] diff --git a/pythainlp/braille/core.py b/pythainlp/braille/core.py index 4481651bd..10b73783f 100644 --- a/pythainlp/braille/core.py +++ b/pythainlp/braille/core.py @@ -151,9 +151,7 @@ + "\\2" for i in _v1 ] -_vowel_patterns += [ - i.replace("-", "([ก-ฮ])") + ",\\1" + i for i in _dict_2.keys() -] +_vowel_patterns += [i.replace("-", "([ก-ฮ])") + ",\\1" + i for i in _dict_2] _VOWELS: list[tuple[str, str]] = [ (x.split(",")[0], x.split(",")[1]) for x in _vowel_patterns ] @@ -541,9 +539,8 @@ def tobraille(self) -> str: if pattern_str in self.db: result += self.db[pattern_str] return result - else: - pattern_str = "".join(cast("list[str]", self.data)) - return self.db.get(pattern_str, "") + pattern_str = "".join(cast("list[str]", self.data)) + return self.db.get(pattern_str, "") def printbraille(self) -> str: """Mirror dot patterns for physical braille printing. @@ -572,9 +569,8 @@ def printbraille(self) -> str: mirrored_patterns.append(self.db[mirrored_sorted]) mirrored_patterns.reverse() return "".join(mirrored_patterns) - else: - mirrored = "".join( - mirror_map[dot] for dot in cast("list[str]", self.data) - ) - mirrored_sorted = "".join(sorted(mirrored)) - return self.db[mirrored_sorted] + mirrored = "".join( + mirror_map[dot] for dot in cast("list[str]", self.data) + ) + mirrored_sorted = "".join(sorted(mirrored)) + return self.db[mirrored_sorted] diff --git a/pythainlp/chunk/crfchunk.py b/pythainlp/chunk/crfchunk.py index 103b80147..0f4083bf7 100644 --- a/pythainlp/chunk/crfchunk.py +++ b/pythainlp/chunk/crfchunk.py @@ -5,6 +5,7 @@ from __future__ import annotations +from contextlib import suppress from importlib.resources import as_file, files from typing import TYPE_CHECKING, Any, Optional, Union, cast @@ -159,7 +160,5 @@ def __del__(self) -> None: Use the context manager protocol for reliable cleanup. """ if self._model_file_ctx is not None: - try: + with suppress(Exception): self._model_file_ctx.__exit__(None, None, None) - except Exception: # noqa: S110 - pass diff --git a/pythainlp/cli/benchmark.py b/pythainlp/cli/benchmark.py index 9228332cf..cf7e3be15 100644 --- a/pythainlp/cli/benchmark.py +++ b/pythainlp/cli/benchmark.py @@ -20,7 +20,7 @@ def _read_file(path: str) -> list[str]: with open(path, encoding="utf-8") as f: - lines = (r.strip() for r in f.readlines()) + lines = (r.strip() for r in f) return list(lines) diff --git a/pythainlp/corpus/core.py b/pythainlp/corpus/core.py index 0581769ad..e7cd24099 100644 --- a/pythainlp/corpus/core.py +++ b/pythainlp/corpus/core.py @@ -75,9 +75,9 @@ def get_corpus_db(url: str) -> Optional[_ResponseWrapper]: corpus_db = None try: - req = Request(url, headers={"User-Agent": _USER_AGENT}) + req = Request(url, headers={"User-Agent": _USER_AGENT}) # noqa: S310 # SSL certificate verification is enabled by default - with urlopen(req, timeout=10) as response: # nosec B310 + with urlopen(req, timeout=10) as response: # noqa: S310 # nosec B310 corpus_db = _ResponseWrapper(response) except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") @@ -213,7 +213,7 @@ def get_corpus_default_db(name: str, version: str = "") -> Optional[str]: corpus_path(), corpus_db[name]["versions"][version]["filename"], ) - elif not version: # load latest version + if not version: # load latest version version = corpus_db[name]["latest_version"] return safe_path_join( corpus_path(), @@ -386,9 +386,9 @@ def _download(url: str, dst: str, md5: str = "") -> int: """ from urllib.request import Request, urlopen - req = Request(url, headers={"User-Agent": _USER_AGENT}) + req = Request(url, headers={"User-Agent": _USER_AGENT}) # noqa: S310 # SSL certificate verification is enabled by default - with urlopen(req, timeout=10) as response: # nosec B310 + with urlopen(req, timeout=10) as response: # noqa: S310 # nosec B310 file_size = int(response.info().get("Content-Length", -1)) # Resolve links, so a link at *dst* stays and its target is replaced. file_path = os.path.realpath(get_full_data_path(dst)) @@ -616,7 +616,7 @@ def _safe_extract_tar(tar: tarfile.TarFile, path: str) -> None: members = tar.getmembers() for member in members: _check_tar_member(path, member) - tar.extractall( # nosec B202 + tar.extractall( # noqa: S202 # nosec B202 path=path, members=[_filter_tar_member(m) for m in members] ) return @@ -667,7 +667,7 @@ def _safe_extract_zip(zip_file: zipfile.ZipFile, path: str) -> None: os.path.dirname(info.filename), ) - zip_file.extractall(path=path) # nosec B202 + zip_file.extractall(path=path) # noqa: S202 # nosec B202 def _version2int(v: str) -> int: diff --git a/pythainlp/el/core.py b/pythainlp/el/core.py index a9ca988ef..8ef6d23f9 100644 --- a/pythainlp/el/core.py +++ b/pythainlp/el/core.py @@ -25,11 +25,11 @@ def __init__( self.model_name: str = model_name self.device: str = device self.tag: str = tag - if self.model_name not in ["bela"]: + if self.model_name != "bela": raise NotImplementedError( f"EntityLinker doesn't support {model_name} model." ) - if self.tag not in ["wikidata"]: + if self.tag != "wikidata": raise NotImplementedError( f"EntityLinker doesn't support {tag} tag." ) diff --git a/pythainlp/generate/core.py b/pythainlp/generate/core.py index 1220b8d68..36918d6ff 100644 --- a/pythainlp/generate/core.py +++ b/pythainlp/generate/core.py @@ -130,7 +130,7 @@ def _next_word( words = [] words.append(text) word_list = list(self._word_prob.keys()) - if N > len(word_list): + if len(word_list) < N: N = len(word_list) for _ in range(N): # Non-cryptographic use, pseudo-random generator is acceptable here diff --git a/pythainlp/khavee/core.py b/pythainlp/khavee/core.py index 2f5f7352c..a85c1daa0 100644 --- a/pythainlp/khavee/core.py +++ b/pythainlp/khavee/core.py @@ -840,8 +840,7 @@ def check_karu_lahu(self, text: str) -> Union[str, bool]: or sara in self._SPECIAL_VOWELS ): return "karu" - else: - return "lahu" + return "lahu" def check_klon(self, text: str, k_type: int = 8) -> Union[list[str], str]: """ @@ -1055,12 +1054,11 @@ def check_aek_too( if "่" in text and "้" not in text: return "aek" - elif "้" in text and "่" not in text: + if "้" in text and "่" not in text: return "too" if dead_syllable_as_aek and sound_syllable(text) == "dead": return "aek" - else: - return False + return False def handle_karun_sound_silence(self, word: str) -> str: """ @@ -1102,5 +1100,4 @@ def handle_karun_sound_silence(self, word: str) -> str: # สัตว์ (ว์), แพทย์ (ย์), พันธุ์ (ธุ์), สิทธิ์ (ธิ์) if len(word) >= 3 and word[-2] in {"ิ", "ี", "ึ", "ื", "ุ", "ู", "ั"}: return word[:-3] - else: - return word[:-2] + return word[:-2] diff --git a/pythainlp/lm/qwen3.py b/pythainlp/lm/qwen3.py index d98f65f98..aaebd5cd9 100644 --- a/pythainlp/lm/qwen3.py +++ b/pythainlp/lm/qwen3.py @@ -66,13 +66,12 @@ def load_model( torch_dtype = torch.float16 # Check CUDA availability early before loading model - if device.startswith("cuda"): - if not torch.cuda.is_available(): - raise RuntimeError( - "CUDA device requested but CUDA is not available. " - "Check your PyTorch installation and GPU drivers, or use " - "device='cpu' instead." - ) + if device.startswith("cuda") and not torch.cuda.is_available(): + raise RuntimeError( + "CUDA device requested but CUDA is not available. " + "Check your PyTorch installation and GPU drivers, or use " + "device='cpu' instead." + ) self.device = device self.torch_dtype = torch_dtype diff --git a/pythainlp/morpheme/thaiwordcheck.py b/pythainlp/morpheme/thaiwordcheck.py index 6f8eea39d..839754289 100644 --- a/pythainlp/morpheme/thaiwordcheck.py +++ b/pythainlp/morpheme/thaiwordcheck.py @@ -64,7 +64,7 @@ # Thai consonant filter # O ANG (U+0E2D) is omitted, as it can be considered as vowel -_TH_CONSONANTS_PATTERN: re.Pattern[str] = re.compile(r"[ก-ฬฮ]", re.U) +_TH_CONSONANTS_PATTERN: re.Pattern[str] = re.compile(r"[ก-ฬฮ]", re.UNICODE) def is_native_thai(word: str) -> bool: @@ -118,7 +118,4 @@ def is_native_thai(word: str) -> bool: # Note: This will not work, as it check the whole word, not the prefix. # Prefix-sensitive tokenization is required in order to be able to check this. - if word in _TH_PREFIX_DIPHTHONG: - return True - - return False + return word in _TH_PREFIX_DIPHTHONG diff --git a/pythainlp/parse/attaparse_engine.py b/pythainlp/parse/attaparse_engine.py index 09e464552..8debfa174 100644 --- a/pythainlp/parse/attaparse_engine.py +++ b/pythainlp/parse/attaparse_engine.py @@ -35,12 +35,12 @@ def __call__( # noqa: CCR001 # phase2-todo row = [ str(word.id), word.text, - word.lemma if word.lemma else "_", - word.upos if word.upos else "_", - word.xpos if word.xpos else "_", - word.feats if word.feats else "_", + word.lemma or "_", + word.upos or "_", + word.xpos or "_", + word.feats or "_", str(word.head), - word.deprel if word.deprel else "_", + word.deprel or "_", "_", # DEPS (enhanced dependencies, not provided) "SpaceAfter=No", # MISC: Thai text has no inter-word spaces ] diff --git a/pythainlp/parse/core.py b/pythainlp/parse/core.py index 6c7f6ad74..834cac299 100644 --- a/pythainlp/parse/core.py +++ b/pythainlp/parse/core.py @@ -99,14 +99,12 @@ def dependency_parsing( if engine == "esupar": from pythainlp.parse.esupar_engine import Parse - _tagger = Parse(model=model if model else "th") + _tagger = Parse(model=model or "th") elif engine == "transformers_ud": from pythainlp.parse.transformers_ud import Parse # type: ignore[assignment] # noqa: I001 _tagger = Parse( - model=model - if model - else "KoichiYasuoka/deberta-base-thai-ud-head" + model=model or "KoichiYasuoka/deberta-base-thai-ud-head" ) elif engine == "spacy_thai": from pythainlp.parse.spacy_thai_engine import Parse # type: ignore[assignment] # noqa: I001 @@ -116,9 +114,7 @@ def dependency_parsing( from pythainlp.parse.ud_goeswith import Parse # type: ignore[assignment] # noqa: I001 _tagger = Parse( - model=model - if model - else "KoichiYasuoka/deberta-base-thai-ud-goeswith" + model=model or "KoichiYasuoka/deberta-base-thai-ud-goeswith" ) elif engine == "attaparse": from pythainlp.parse.attaparse_engine import Parse # type: ignore[assignment] # noqa: I001 diff --git a/pythainlp/parse/ud_goeswith.py b/pythainlp/parse/ud_goeswith.py index dd9c21251..b1dd3b05e 100644 --- a/pythainlp/parse/ud_goeswith.py +++ b/pythainlp/parse/ud_goeswith.py @@ -104,26 +104,23 @@ def __call__( # noqa: CCR001 # phase2-todo ] ) return _tag_data - else: - for i, (s, e) in enumerate(v, 1): - q = self.model.config.id2label[p[i, h[i]]].split("|") - u += ( - "\t".join( - [ - str(i), - text[s:e], - "_", - q[0], - "_", - "|".join(q[1:-1]), - str(h[i]), - q[-1], - "_", - "_" - if i < len(v) and e < v[i][0] - else "SpaceAfter=No", - ] - ) - + "\n" + for i, (s, e) in enumerate(v, 1): + q = self.model.config.id2label[p[i, h[i]]].split("|") + u += ( + "\t".join( + [ + str(i), + text[s:e], + "_", + q[0], + "_", + "|".join(q[1:-1]), + str(h[i]), + q[-1], + "_", + "_" if i < len(v) and e < v[i][0] else "SpaceAfter=No", + ] ) - return u + "\n" + + "\n" + ) + return u + "\n" diff --git a/pythainlp/phayathaibert/core.py b/pythainlp/phayathaibert/core.py index f7a1a9f67..8314fab98 100644 --- a/pythainlp/phayathaibert/core.py +++ b/pythainlp/phayathaibert/core.py @@ -41,7 +41,7 @@ def __init__(self) -> None: self._TK_WREP, self._TK_URL, self._TK_END, - ) = " ".split() + ) = ["", "", "", "", ""] self.SPACE_SPECIAL_TOKEN: str = "<_>" # noqa: S105 def replace_url(self, text: str) -> str: diff --git a/pythainlp/soundex/complete_soundex.py b/pythainlp/soundex/complete_soundex.py index 61f264cc0..cc4735e54 100644 --- a/pythainlp/soundex/complete_soundex.py +++ b/pythainlp/soundex/complete_soundex.py @@ -283,10 +283,7 @@ def _map_leading_vowel_code(self, leading_vowel: str) -> tuple[str, str]: if leading_vowel: if leading_vowel == "โ": vowel_code = "7N" - elif leading_vowel == "ไ": - vowel_code = "1A" - final_code = "ย" - elif leading_vowel == "ใ": + elif leading_vowel == "ไ" or leading_vowel == "ใ": vowel_code = "1A" final_code = "ย" elif leading_vowel == "แ": @@ -395,13 +392,11 @@ def _check_special_format( return True if final_candidates and any(c in ["ญ", "ณ"] for c in final_candidates): return True - if ( + return bool( final_candidates and any(c == "น" for c in final_candidates) and vowel_code == "1A" - ): - return True - return False + ) def _apply_implicit_vowel( self, vowel_code: str, implicit_rule: Optional[str] @@ -424,15 +419,19 @@ def _adjust_so_sua_mapping( implicit_rule: Optional[str], ) -> str: """Special adjustments for ส (so sua) mapping.""" - if init_char == "ส" and init_code == "ซศ": - # Not for implicit splits - if implicit_rule is None and len(syl) >= 2: - # Simple syllable: ส + vowel, no other consonants except ร ล ว - consonants_after_init = [c for c in syl[1:] if "ก" <= c <= "ฮ"] - if not consonants_after_init or all( - c in "รลว" for c in consonants_after_init - ): - init_code = "ซซ" + # Not for implicit splits + if ( + init_char == "ส" + and init_code == "ซศ" + and implicit_rule is None + and len(syl) >= 2 + ): + # Simple syllable: ส + vowel, no other consonants except ร ล ว + consonants_after_init = [c for c in syl[1:] if "ก" <= c <= "ฮ"] + if not consonants_after_init or all( + c in "รลว" for c in consonants_after_init + ): + init_code = "ซซ" return init_code def _format_output( diff --git a/pythainlp/spell/words_spelling_correction.py b/pythainlp/spell/words_spelling_correction.py index 5dac74b24..5db0430e5 100644 --- a/pythainlp/spell/words_spelling_correction.py +++ b/pythainlp/spell/words_spelling_correction.py @@ -94,7 +94,7 @@ def _load_embeddings(self) -> tuple[list[str], NDArray[np.float32]]: words = [] vocab_path = safe_path_join(self.model_dir, "vocabulary.txt") with open(vocab_path, encoding="utf-8") as f: - for line in f.readlines(): + for line in f: words.append(line.rstrip()) return words, input_matrix diff --git a/pythainlp/summarize/keybert.py b/pythainlp/summarize/keybert.py index f572cd80d..e06b6a8b5 100644 --- a/pythainlp/summarize/keybert.py +++ b/pythainlp/summarize/keybert.py @@ -124,7 +124,7 @@ def extract_keywords( return [] # generate all lists of keywords / keyphrases - stop_words_ = stop_words if stop_words else thai_stopwords() + stop_words_ = stop_words or thai_stopwords() kw_candidates = _generate_ngrams( text, keyphrase_ngram_range, min_df, tokenizer, stop_words_ ) @@ -140,8 +140,7 @@ def extract_keywords( if return_similarity: return keywords - else: - return [kw for kw, _ in keywords] + return [kw for kw, _ in keywords] def embed(self, docs: Union[str, list[str]]) -> "NDArray[np.float32]": """Create embeddings by averaging vectors from the last hidden layer. diff --git a/pythainlp/tag/_tag_perceptron.py b/pythainlp/tag/_tag_perceptron.py index a9c9ddc5e..8b02b40cf 100644 --- a/pythainlp/tag/_tag_perceptron.py +++ b/pythainlp/tag/_tag_perceptron.py @@ -235,12 +235,11 @@ def _normalize(self, word: str) -> str: """ if "-" in word and word[0] != "-": return "!HYPHEN" - elif word.isdigit() and len(word) == 4: + if word.isdigit() and len(word) == 4: return "!YEAR" - elif word[0].isdigit(): + if word[0].isdigit(): return "!DIGITS" - else: - return word.lower() + return word.lower() def _get_features( self, i: int, word: str, context: list[str], prev: str, prev2: str diff --git a/pythainlp/tag/pos_tag.py b/pythainlp/tag/pos_tag.py index 7f5797d3f..af5661df0 100644 --- a/pythainlp/tag/pos_tag.py +++ b/pythainlp/tag/pos_tag.py @@ -231,7 +231,7 @@ def pos_tag_transformers( "mdeberta": "Pavarissy/mdeberta-v3-ud-thai-pud-upos", } - if corpus == "blackboard" and engine in _blackboard_support_engine.keys(): + if corpus == "blackboard" and engine in _blackboard_support_engine: base_model = _blackboard_support_engine.get(engine) model = AutoModelForTokenClassification.from_pretrained( base_model, revision=revision @@ -239,7 +239,7 @@ def pos_tag_transformers( tokenizer = AutoTokenizer.from_pretrained( base_model, revision=revision ) - elif corpus == "pud" and engine in _pud_support_engine.keys(): + elif corpus == "pud" and engine in _pud_support_engine: base_model = _pud_support_engine.get(engine) model = AutoModelForTokenClassification.from_pretrained( base_model, revision=revision diff --git a/pythainlp/tag/thai_nner.py b/pythainlp/tag/thai_nner.py index be016359f..25e50db2d 100644 --- a/pythainlp/tag/thai_nner.py +++ b/pythainlp/tag/thai_nner.py @@ -232,9 +232,8 @@ def get_ner( if tag: # Convert to HTML-like tags format return _entities_to_html(tokens, entities) - else: - # Convert to IOB format - return _entities_to_iob(tokens, entities) + # Convert to IOB format + return _entities_to_iob(tokens, entities) def _entities_to_iob( diff --git a/pythainlp/tag/wangchanberta_onnx.py b/pythainlp/tag/wangchanberta_onnx.py index 3a2353444..1a5cacc56 100644 --- a/pythainlp/tag/wangchanberta_onnx.py +++ b/pythainlp/tag/wangchanberta_onnx.py @@ -162,5 +162,4 @@ def get_ner( # noqa: CCR001 # phase2-todo sent += "" return sent - else: - return _tag + return _tag diff --git a/pythainlp/tokenize/_registry.py b/pythainlp/tokenize/_registry.py index 44e64cdc7..2de1a9218 100644 --- a/pythainlp/tokenize/_registry.py +++ b/pythainlp/tokenize/_registry.py @@ -202,7 +202,7 @@ def _crfcut(text: str) -> list[str]: def _whitespace(text: str) -> list[str]: - return re.split(r" +", text, flags=re.U) + return re.split(r" +", text, flags=re.UNICODE) def _whitespace_newline(text: str) -> list[str]: diff --git a/pythainlp/tokenize/core.py b/pythainlp/tokenize/core.py index ce7180726..178e843bc 100644 --- a/pythainlp/tokenize/core.py +++ b/pythainlp/tokenize/core.py @@ -335,10 +335,9 @@ def map_indices_to_words( start, end = c[0] if start > n_sum + len(words) - 1: break - else: - c.popleft() - word = sentence[start - n_sum : end + 1 - n_sum] - sentence_result.append(word) + c.popleft() + word = sentence[start - n_sum : end + 1 - n_sum] + sentence_result.append(word) result.append(sentence_result) n_sum += len(words) diff --git a/pythainlp/tokenize/han_solo.py b/pythainlp/tokenize/han_solo.py index 753ac0d27..52ab6e836 100644 --- a/pythainlp/tokenize/han_solo.py +++ b/pythainlp/tokenize/han_solo.py @@ -149,14 +149,13 @@ def featurize( "X": all_features_list, "Y": [str(label) for label in all_labels_int], } - else: - return { - "X": [ - dict.fromkeys(feature_list, 1) - for feature_list in all_features_list - ], - "Y": all_labels_int, - } + return { + "X": [ + dict.fromkeys(feature_list, 1) + for feature_list in all_features_list + ], + "Y": all_labels_int, + } _to_feature: Featurizer = Featurizer() diff --git a/pythainlp/tokenize/longest.py b/pythainlp/tokenize/longest.py index 3e86d1975..c31a2987a 100644 --- a/pythainlp/tokenize/longest.py +++ b/pythainlp/tokenize/longest.py @@ -105,11 +105,7 @@ def __is_next_word_valid(self, text: str, begin_pos: int) -> bool: if match: return True - for pos in range(len(text) + 1): - if text[0:pos] in self.__trie: - return True - - return False + return any(text[0:pos] in self.__trie for pos in range(len(text) + 1)) def __longest_matching(self, text: str, begin_pos: int) -> str: text = text[begin_pos:] diff --git a/pythainlp/tokenize/thaisumcut.py b/pythainlp/tokenize/thaisumcut.py index 1785bd797..e4ff04b47 100644 --- a/pythainlp/tokenize/thaisumcut.py +++ b/pythainlp/tokenize/thaisumcut.py @@ -202,10 +202,13 @@ def _remove_digit_spaces(sentence: str) -> str: if sentence[k].isdigit() and sentence[k - 1] == " ": sentence = sentence[: k - 1] + sentence[k:] sentence_len = len(sentence) - if k + 2 <= sentence_len: - if sentence[k].isdigit() and sentence[k + 1] == " ": - sentence = sentence[: k + 1] + sentence[k + 2 :] - sentence_len = len(sentence) + if ( + k + 2 <= sentence_len + and sentence[k].isdigit() + and sentence[k + 1] == " " + ): + sentence = sentence[: k + 1] + sentence[k + 2 :] + sentence_len = len(sentence) return sentence diff --git a/pythainlp/tokenize/wtsplit.py b/pythainlp/tokenize/wtsplit.py index 52c1a09e5..bcb9837d8 100644 --- a/pythainlp/tokenize/wtsplit.py +++ b/pythainlp/tokenize/wtsplit.py @@ -36,7 +36,7 @@ def _tokenize( # Thread-safe model loading global _MODEL, _MODEL_NAME with _model_lock: - if _MODEL_NAME != model: + if model != _MODEL_NAME: _MODEL = WtP(model_name_or_model=model) _MODEL_NAME = model model_instance = _MODEL @@ -49,33 +49,32 @@ def _tokenize( return cast( "list[str]", model_instance.split(text, lang_code=lang_code) ) - else: # Paragraph - if style == "newline": - return cast( - "list[str]", - model_instance.split( - text, - lang_code=lang_code, - do_paragraph_segmentation=True, - paragraph_threshold=paragraph_threshold, - ), - ) - elif style == "opus100": - return cast( - "list[str]", - model_instance.split( - text, - lang_code=lang_code, - do_paragraph_segmentation=True, - threshold=paragraph_threshold, - style=style, - ), - ) - else: - raise ValueError( - f"""Segmentation style \"{style}\" not found. + # Paragraph + if style == "newline": + return cast( + "list[str]", + model_instance.split( + text, + lang_code=lang_code, + do_paragraph_segmentation=True, + paragraph_threshold=paragraph_threshold, + ), + ) + if style == "opus100": + return cast( + "list[str]", + model_instance.split( + text, + lang_code=lang_code, + do_paragraph_segmentation=True, + threshold=paragraph_threshold, + style=style, + ), + ) + raise ValueError( + f"""Segmentation style \"{style}\" not found. It might be a typo; if not, please consult our document.""" - ) + ) def tokenize( diff --git a/pythainlp/translate/core.py b/pythainlp/translate/core.py index 02be10292..abf821869 100644 --- a/pythainlp/translate/core.py +++ b/pythainlp/translate/core.py @@ -253,7 +253,6 @@ def word_translate( from .word2word_translate import translate return translate(word=word, src=src, target=target) - else: - raise NotImplementedError( - f"pythainlp.translate.word_translate isn't support {engine}." - ) + raise NotImplementedError( + f"pythainlp.translate.word_translate isn't support {engine}." + ) diff --git a/pythainlp/translate/tokenization_small100.py b/pythainlp/translate/tokenization_small100.py index c77ba36df..bffe20146 100644 --- a/pythainlp/translate/tokenization_small100.py +++ b/pythainlp/translate/tokenization_small100.py @@ -338,19 +338,14 @@ def build_inputs_with_special_tokens( if token_ids_1 is None: if self.prefix_tokens is None: return token_ids_0 + self.suffix_tokens - else: - return self.prefix_tokens + token_ids_0 + self.suffix_tokens + return self.prefix_tokens + token_ids_0 + self.suffix_tokens # We don't expect to process pairs, # but leave the pair logic for API consistency if self.prefix_tokens is None: return token_ids_0 + token_ids_1 + self.suffix_tokens - else: - return ( - self.prefix_tokens - + token_ids_0 - + token_ids_1 - + self.suffix_tokens - ) + return ( + self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens + ) def get_vocab(self) -> dict[str, int]: vocab = { diff --git a/pythainlp/translate/word2word_translate.py b/pythainlp/translate/word2word_translate.py index 95e20d5c1..45dcd5cde 100644 --- a/pythainlp/translate/word2word_translate.py +++ b/pythainlp/translate/word2word_translate.py @@ -82,7 +82,7 @@ def translate(word: str, src: str, target: str) -> Optional[list[str]]: """ if src not in support_list or target not in support_list: raise NotImplementedError(f"word2word doesn't support {src}-{target}.") - elif src == target: + if src == target: return [word] _engine = Word2word(src, target) return cast("Optional[list[str]]", _engine(word)) diff --git a/pythainlp/transliterate/core.py b/pythainlp/transliterate/core.py index b18c89b88..f54ddc658 100644 --- a/pythainlp/transliterate/core.py +++ b/pythainlp/transliterate/core.py @@ -83,13 +83,12 @@ def select_romanize_engine(engine: str) -> Callable[[str], str]: fallback = select_romanize_engine(fallback_engine) return romanize(text, fallback_func=fallback) - else: - rom_engine = select_romanize_engine(engine) - trans_word = [] - for subword in text.split(" "): - trans_word.append(rom_engine(subword)) - new_word = " ".join(trans_word) - return new_word + rom_engine = select_romanize_engine(engine) + trans_word = [] + for subword in text.split(" "): + trans_word.append(rom_engine(subword)) + new_word = " ".join(trans_word) + return new_word def transliterate( diff --git a/pythainlp/util/morse.py b/pythainlp/util/morse.py index a942b9be7..e6f753f4e 100644 --- a/pythainlp/util/morse.py +++ b/pythainlp/util/morse.py @@ -155,12 +155,11 @@ def morse_encode(text: str, lang: str = "th") -> str: return " ".join( THAI_MORSE_CODE.get(char, " ") for char in text.upper() ) - elif lang == "en": # English + if lang == "en": # English return " ".join( ENGLISH_MORSE_CODE.get(char, " ") for char in text.upper() ) - else: - raise NotImplementedError(f"This function doesn't support {lang}.") + raise NotImplementedError(f"This function doesn't support {lang}.") def morse_decode(morse_text: str, lang: str = "th") -> str: @@ -187,10 +186,9 @@ def morse_decode(morse_text: str, lang: str = "th") -> str: decodingthai.get(code, "") for code in morse_text.split(" ") ) return "".join(ans.split()) - elif lang == "en": + if lang == "en": ans = "".join( decodingeng.get(code, " ") for code in morse_text.split(" ") ) return " ".join(ans.split()) - else: - raise NotImplementedError(f"This function doesn't support {lang}.") + raise NotImplementedError(f"This function doesn't support {lang}.") diff --git a/pythainlp/util/phoneme.py b/pythainlp/util/phoneme.py index 504486d6e..31dc01276 100644 --- a/pythainlp/util/phoneme.py +++ b/pythainlp/util/phoneme.py @@ -112,7 +112,7 @@ def nectec_to_ipa(pronunciation: str) -> str: parts = pronunciation.split("-") ipa = [] for part in parts: - if part in dict_nectec_to_ipa.keys(): + if part in dict_nectec_to_ipa: ipa.append(dict_nectec_to_ipa[part]) else: ipa.append(part) diff --git a/pythainlp/util/profanity.py b/pythainlp/util/profanity.py index 02c431f6f..2bc5f0051 100644 --- a/pythainlp/util/profanity.py +++ b/pythainlp/util/profanity.py @@ -57,11 +57,7 @@ def contains_profanity( tokens = word_tokenize(text, custom_dict=custom_dict, engine=engine) - for token in tokens: - if token in profanity_set: - return True - - return False + return any(token in profanity_set for token in tokens) def find_profanity( diff --git a/pythainlp/util/pronounce.py b/pythainlp/util/pronounce.py index 55880f4da..3118c5bb7 100644 --- a/pythainlp/util/pronounce.py +++ b/pythainlp/util/pronounce.py @@ -116,11 +116,11 @@ def tone_to_spelling(t: str) -> str: """ if t == "่": return "ไม้เอก" - elif t == "้": + if t == "้": return "ไม้โท" - elif t == "๊": + if t == "๊": return "ไม้ตรี" - elif t == "๋": + if t == "๋": return "ไม้จัตวา" return t @@ -141,7 +141,7 @@ def _spelling_impl(word: str) -> list[str]: tone = [tone_to_spelling(i) for i in word if i in thai_tonemarks] word_output = word_pre for i, j in thai_vowel_all: - if len(re.findall(i, word_pre, re.U)) > 0: + if len(re.findall(i, word_pre, re.UNICODE)) > 0: if "็" in word and i == "เ([ก-ฮ])": word_output = re.sub(i, "\\1เอะ", word_pre) else: @@ -155,12 +155,11 @@ def _spelling_impl(word: str) -> list[str]: ] if word_pre == word: return output + [word] - elif tone != []: + if tone != []: return output + [word_pre, tone[0], word] - elif "็" in word: + if "็" in word: return output + [word] - else: - return output + [word_pre, word] + return output + [word_pre, word] def spelling(word: str) -> list[str]: diff --git a/pythainlp/util/syllable.py b/pythainlp/util/syllable.py index e37775662..d57d3cea0 100644 --- a/pythainlp/util/syllable.py +++ b/pythainlp/util/syllable.py @@ -33,9 +33,11 @@ # vowel's short sound short: str = "ะัิึุ" re_short: Pattern[str] = re.compile( - "เ(.*)ะ|แ(.*)ะ|เ(.*)อะ|โ(.*)ะ|เ(.*)าะ", re.U + "เ(.*)ะ|แ(.*)ะ|เ(.*)อะ|โ(.*)ะ|เ(.*)าะ", re.UNICODE ) -pattern: Pattern[str] = re.compile("เ(.*)า", re.U) # เ-า is live syllable +pattern: Pattern[str] = re.compile( + "เ(.*)า", re.UNICODE +) # เ-า is live syllable _check_1: list[str] = [] # These spelling consonants are live syllables. @@ -240,10 +242,7 @@ def _check_sonorant_syllable(syllable: str) -> bool: if _sonorant[-1] == consonants[-2]: return True - if _sonorant[-1] == consonants[-1]: - return True - - return False + return _sonorant[-1] == consonants[-1] def _tone_ah_sonorant(initial: str, sound: str, tone_mark: str) -> str: diff --git a/pythainlp/util/thai.py b/pythainlp/util/thai.py index 95b923f90..6a0a0f071 100644 --- a/pythainlp/util/thai.py +++ b/pythainlp/util/thai.py @@ -100,9 +100,7 @@ def is_thai_char(ch: str) -> bool: True """ ch_val = ord(ch) - if _TH_FIRST_CHAR_ASCII <= ch_val <= _TH_LAST_CHAR_ASCII: - return True - return False + return _TH_FIRST_CHAR_ASCII <= ch_val <= _TH_LAST_CHAR_ASCII def isthaichar(ch: str) -> bool: @@ -272,8 +270,7 @@ def display_thai_char(ch: str) -> str: ): # last condition is Sra Aum, Thanthakhat, Nikhahit, Yamakkan return "_" + ch - else: - return ch + return ch def thai_word_tone_detector(word: Optional[str]) -> list[tuple[str, str]]: diff --git a/pythainlp/util/thai_lunar_date.py b/pythainlp/util/thai_lunar_date.py index fb8ef0281..44f60d706 100644 --- a/pythainlp/util/thai_lunar_date.py +++ b/pythainlp/util/thai_lunar_date.py @@ -290,7 +290,7 @@ def deviation(year: int) -> float: def last_day_in_year(year: int) -> int: if athikamas(year): return 384 - elif athikavar(year): + if athikavar(year): return 355 return 354 @@ -305,11 +305,9 @@ def athikasurathin(year: int) -> bool: """ if year % 400 == 0: return True - elif year % 100 == 0: + if year % 100 == 0: return False - elif year % 4 == 0: - return True - return False + return year % 4 == 0 def number_day_in_year(year: int) -> int: diff --git a/pythainlp/util/time.py b/pythainlp/util/time.py index 274c3bf3a..b03c9593e 100644 --- a/pythainlp/util/time.py +++ b/pythainlp/util/time.py @@ -8,6 +8,7 @@ from __future__ import annotations +from contextlib import suppress from datetime import datetime, time from functools import lru_cache from typing import Callable, Optional, Union @@ -227,10 +228,8 @@ def time_to_thaiword( try: _time = datetime.strptime(time_data, _TIME_FORMAT_WITH_SEC) except ValueError: - try: + with suppress(ValueError): _time = datetime.strptime(time_data, _TIME_FORMAT_WITHOUT_SEC) - except ValueError: - pass if not _time: raise ValueError( diff --git a/pythainlp/util/wordtonum.py b/pythainlp/util/wordtonum.py index d76e3682d..18e70f122 100644 --- a/pythainlp/util/wordtonum.py +++ b/pythainlp/util/wordtonum.py @@ -211,10 +211,7 @@ def text_to_num(text: str) -> list[str]: if isthainum and last_index + 1 == i and i + 1 == len(_temp): thainum.append(word) _flush(thainum, list_word_new) - elif isthainum and last_index + 1 == i: - thainum.append(word) - last_index = i - elif isthainum: + elif isthainum and last_index + 1 == i or isthainum: thainum.append(word) last_index = i elif not isthainum and last_index + 1 == i and last_index != -1: diff --git a/pythainlp/wangchanberta/core.py b/pythainlp/wangchanberta/core.py index c461a0b45..d5c686e04 100644 --- a/pythainlp/wangchanberta/core.py +++ b/pythainlp/wangchanberta/core.py @@ -131,11 +131,13 @@ def get_ner( # noqa: C901, CCR001 # phase2-todo if self.sent_ner[0][0] == "" and len(self.sent_ner) > 1: self.sent_ner = self.sent_ner[1:] for idx, (word, ner) in enumerate(self.sent_ner): - if idx > 0 and ner.startswith("B-"): - if self._clear_tag(ner) == self._clear_tag( - self.sent_ner[idx - 1][1] - ): - self.sent_ner[idx] = (word, ner.replace("B-", "I-")) + if ( + idx > 0 + and ner.startswith("B-") + and self._clear_tag(ner) + == self._clear_tag(self.sent_ner[idx - 1][1]) + ): + self.sent_ner[idx] = (word, ner.replace("B-", "I-")) if tag: temp = "" sent = "" @@ -156,8 +158,7 @@ def get_ner( # noqa: C901, CCR001 # phase2-todo sent += "" return sent - else: - return self.sent_ner + return self.sent_ner class NamedEntityRecognition: diff --git a/tests/core/test_corpus_core_internals.py b/tests/core/test_corpus_core_internals.py index 6367b7e10..71b0bb316 100644 --- a/tests/core/test_corpus_core_internals.py +++ b/tests/core/test_corpus_core_internals.py @@ -916,8 +916,10 @@ def test_rejects(self) -> None: # Absolute targets are rejected, as in tar ( [("link", b"/etc/passwd", True)], - "Symlink link points outside extraction directory: " - "/etc/passwd", + ( + "Symlink link points outside extraction directory: " + "/etc/passwd" + ), ), ( [("link", b"/../../x", True)], diff --git a/tests/core/test_tokenize_newmm_internals.py b/tests/core/test_tokenize_newmm_internals.py index 7b0dbb6b4..8be63bd9c 100644 --- a/tests/core/test_tokenize_newmm_internals.py +++ b/tests/core/test_tokenize_newmm_internals.py @@ -58,9 +58,11 @@ # Each case: text, dictionary name, safe_mode, expected outcome. _GOLDEN: list[list[Any]] = [ [ - "กเธอ@แมวข้าวกกกข้าวเทศพลันๆกลับึดีบ้านไป@ญ!!ประเทศมากประ日本เฉียบกงานบ้านไปผมๆกกถนน " - "ถนนบ้านใหญ่ไทยเฉียบพลันไทยฉฏ1,234.5เฉียบเธอเฉียบเฉียบข้าว!!พลันabcประเทศ์ประ\n" - "@1,234.5ถนนกกเฉียบพลันข้าว", + ( + "กเธอ@แมวข้าวกกกข้าวเทศพลันๆกลับึดีบ้านไป@ญ!!ประเทศมากประ日本เฉียบกงานบ้านไปผมๆกกถนน " + "ถนนบ้านใหญ่ไทยเฉียบพลันไทยฉฏ1,234.5เฉียบเธอเฉียบเฉียบข้าว!!พลันabcประเทศ์ประ\n" + "@1,234.5ถนนกกเฉียบพลันข้าว" + ), "A", True, [ @@ -181,9 +183,11 @@ ["ok", ["!!日本", "ญ", "เทศ", "ไทย", " ", "1,234.5", "เฉียบ", "ฤๅ"]], ], [ - "เฉียบพลันเทศงานฝ่เกมทำ日本ผม่1,234.5รถปวด\n" - "กาข้าวกฤๅโรงเรียนโรงเรียนเทศทำขรถกลับพลันฤๅปวดเล่น\r\n" - "-x", + ( + "เฉียบพลันเทศงานฝ่เกมทำ日本ผม่1,234.5รถปวด\n" + "กาข้าวกฤๅโรงเรียนโรงเรียนเทศทำขรถกลับพลันฤๅปวดเล่น\r\n" + "-x" + ), "A", True, [ @@ -241,9 +245,11 @@ ], ], [ - "ปวดน้ำไทยขไทยโรงเรียนญงานฯํประเล่นฉฏกกข้าวไปประภาษารถึฮดีๅใหญ่กลับรถ\t" - "ขแมวน้ำํประ1,234.5กลับไป แมว\n" - "ใหญ่กลับโรงเรียนฯใหญ่การ123เล่นรถเฉียบประไทยใหญ่โรงเรียนข้าวฯเทศ", + ( + "ปวดน้ำไทยขไทยโรงเรียนญงานฯํประเล่นฉฏกกข้าวไปประภาษารถึฮดีๅใหญ่กลับรถ\t" + "ขแมวน้ำํประ1,234.5กลับไป แมว\n" + "ใหญ่กลับโรงเรียนฯใหญ่การ123เล่นรถเฉียบประไทยใหญ่โรงเรียนข้าวฯเทศ" + ), "A", True, [ @@ -332,15 +338,17 @@ ], ], [ - " ถนน日本 ข้าวฟทำข้าวดีฤๅฟไป มากพลันไทยปวดฯ\n" - "ทำทำน้ำกา แมวญ日本ไปแมวฟใหญ่ กินกกพลันึเล่น!!\n" - "โรงเรียนมาก โรงเรียนฤๅเล่นไป กา ฮฮ123 ฯไทย ํญประกก\r\n" - "@ๆ !!ประ บ้านบ้านพลันถนนทำเทศน้ำฤๅประเทศ กกabcขบ้าน เธอการปวดไทย \t" - "เทศ-xเล่นถนนๅกลับ123เทศไทย เธอผม!!日本กก ประประโรงเรียนๆฟฮเธอ " - "รถเฉียบพลันเธอโรงเรียนเกม1,234.5ํ เฉียบพลันกลับ ปวดabc ่\n" - "ภาษากการโรงเรียนฯ งานเฉียบพลันเฉียบ ฟพลัน เฉียบพลัน ๆแมว \r\n" - "ภาษาบ้านทำึประเทศรถกกลับก 123การเฉียบabcฯเกมึHello\n" - "ก พลันประเทศ!! เทศผมผม", + ( + " ถนน日本 ข้าวฟทำข้าวดีฤๅฟไป มากพลันไทยปวดฯ\n" + "ทำทำน้ำกา แมวญ日本ไปแมวฟใหญ่ กินกกพลันึเล่น!!\n" + "โรงเรียนมาก โรงเรียนฤๅเล่นไป กา ฮฮ123 ฯไทย ํญประกก\r\n" + "@ๆ !!ประ บ้านบ้านพลันถนนทำเทศน้ำฤๅประเทศ กกabcขบ้าน เธอการปวดไทย \t" + "เทศ-xเล่นถนนๅกลับ123เทศไทย เธอผม!!日本กก ประประโรงเรียนๆฟฮเธอ " + "รถเฉียบพลันเธอโรงเรียนเกม1,234.5ํ เฉียบพลันกลับ ปวดabc ่\n" + "ภาษากการโรงเรียนฯ งานเฉียบพลันเฉียบ ฟพลัน เฉียบพลัน ๆแมว \r\n" + "ภาษาบ้านทำึประเทศรถกกลับก 123การเฉียบabcฯเกมึHello\n" + "ก พลันประเทศ!! เทศผมผม" + ), "A", True, [ @@ -553,9 +561,11 @@ ["์ๅ่แมวเฉียบ", "A", False, ["ok", ["์ๅ่", "แมว", "เฉียบ"]]], ["ไปกลับ\tๆฝ", "A", False, ["ok", ["ไป", "กลับ", "\t", "ๆ", "ฝ"]]], [ - "ไทยรถเทศ์ทำญ์การน้ำปวด!!ข้าวใหญ่กลับกกงานประเทศเล่นแมวHelloผมดี " - "ภาษาฤๅฝ1,234.5กินก์แมวปวดโรงเรียนประเทศแมวกลับฉฏ์น้ำถนน่!!ึ日本รถดีเกมใหญ่ประเทศกน้ำฤๅกabc์ข้าว " - "กึ\r\n", + ( + "ไทยรถเทศ์ทำญ์การน้ำปวด!!ข้าวใหญ่กลับกกงานประเทศเล่นแมวHelloผมดี " + "ภาษาฤๅฝ1,234.5กินก์แมวปวดโรงเรียนประเทศแมวกลับฉฏ์น้ำถนน่!!ึ日本รถดีเกมใหญ่ประเทศกน้ำฤๅกabc์ข้าว " + "กึ\r\n" + ), "A", True, [ diff --git a/tests/core/test_util_strftime.py b/tests/core/test_util_strftime.py index cf39e805f..0d0a95c23 100644 --- a/tests/core/test_util_strftime.py +++ b/tests/core/test_util_strftime.py @@ -492,33 +492,51 @@ "พฤ 31 ธ.ค. 13:05:07 2563|พฤ 31 ธ.ค. 2563 13:05:07|13:05:07|31/12/2563|2563-12-31", "พฤ 29 ก.พ. 12:00:00 2567|พฤ 29 ก.พ. 2567 12:00:00|12:00:00|29/02/2567|2567-02-29", "อา 3 ม.ค. 18:30:45 2564|อา 3 ม.ค. 2564 18:30:45|18:30:45|03/01/2564|2564-01-03", - "ศ 31 ธ.ค. 23:59:59 10542|ศ 31 ธ.ค. 10542 " - "23:59:59|23:59:59|31/12/10542|10542-12-31", + ( + "ศ 31 ธ.ค. 23:59:59 10542|ศ 31 ธ.ค. 10542 " + "23:59:59|23:59:59|31/12/10542|10542-12-31" + ), ), ), ( "%A%a%B%b%C%c%D%F%G%g%v%X%x%Y%y%+%%", ( - "วันพุธพตุลาคมต.ค.26พ 6 ต.ค. 01:40:00 251910/06/192519-10-06251919 " - "6-ต.ค.-251901:40:0006/10/2519251919พ 6 ต.ค. 2519 01:40:00%", - "วันอาทิตย์อามิถุนายนมิ.ย.26อา 9 มิ.ย. 05:59:00 256206/09/622562-06-09256262 " - "9-มิ.ย.-256205:59:0009/06/2562256262อา 9 มิ.ย. 2562 05:59:00%", - "วันจันทร์จมกราคมม.ค.06จ 1 ม.ค. 00:00:00 054401/01/440544-01-01054444 " - "1-ม.ค.-054400:00:0001/01/0544054444จ 1 ม.ค. 544 00:00:00%", - "วันอังคารอธันวาคมธ.ค.16อ 31 ธ.ค. 23:59:59 " - "154212/31/421542-12-3115434331-ธ.ค.-154223:59:5931/12/1542154242อ 31 ธ.ค. 1542 " - "23:59:59%", - "วันพฤหัสบดีพฤธันวาคมธ.ค.26พฤ 31 ธ.ค. 13:05:07 " - "256312/31/632563-12-3125636331-ธ.ค.-256313:05:0731/12/2563256363พฤ 31 ธ.ค. 2563 " - "13:05:07%", - "วันพฤหัสบดีพฤกุมภาพันธ์ก.พ.26พฤ 29 ก.พ. 12:00:00 " - "256702/29/672567-02-2925676729-ก.พ.-256712:00:0029/02/2567256767พฤ 29 ก.พ. 2567 " - "12:00:00%", - "วันอาทิตย์อามกราคมม.ค.26อา 3 ม.ค. 18:30:45 256401/03/642564-01-03256363 " - "3-ม.ค.-256418:30:4503/01/2564256464อา 3 ม.ค. 2564 18:30:45%", - "วันศุกร์ศธันวาคมธ.ค.106ศ 31 ธ.ค. 23:59:59 " - "1054212/31/4210542-12-31105424231-ธ.ค.-1054223:59:5931/12/105421054242ศ 31 ธ.ค. " - "10542 23:59:59%", + ( + "วันพุธพตุลาคมต.ค.26พ 6 ต.ค. 01:40:00 251910/06/192519-10-06251919 " + "6-ต.ค.-251901:40:0006/10/2519251919พ 6 ต.ค. 2519 01:40:00%" + ), + ( + "วันอาทิตย์อามิถุนายนมิ.ย.26อา 9 มิ.ย. 05:59:00 256206/09/622562-06-09256262 " + "9-มิ.ย.-256205:59:0009/06/2562256262อา 9 มิ.ย. 2562 05:59:00%" + ), + ( + "วันจันทร์จมกราคมม.ค.06จ 1 ม.ค. 00:00:00 054401/01/440544-01-01054444 " + "1-ม.ค.-054400:00:0001/01/0544054444จ 1 ม.ค. 544 00:00:00%" + ), + ( + "วันอังคารอธันวาคมธ.ค.16อ 31 ธ.ค. 23:59:59 " + "154212/31/421542-12-3115434331-ธ.ค.-154223:59:5931/12/1542154242อ 31 ธ.ค. 1542 " + "23:59:59%" + ), + ( + "วันพฤหัสบดีพฤธันวาคมธ.ค.26พฤ 31 ธ.ค. 13:05:07 " + "256312/31/632563-12-3125636331-ธ.ค.-256313:05:0731/12/2563256363พฤ 31 ธ.ค. 2563 " + "13:05:07%" + ), + ( + "วันพฤหัสบดีพฤกุมภาพันธ์ก.พ.26พฤ 29 ก.พ. 12:00:00 " + "256702/29/672567-02-2925676729-ก.พ.-256712:00:0029/02/2567256767พฤ 29 ก.พ. 2567 " + "12:00:00%" + ), + ( + "วันอาทิตย์อามกราคมม.ค.26อา 3 ม.ค. 18:30:45 256401/03/642564-01-03256363 " + "3-ม.ค.-256418:30:4503/01/2564256464อา 3 ม.ค. 2564 18:30:45%" + ), + ( + "วันศุกร์ศธันวาคมธ.ค.106ศ 31 ธ.ค. 23:59:59 " + "1054212/31/4210542-12-31105424231-ธ.ค.-1054223:59:5931/12/105421054242ศ 31 ธ.ค. " + "10542 23:59:59%" + ), ), ), ("", ("", "", "", "", "", "", "", "")), diff --git a/tests/core/test_util_thai.py b/tests/core/test_util_thai.py index 3f778cd8f..428bddd83 100644 --- a/tests/core/test_util_thai.py +++ b/tests/core/test_util_thai.py @@ -30,9 +30,11 @@ _SINGLE_CHAR = [ ( ("non_thai",), - " " - "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x00\n" - "é\u200b—一\u0e80", + ( + " " + "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x00\n" + "é\u200b—一\u0e80" + ), ), (("consonants",), "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ"), (("vowels", "non_thai"), "ฤฦ"), diff --git a/tests/extra/testx_khavee.py b/tests/extra/testx_khavee.py index 57b0634fd..e8b2cbc06 100644 --- a/tests/extra/testx_khavee.py +++ b/tests/extra/testx_khavee.py @@ -70,8 +70,10 @@ def test_check_klon4_incorrect_poem(self): self.assertEqual( result, [ - "Rhyme error in Stanza (บทที่) 1: 'สวด' (Wak 1) " - "does not rhyme with ['ระ', 'รวย'] (Wak 2)" + ( + "Rhyme error in Stanza (บทที่) 1: 'สวด' (Wak 1) " + "does not rhyme with ['ระ', 'รวย'] (Wak 2)" + ) ], ) @@ -86,10 +88,14 @@ def test_check_klon4_incorrect_poem_2(self): self.assertEqual( result, [ - "Rhyme error in Stanza (บทที่) 1: " - "'สวด' (Wak 1) does not rhyme with ['ระ', 'รวย'] (Wak 2)", - "Inter-stanza rhyme error (ผิดสัมผัสระหว่างบท) between Stanza 1 and 2: " - "'นะ' (Wak 4) does not rhyme with 'มา' (Wak 2)", + ( + "Rhyme error in Stanza (บทที่) 1: " + "'สวด' (Wak 1) does not rhyme with ['ระ', 'รวย'] (Wak 2)" + ), + ( + "Inter-stanza rhyme error (ผิดสัมผัสระหว่างบท) between Stanza 1 and 2: " + "'นะ' (Wak 4) does not rhyme with 'มา' (Wak 2)" + ), ], ) @@ -157,10 +163,14 @@ def test_check_klon8_invalid_poem(self): self.assertEqual( result, [ - "Stanza (บทที่) 1 Wak 1: Word count exceeds 10: " - "['แม่', 'รัก', 'ลูก', 'ลูก', 'ก็', 'รู้', 'อยู่', 'ว่า', 'รัก', 'มาก', 'มาก']", - "Rhyme error in Stanza (บทที่) 1: 'มาก' (Wak 1) does not rhyme with " - "['คน', 'อื่น', 'สัก', 'หมื่น', 'แสน'] (Wak 2)", + ( + "Stanza (บทที่) 1 Wak 1: Word count exceeds 10: " + "['แม่', 'รัก', 'ลูก', 'ลูก', 'ก็', 'รู้', 'อยู่', 'ว่า', 'รัก', 'มาก', 'มาก']" + ), + ( + "Rhyme error in Stanza (บทที่) 1: 'มาก' (Wak 1) does not rhyme with " + "['คน', 'อื่น', 'สัก', 'หมื่น', 'แสน'] (Wak 2)" + ), ], ) @@ -177,10 +187,14 @@ def test_check_klon8_invalid_poem_2(self): self.assertEqual( result, [ - "Rhyme error in Stanza (บทที่) 1: 'มาก' (Wak 1) " - "does not rhyme with ['คน', 'อื่น', 'สัก', 'หมื่น', 'แสน'] (Wak 2)", - "Rhyme error in Stanza (บทที่) 1: 'เตือน' (Wak 3) does not rhyme with " - "['จะ', 'จาก', 'เรือ', 'ร้าง', 'แม่'] (Wak 4)", + ( + "Rhyme error in Stanza (บทที่) 1: 'มาก' (Wak 1) " + "does not rhyme with ['คน', 'อื่น', 'สัก', 'หมื่น', 'แสน'] (Wak 2)" + ), + ( + "Rhyme error in Stanza (บทที่) 1: 'เตือน' (Wak 3) does not rhyme with " + "['จะ', 'จาก', 'เรือ', 'ร้าง', 'แม่'] (Wak 4)" + ), ], ) @@ -197,10 +211,14 @@ def test_check_klon8_invalid_poem_3(self): self.assertEqual( result, [ - "Rhyme error in Stanza (บทที่) 1: 'เหมือน' (Wak 2) " - "does not rhyme with 'เตือด' (Wak 3)", - "Rhyme error in Stanza (บทที่) 1: 'เตือด' (Wak 3) " - "does not rhyme with ['จะ', 'จาก', 'เรือน', 'ร้าง', 'แม่'] (Wak 4)", + ( + "Rhyme error in Stanza (บทที่) 1: 'เหมือน' (Wak 2) " + "does not rhyme with 'เตือด' (Wak 3)" + ), + ( + "Rhyme error in Stanza (บทที่) 1: 'เตือด' (Wak 3) " + "does not rhyme with ['จะ', 'จาก', 'เรือน', 'ร้าง', 'แม่'] (Wak 4)" + ), ], ) @@ -217,9 +235,11 @@ def test_check_klon8_invalid_poem_4(self): self.assertEqual( result, [ - "Inter-stanza rhyme error (ผิดสัมผัสระหว่างบท) " - "between Stanza 1 and 2: 'ตัง' (Wak 4) " - "does not rhyme with 'หัว' (Wak 2)" + ( + "Inter-stanza rhyme error (ผิดสัมผัสระหว่างบท) " + "between Stanza 1 and 2: 'ตัง' (Wak 4) " + "does not rhyme with 'หัว' (Wak 2)" + ) ], ) @@ -244,9 +264,13 @@ def test_check_klon(self): self.assertEqual( result_invalid, [ - "Rhyme error in Stanza (บทที่) 1: 'ไล่' (Wak 3) " - "does not rhyme with ['น้อง', 'หมา'] (Wak 4)", - "Rhyme error in Stanza (บทที่) 2: 'โหด' (Wak 1) " - "does not rhyme with ['เอ๋ง', 'เอ๋ง'] (Wak 2)", + ( + "Rhyme error in Stanza (บทที่) 1: 'ไล่' (Wak 3) " + "does not rhyme with ['น้อง', 'หมา'] (Wak 4)" + ), + ( + "Rhyme error in Stanza (บทที่) 2: 'โหด' (Wak 1) " + "does not rhyme with ['เอ๋ง', 'เอ๋ง'] (Wak 2)" + ), ], ) diff --git a/tests/extra/testx_ulmfit.py b/tests/extra/testx_ulmfit.py index 36fd10635..4e370a59b 100644 --- a/tests/extra/testx_ulmfit.py +++ b/tests/extra/testx_ulmfit.py @@ -227,7 +227,7 @@ def test_document_vector(self): # Security note: pickle.load() executes arbitrary code if file is malicious. # These corpus files come from a trusted source with MD5 verification. with open(cast("str", thwiki["itos_fname"]), "rb") as f: - thwiki_itos = pickle.load(f) + thwiki_itos = pickle.load(f) # noqa: S301 thwiki_vocab = fastai.text.transform.Vocab(thwiki_itos) tt = Tokenizer( tok_func=ThaiTokenizer, From 871420153bb81a40c6ac5ba4c28366bb5da87647 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:37:52 +0100 Subject: [PATCH 4/8] fix _read_file Signed-off-by: Arthit Suriyawongkul --- pythainlp/cli/benchmark.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pythainlp/cli/benchmark.py b/pythainlp/cli/benchmark.py index cf7e3be15..dc9eaa866 100644 --- a/pythainlp/cli/benchmark.py +++ b/pythainlp/cli/benchmark.py @@ -20,8 +20,7 @@ def _read_file(path: str) -> list[str]: with open(path, encoding="utf-8") as f: - lines = (r.strip() for r in f) - return list(lines) + return [r.strip() for r in f] class App: From 102c5c81e331e319f74088950007b2cb69978357 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:42:34 +0100 Subject: [PATCH 5/8] Add test_branches_offline Signed-off-by: Arthit Suriyawongkul --- tests/core/__init__.py | 1 + tests/core/test_branches_offline.py | 119 ++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 tests/core/test_branches_offline.py diff --git a/tests/core/__init__.py b/tests/core/__init__.py index 1eed2fa6b..6a8834ff2 100644 --- a/tests/core/__init__.py +++ b/tests/core/__init__.py @@ -16,6 +16,7 @@ "tests.core.test_benchmarks_metrics", "tests.core.test_braille", "tests.core.test_cli", + "tests.core.test_branches_offline", "tests.core.test_corpus", "tests.core.test_corpus_core_internals", "tests.core.test_generate", diff --git a/tests/core/test_branches_offline.py b/tests/core/test_branches_offline.py new file mode 100644 index 000000000..3a9b96542 --- /dev/null +++ b/tests/core/test_branches_offline.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project +# SPDX-FileType: SOURCE +# SPDX-License-Identifier: Apache-2.0 +"""Offline tests for branches in spelling, profanity, and POS tagging. + +These cover code that is otherwise tested only with a downloaded corpus +or model. ``transformers`` and the profanity corpus are replaced with fakes. +""" + +import sys +import types +import unittest +from contextlib import ExitStack +from typing import Any +from unittest import mock + +from pythainlp.tag import pos_tag_transformers +from pythainlp.util import contains_profanity +from pythainlp.util.pronounce import spelling + +# (word, expected spelling): short vowel mark, tone marks, no change +_SPELLING = [ + ("กา", ["กอ", "อา", "กา"]), + ("เด็ก", ["ดอ", "เอะ", "กอ", "เด็ก"]), + ("น้ำ", ["นอ", "อำ", "นำ", "ไม้โท", "น้ำ"]), + ("เรื่อง", ["รอ", "เอือ", "งอ", "เรือง", "ไม้เอก", "เรื่อง"]), +] + + +class SpellingBranchesTestCase(unittest.TestCase): + def test_spelling(self) -> None: + for word, expected in _SPELLING: + with self.subTest(word=word): + self.assertEqual(spelling(word), expected) + + +class ContainsProfanityTestCase(unittest.TestCase): + def check(self, tokens: list[str], expected: bool, **kwargs: Any) -> None: + patches = { + "thai_profanity_words": frozenset({"คำหยาบ"}), + "thai_words": frozenset({"สวัสดี"}), + "word_tokenize": tokens, + } + with ExitStack() as stack: + for name, value in patches.items(): + stack.enter_context( + mock.patch( + f"pythainlp.util.profanity.{name}", return_value=value + ) + ) + self.assertIs(contains_profanity("x", **kwargs), expected) + + def test_found(self) -> None: + self.check(["สวัสดี", "คำหยาบ"], True) + + def test_not_found(self) -> None: + self.check(["สวัสดี"], False) + + def test_custom_words(self) -> None: + self.check(["คำใหม่"], True, custom_words={"คำใหม่"}) + + def test_empty_text(self) -> None: + self.assertIs(contains_profanity(""), False) + + +def _fake_transformers() -> tuple[types.ModuleType, mock.Mock]: + """Return a fake ``transformers`` module and its model loader.""" + module = types.ModuleType("transformers") + model_loader = mock.Mock() + auto_model = mock.Mock() + auto_model.from_pretrained = model_loader + auto_tokenizer = mock.Mock() + pipeline = mock.Mock( + return_value=mock.Mock( + return_value=[{"word": "แมว", "entity_group": "NOUN"}] + ) + ) + module.AutoModelForTokenClassification = auto_model # type: ignore[attr-defined] + module.AutoTokenizer = auto_tokenizer # type: ignore[attr-defined] + module.TokenClassificationPipeline = pipeline # type: ignore[attr-defined] + return module, model_loader + + +class PosTagTransformersTestCase(unittest.TestCase): + def run_tag(self, **kwargs: Any) -> tuple[Any, mock.Mock]: + module, model_loader = _fake_transformers() + with mock.patch.dict(sys.modules, {"transformers": module}): + result = pos_tag_transformers("แมว", **kwargs) + return result, model_loader + + def test_blackboard_corpus(self) -> None: + result, loader = self.run_tag(engine="bert", corpus="blackboard") + self.assertEqual(result, [[("แมว", "NOUN")]]) + loader.assert_called_once_with("lunarlist/pos_thai", revision=None) + + def test_pud_corpus(self) -> None: + result, loader = self.run_tag(engine="mdeberta", corpus="pud") + self.assertEqual(result, [[("แมว", "NOUN")]]) + loader.assert_called_once_with( + "Pavarissy/mdeberta-v3-ud-thai-pud-upos", revision=None + ) + + def test_unsupported_engine_or_corpus(self) -> None: + for kwargs in ( + {"engine": "mdeberta", "corpus": "blackboard"}, + {"engine": "bert", "corpus": "pud"}, + {"engine": "bert", "corpus": "other"}, + ): + with self.subTest(**kwargs), self.assertRaises(ValueError): + self.run_tag(**kwargs) + + def test_empty_sentence(self) -> None: + module, _ = _fake_transformers() + with mock.patch.dict(sys.modules, {"transformers": module}): + self.assertEqual(pos_tag_transformers(""), []) + + +if __name__ == "__main__": + unittest.main() From a038926e262fa7e0f6b5815bb1e2d286e0892355 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:50:44 +0100 Subject: [PATCH 6/8] Add benchmark CLI and offline summarize tests Signed-off-by: Arthit Suriyawongkul --- tests/core/__init__.py | 2 + tests/core/test_branches_offline.py | 122 ++++++++----------- tests/core/test_cli_benchmark.py | 168 +++++++++++++++++++++++++++ tests/core/test_summarize_offline.py | 141 ++++++++++++++++++++++ 4 files changed, 361 insertions(+), 72 deletions(-) create mode 100644 tests/core/test_cli_benchmark.py create mode 100644 tests/core/test_summarize_offline.py diff --git a/tests/core/__init__.py b/tests/core/__init__.py index 6a8834ff2..2d42f0e79 100644 --- a/tests/core/__init__.py +++ b/tests/core/__init__.py @@ -16,6 +16,7 @@ "tests.core.test_benchmarks_metrics", "tests.core.test_braille", "tests.core.test_cli", + "tests.core.test_cli_benchmark", "tests.core.test_branches_offline", "tests.core.test_corpus", "tests.core.test_corpus_core_internals", @@ -32,6 +33,7 @@ "tests.core.test_soundex", "tests.core.test_soundex_engines", "tests.core.test_spell", + "tests.core.test_summarize_offline", "tests.core.test_tag", "tests.core.test_tokenize", "tests.core.test_tokenize_core", diff --git a/tests/core/test_branches_offline.py b/tests/core/test_branches_offline.py index 3a9b96542..8d6d82654 100644 --- a/tests/core/test_branches_offline.py +++ b/tests/core/test_branches_offline.py @@ -3,8 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 """Offline tests for branches in spelling, profanity, and POS tagging. -These cover code that is otherwise tested only with a downloaded corpus -or model. ``transformers`` and the profanity corpus are replaced with fakes. +``transformers`` and the profanity corpus are replaced with fakes. """ import sys @@ -18,7 +17,6 @@ from pythainlp.util import contains_profanity from pythainlp.util.pronounce import spelling -# (word, expected spelling): short vowel mark, tone marks, no change _SPELLING = [ ("กา", ["กอ", "อา", "กา"]), ("เด็ก", ["ดอ", "เอะ", "กอ", "เด็ก"]), @@ -27,91 +25,71 @@ ] -class SpellingBranchesTestCase(unittest.TestCase): +class BranchesOfflineTestCase(unittest.TestCase): def test_spelling(self) -> None: for word, expected in _SPELLING: with self.subTest(word=word): self.assertEqual(spelling(word), expected) - -class ContainsProfanityTestCase(unittest.TestCase): - def check(self, tokens: list[str], expected: bool, **kwargs: Any) -> None: + def test_contains_profanity(self) -> None: + cases: list[tuple[list[str], dict[str, Any], bool]] = [ + (["สวัสดี", "คำหยาบ"], {}, True), + (["สวัสดี"], {}, False), + (["คำใหม่"], {"custom_words": {"คำใหม่"}}, True), + ] patches = { "thai_profanity_words": frozenset({"คำหยาบ"}), "thai_words": frozenset({"สวัสดี"}), - "word_tokenize": tokens, } - with ExitStack() as stack: - for name, value in patches.items(): - stack.enter_context( - mock.patch( - f"pythainlp.util.profanity.{name}", return_value=value + for tokens, kwargs, expected in cases: + with self.subTest(tokens=tokens), ExitStack() as stack: + patches["word_tokenize"] = tokens # type: ignore[assignment] + for name, value in patches.items(): + stack.enter_context( + mock.patch( + f"pythainlp.util.profanity.{name}", + return_value=value, + ) ) - ) - self.assertIs(contains_profanity("x", **kwargs), expected) - - def test_found(self) -> None: - self.check(["สวัสดี", "คำหยาบ"], True) - - def test_not_found(self) -> None: - self.check(["สวัสดี"], False) - - def test_custom_words(self) -> None: - self.check(["คำใหม่"], True, custom_words={"คำใหม่"}) - - def test_empty_text(self) -> None: + self.assertIs(contains_profanity("x", **kwargs), expected) self.assertIs(contains_profanity(""), False) - -def _fake_transformers() -> tuple[types.ModuleType, mock.Mock]: - """Return a fake ``transformers`` module and its model loader.""" - module = types.ModuleType("transformers") - model_loader = mock.Mock() - auto_model = mock.Mock() - auto_model.from_pretrained = model_loader - auto_tokenizer = mock.Mock() - pipeline = mock.Mock( - return_value=mock.Mock( - return_value=[{"word": "แมว", "entity_group": "NOUN"}] - ) - ) - module.AutoModelForTokenClassification = auto_model # type: ignore[attr-defined] - module.AutoTokenizer = auto_tokenizer # type: ignore[attr-defined] - module.TokenClassificationPipeline = pipeline # type: ignore[attr-defined] - return module, model_loader - - -class PosTagTransformersTestCase(unittest.TestCase): - def run_tag(self, **kwargs: Any) -> tuple[Any, mock.Mock]: - module, model_loader = _fake_transformers() - with mock.patch.dict(sys.modules, {"transformers": module}): - result = pos_tag_transformers("แมว", **kwargs) - return result, model_loader - - def test_blackboard_corpus(self) -> None: - result, loader = self.run_tag(engine="bert", corpus="blackboard") - self.assertEqual(result, [[("แมว", "NOUN")]]) - loader.assert_called_once_with("lunarlist/pos_thai", revision=None) - - def test_pud_corpus(self) -> None: - result, loader = self.run_tag(engine="mdeberta", corpus="pud") - self.assertEqual(result, [[("แมว", "NOUN")]]) - loader.assert_called_once_with( - "Pavarissy/mdeberta-v3-ud-thai-pud-upos", revision=None + def test_pos_tag_transformers(self) -> None: + loader = mock.Mock() + fake = types.ModuleType("transformers") + fake.__dict__.update( + AutoModelForTokenClassification=mock.Mock(from_pretrained=loader), + AutoTokenizer=mock.Mock(), + TokenClassificationPipeline=mock.Mock( + return_value=lambda _: [ + {"word": "แมว", "entity_group": "NOUN"} + ] + ), ) - - def test_unsupported_engine_or_corpus(self) -> None: - for kwargs in ( + ok = [ + ({"engine": "bert", "corpus": "blackboard"}, "lunarlist/pos_thai"), + ( + {"engine": "mdeberta", "corpus": "pud"}, + "Pavarissy/mdeberta-v3-ud-thai-pud-upos", + ), + ] + bad = [ {"engine": "mdeberta", "corpus": "blackboard"}, {"engine": "bert", "corpus": "pud"}, {"engine": "bert", "corpus": "other"}, - ): - with self.subTest(**kwargs), self.assertRaises(ValueError): - self.run_tag(**kwargs) - - def test_empty_sentence(self) -> None: - module, _ = _fake_transformers() - with mock.patch.dict(sys.modules, {"transformers": module}): + ] + with mock.patch.dict(sys.modules, {"transformers": fake}): + for kwargs, model in ok: + with self.subTest(**kwargs): + loader.reset_mock() + self.assertEqual( + pos_tag_transformers("แมว", **kwargs), + [[("แมว", "NOUN")]], + ) + loader.assert_called_once_with(model, revision=None) + for kwargs in bad: + with self.subTest(**kwargs), self.assertRaises(ValueError): + pos_tag_transformers("แมว", **kwargs) self.assertEqual(pos_tag_transformers(""), []) diff --git a/tests/core/test_cli_benchmark.py b/tests/core/test_cli_benchmark.py new file mode 100644 index 000000000..b2b6591a2 --- /dev/null +++ b/tests/core/test_cli_benchmark.py @@ -0,0 +1,168 @@ +# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project +# SPDX-FileType: SOURCE +# SPDX-License-Identifier: Apache-2.0 +"""Offline tests for pythainlp.cli.benchmark. + +``yaml`` and the benchmark function are replaced with fakes, so the tests +need neither pandas nor PyYAML. +""" + +import io +import json +import sys +import tempfile +import types +import unittest +from argparse import ArgumentError +from contextlib import ExitStack, redirect_stderr, redirect_stdout +from pathlib import Path +from typing import Any +from unittest import mock + +from pythainlp.benchmarks import word_tokenization +from pythainlp.cli import benchmark +from pythainlp.cli.benchmark import App, WordTokenizationBenchmark, _read_file + +_RECORD: dict[str, Any] = { + "char_level:tp": 8, + "char_level:fp": 2, + "char_level:tn": 4, + "char_level:fn": 2, + "word_level:correctly_tokenized_words": 3, + "word_level:total_words_in_sample": 4, + "word_level:total_words_in_ref_sample": 6, + "expected": "ก|ข", + "actual": "ก|ข", +} + + +class _FakeFrame: + """The part of pandas.DataFrame that the command uses.""" + + def __init__(self, records: list[dict[str, Any]]) -> None: + self.records = records + + def __getitem__(self, column: str) -> Any: + return mock.Mock(sum=lambda: sum(r[column] for r in self.records)) + + def to_dict(self, orient: str) -> list[dict[str, Any]]: + return [dict(r) for r in self.records] + + +class CliBenchmarkTestCase(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def write(self, name: str, text: str) -> str: + (self.root / name).write_text(text, encoding="utf-8") + return str(self.root / name) + + def command(self, actual: str, expected: str, *extra: str) -> None: + WordTokenizationBenchmark( + "word-tokenization", + [ + "--input-file", + self.write("sub.txt", actual), + "--test-file", + self.write("ref.txt", expected), + *extra, + ], + ) + + def test_read_file(self) -> None: + # Regression: a lazy generator read the file after it was closed. + path = self.write("a.txt", " ก|ข \nค\n\n \n") + self.assertEqual(_read_file(path), ["ก|ข", "ค", "", ""]) + with self.assertRaises(FileNotFoundError): + _read_file(str(self.root / "missing.txt")) + + def test_app(self) -> None: + cases = [ + ( + ["Word-Tokenization", "--x", "1"], + ("word-tokenization", ["--x", "1"]), + ), + (["unknown"], None), + ] + for argv, call in cases: + with self.subTest(argv=argv): + with mock.patch.object( + benchmark, "WordTokenizationBenchmark" + ) as command: + App(["thainlp", "benchmark", *argv]) + if call is None: + command.assert_not_called() + else: + command.assert_called_once_with(*call) + + def test_app_without_task(self) -> None: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + for argv in ( + ["thainlp", "benchmark", ""], + ["thainlp", "benchmark"], + ): + with self.subTest(argv=argv): + with self.assertRaises((ArgumentError, SystemExit)): + App(argv) + + def test_run(self) -> None: + fake_yaml = types.ModuleType("yaml") + fake_yaml.dump = lambda data, f, **kw: f.write(json.dumps(data)) # type: ignore[attr-defined] + frame = _FakeFrame([dict(_RECORD), dict(_RECORD)]) + out = io.StringIO() + with ExitStack() as stack: + stack.enter_context( + mock.patch.dict(sys.modules, {"yaml": fake_yaml}) + ) + bench = stack.enter_context( + mock.patch.object( + word_tokenization, "benchmark", return_value=frame + ) + ) + stack.enter_context(redirect_stdout(out)) + self.command("ก|ข\nค\n", "ก|ข\nค\n") + self.assertEqual( + sorted(p.name for p in self.root.iterdir()), + ["ref.txt", "sub.txt"], + ) + self.command("ก|ข\nค\n", "ก|ข\nค\n", "--save-details") + bench.assert_called_with(["ก|ข", "ค"], ["ก|ข", "ค"]) + output = out.getvalue() + # tp=16 fp=4 fn=4: char precision = recall = 0.8; words 6/8 and 6/12 + for text in ( + "with 2 samples in total", + "char_level:precision 0.8000", + "char_level:recall 0.8000", + "word_level:precision 0.7500", + "word_level:recall 0.5000", + "eval-sub.yml", + "eval-details-sub.json", + ): + self.assertIn(text, output) + details = json.loads( + (self.root / "eval-details-sub.json").read_text(encoding="utf-8") + ) + self.assertEqual([s["id"] for s in details["samples"]], [0, 1]) + self.assertEqual(details["samples"][0]["expected"], "ก|ข") + self.assertNotIn("expected", details["samples"][0]["metrics"]) + self.assertEqual(details["metrics"]["char_level:tp"], 16.0) + self.assertTrue((self.root / "eval-sub.yml").exists()) + + def test_errors(self) -> None: + with redirect_stdout(io.StringIO()): + with self.assertRaisesRegex(ValueError, "same number of samples"): + self.command("ก\n", "ก\nข\n") + # None in sys.modules makes "import yaml" raise ImportError + with mock.patch.dict(sys.modules, {"yaml": None}): + with self.assertRaisesRegex( + ImportError, r"pythainlp\[benchmarks\]" + ): + self.command("ก\n", "ก\n") + with self.assertRaises(TypeError): # no file arguments + WordTokenizationBenchmark("word-tokenization", []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_summarize_offline.py b/tests/core/test_summarize_offline.py new file mode 100644 index 000000000..643ad4e12 --- /dev/null +++ b/tests/core/test_summarize_offline.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project +# SPDX-FileType: SOURCE +# SPDX-License-Identifier: Apache-2.0 +"""Offline tests for pythainlp.summarize and the benchmark text helpers. + +They use only the standard library and the bundled corpora. The mT5 and +KeyBERT engines are replaced with fakes. +""" + +import sys +import types +import unittest +from typing import Any, Union +from unittest import mock + +from pythainlp.benchmarks import word_tokenization as wt +from pythainlp.summarize import extract_keywords, summarize +from pythainlp.summarize.freq import FrequencySummarizer + +_TEXT = "แมวกินปลาแมว\nแมวนอนหลับ\nสุนัขเห่า" # "แมว" is the top word +_WORDS = "แมวกินปลา แมวนอนหลับ แมวกินปลา ปลาว่ายน้ำ" + + +def _fake(name: str, **attrs: Any) -> dict[str, types.ModuleType]: + """Return a ``sys.modules`` patch with a fake module.""" + module = types.ModuleType(name) + module.__dict__.update(attrs) + return {name: module} + + +class SummarizeOfflineTestCase(unittest.TestCase): + def test_frequency_summarizer(self) -> None: + wide = FrequencySummarizer(min_cut=0.0, max_cut=1.1) + top2 = wide.summarize(_TEXT, 2) + self.assertEqual(wide.summarize(_TEXT, 1), ["แมวกินปลาแมว"]) + self.assertEqual((len(top2), top2[0]), (2, "แมวกินปลาแมว")) + self.assertEqual(len(wide.summarize(_TEXT, 10)), 3) + self.assertEqual(FrequencySummarizer().summarize("", 3), []) + self.assertEqual(FrequencySummarizer().summarize("! ? ,", 1), ["!"]) + # One-word sentences with frequencies a=1.0, b=0.5, c=0.25. + # With max_cut=0.6, "a" is dropped and "b" ranks first. + text = "a a a a b b c" + self.assertEqual(wide.summarize(text, 1), ["a"]) + self.assertEqual( + FrequencySummarizer(0.0, 0.6).summarize(text, 1), ["b"] + ) + + def test_summarize(self) -> None: + for text in ("", None, 123): + with self.subTest(text=text): + self.assertEqual(summarize(text), []) # type: ignore[arg-type] + self.assertEqual(summarize(_TEXT, n=1)[0], "แมวกินปลาแมว") + # An unknown engine returns the first n sentences + self.assertEqual( + summarize(_TEXT, n=2, engine="unknown"), + ["แมวกินปลาแมว", "แมวนอนหลับ"], + ) + + def test_summarize_mt5(self) -> None: + mt5 = mock.Mock() + mt5.return_value.summarize.return_value = ["สรุป"] + cases: list[tuple[str, dict[str, Any]]] = [ + ( + "mt5-cpe-kmutt-thai-sentence-sum", + { + "pretrained_mt5_model_name": "mt5-cpe-kmutt-thai-sentence-sum", + "min_length": 5, + }, + ), + ("mt5-small", {"model_size": "small"}), + ("mt5", {"model_size": "mt5"}), + ] + with mock.patch.dict( + sys.modules, _fake("pythainlp.summarize.mt5", mT5Summarizer=mt5) + ): + for engine, kwargs in cases: + with self.subTest(engine=engine): + mt5.reset_mock() + self.assertEqual(summarize(_TEXT, engine=engine), ["สรุป"]) + mt5.assert_called_once_with(**kwargs) + + def test_extract_keywords(self) -> None: + kw = "frequency" + self.assertEqual( + extract_keywords(_WORDS, max_keywords=3, engine=kw), + ["แมว", "ปลา", "กิน"], + ) + self.assertEqual(extract_keywords("แมวกินปลา", min_df=5, engine=kw), []) + self.assertNotIn( + "แมว", extract_keywords(_WORDS, stop_words=["แมว"], engine=kw) + ) + for text in ("", " "): + self.assertEqual(extract_keywords(text, engine=kw), []) + with self.assertRaisesRegex(ValueError, "'unknown'"): + extract_keywords("แมว", engine="unknown") + + def test_extract_keywords_keybert(self) -> None: + extractor = mock.Mock() + extractor.extract_keywords.return_value = ["คำ"] + patch = _fake("pythainlp.summarize.keybert", KeyBERT=lambda: extractor) + with mock.patch.dict(sys.modules, patch): + self.assertEqual( + extract_keywords("แมว", max_keywords=2, min_df=3), ["คำ"] + ) + kwargs = extractor.extract_keywords.call_args.kwargs + self.assertEqual( + ( + kwargs["max_keywords"], + kwargs["min_df"], + kwargs["return_similarity"], + ), + (2, 3, False), + ) + + def test_benchmark_text_helpers(self) -> None: + for text, expected in ( + ("ก|ข | |ค||ง|", "ก|ข|ค|ง"), + ("ก ข|ค", "กข|ค"), + ("", ""), + ("||", ""), + ): + with self.subTest(text=text): + self.assertEqual(wt.preprocessing(text), expected) + self.assertEqual(wt.preprocessing("ก ข", remove_space=False), "ก ข") + self.assertEqual((wt._f1(0, 0), wt._f1(0.5, 0.5)), (0, 0.5)) + self.assertAlmostEqual(wt._f1(1.0, 0.5), 2 / 3) + nested: dict[str, dict[str, Union[int, str]]] = { + "a": {"b": 1, "c": "x"}, + "d": {"e": 2}, + } + self.assertEqual( + wt._flatten_result(nested), {"a:b": 1, "a:c": "x", "d:e": 2} + ) + self.assertEqual( + wt._flatten_result({"a": {"b": 1}}, sep="."), {"a.b": 1} + ) + self.assertEqual(wt._flatten_result({}), {}) + + +if __name__ == "__main__": + unittest.main() From c2088f7f6ee5fe322f7a8752f0c74ae32e52f03f Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 21:58:08 +0100 Subject: [PATCH 7/8] Use nested with in tests for Python 3.9; simplify a condition Signed-off-by: Arthit Suriyawongkul --- pythainlp/util/wordtonum.py | 2 +- tests/core/test_corpus.py | 8 +- tests/core/test_corpus_core_internals.py | 123 +++++++++++------------ 3 files changed, 61 insertions(+), 72 deletions(-) diff --git a/pythainlp/util/wordtonum.py b/pythainlp/util/wordtonum.py index 18e70f122..3af4315a4 100644 --- a/pythainlp/util/wordtonum.py +++ b/pythainlp/util/wordtonum.py @@ -211,7 +211,7 @@ def text_to_num(text: str) -> list[str]: if isthainum and last_index + 1 == i and i + 1 == len(_temp): thainum.append(word) _flush(thainum, list_word_new) - elif isthainum and last_index + 1 == i or isthainum: + elif isthainum: thainum.append(word) last_index = i elif not isthainum and last_index + 1 == i and last_index != -1: diff --git a/tests/core/test_corpus.py b/tests/core/test_corpus.py index c21b899cf..41195f6b7 100644 --- a/tests/core/test_corpus.py +++ b/tests/core/test_corpus.py @@ -39,11 +39,9 @@ class CorpusTestCase(unittest.TestCase): def test_get_corpus_db_errors(self): # Network errors are reported and return None for error in (TimeoutError("timed out"), OSError("unreachable")): - with ( - patch("urllib.request.urlopen", side_effect=error), - patch("builtins.print"), - ): - self.assertIsNone(get_corpus_db("https://example.com/db")) + with patch("urllib.request.urlopen", side_effect=error): + with patch("builtins.print"): + self.assertIsNone(get_corpus_db("https://example.com/db")) # Unexpected errors are not swallowed with patch("urllib.request.urlopen", side_effect=RuntimeError("bug")): with self.assertRaises(RuntimeError): diff --git a/tests/core/test_corpus_core_internals.py b/tests/core/test_corpus_core_internals.py index 71b0bb316..21575e27d 100644 --- a/tests/core/test_corpus_core_internals.py +++ b/tests/core/test_corpus_core_internals.py @@ -697,18 +697,15 @@ def legacy_extractall( ) -> None: original(path=path, members=members, **kwargs) - with ( - patch.object( - tar, "extractall", side_effect=legacy_extractall - ) as extractall, - warnings.catch_warnings(), - ): - # Python 3.12 to 3.14 warn about no filter - warnings.simplefilter("ignore", DeprecationWarning) - try: - core._safe_extract_tar(tar, str(self.dest)) - finally: - self.extractall_calls = extractall.call_args_list + with patch.object( + tar, "extractall", side_effect=legacy_extractall + ) as extractall: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + try: + core._safe_extract_tar(tar, str(self.dest)) + finally: + self.extractall_calls = extractall.call_args_list def check_error( self, error: ValueError, message: str, error_type: str @@ -812,26 +809,24 @@ def test_owner_is_not_restored_as_root(self) -> None: tar.addfile(info, io.BytesIO(b"")) tar.addfile(_dir_info("d", 4321)) members = [("a.txt",), ("d",)] - with ( - patch("os.geteuid", return_value=0, create=True), - patch("os.chown") as chown, - ): - buf.seek(0) - with tarfile.open(fileobj=buf) as tar: - original = tar.extractall - kwargs: dict[str, Any] = ( - {"filter": "fully_trusted"} - if hasattr(tarfile, "fully_trusted_filter") - else {} - ) - with patch.object( - tar, - "extractall", - side_effect=lambda path, members=None: original( - path=path, members=members, **kwargs - ), - ): - core._safe_extract_tar(tar, str(self.dest)) + with patch("os.geteuid", return_value=0, create=True): + with patch("os.chown") as chown: + buf.seek(0) + with tarfile.open(fileobj=buf) as tar: + original = tar.extractall + kwargs: dict[str, Any] = ( + {"filter": "fully_trusted"} + if hasattr(tarfile, "fully_trusted_filter") + else {} + ) + with patch.object( + tar, + "extractall", + side_effect=lambda path, members=None: original( + path=path, members=members, **kwargs + ), + ): + core._safe_extract_tar(tar, str(self.dest)) self.assertEqual(len(chown.call_args_list), len(members)) for call in chown.call_args_list: self.assertEqual(call.args[1:], (-1, -1)) @@ -1648,14 +1643,14 @@ def replace_file(src: str, dst: str) -> None: self.assertEqual(Path(dst).read_bytes(), b"old") real_replace(src, dst) - with ( - patch( - "urllib.request.urlopen", return_value=_FakeResponse(b"new") - ), - patch.object(core, "_replace_file", replace_file), - redirect_stdout(io.StringIO()), + with patch( + "urllib.request.urlopen", return_value=_FakeResponse(b"new") ): - size = core._download(_FILE_URL + "c.txt", "c.txt", _md5(b"new")) + with patch.object(core, "_replace_file", replace_file): + with redirect_stdout(io.StringIO()): + size = core._download( + _FILE_URL + "c.txt", "c.txt", _md5(b"new") + ) self.assertEqual(size, 3) ((src, dst),) = moves self.assertEqual(Path(src).parent.resolve(), self.data_dir.resolve()) @@ -1683,26 +1678,26 @@ def test_failed_download_keeps_existing_file(self) -> None: if error is None else _BrokenResponse(b"x" * 70000, error) ) - with ( - patch("urllib.request.urlopen", return_value=response), - redirect_stdout(io.StringIO()), + with patch( + "urllib.request.urlopen", return_value=response ): - with self.assertRaises( - ValueError if error is None else type(error) - ): - core._download(_FILE_URL + "c.txt", "c.txt", md5) + with redirect_stdout(io.StringIO()): + with self.assertRaises( + ValueError if error is None else type(error) + ): + core._download( + _FILE_URL + "c.txt", "c.txt", md5 + ) self.assertEqual(_snapshot(self.data_dir), existing) self.assertEqual(_tree(self.data_dir), list(existing)) def test_failed_replace_keeps_existing_path(self) -> None: # A directory in the way cannot be replaced; it is not removed (self.data_dir / "c.txt").mkdir() - with ( - patch("urllib.request.urlopen", return_value=_FakeResponse(b"x")), - redirect_stdout(io.StringIO()), - self.assertRaises(OSError), - ): - core._download(_FILE_URL + "c.txt", "c.txt") + with patch("urllib.request.urlopen", return_value=_FakeResponse(b"x")): + with redirect_stdout(io.StringIO()): + with self.assertRaises(OSError): + core._download(_FILE_URL + "c.txt", "c.txt") self.assertEqual(_tree(self.data_dir), ["c.txt"]) def test_empty_key_in_local_db(self) -> None: @@ -1953,12 +1948,10 @@ def replace(src: str, dst: str) -> None: raise errors.pop() real_replace(src, dst) - with ( - patch.object(core, "_REPLACE_RETRIES", 5), - patch("os.replace", side_effect=replace) as replace_mock, - patch("time.sleep") as sleep, - ): - core._write_local_db(new_db) + with patch.object(core, "_REPLACE_RETRIES", 5): + with patch("os.replace", side_effect=replace) as replace_mock: + with patch("time.sleep") as sleep: + core._write_local_db(new_db) self.assertEqual(replace_mock.call_count, 3) self.assertEqual(sleep.call_count, 2) sleep.assert_called_with(0.05) @@ -1968,15 +1961,13 @@ def replace(src: str, dst: str) -> None: def test_replace_gives_up_after_retries(self) -> None: for retries in (0, 5): with self.subTest(retries=retries): - with ( - patch.object(core, "_REPLACE_RETRIES", retries), - patch( + with patch.object(core, "_REPLACE_RETRIES", retries): + with patch( "os.replace", side_effect=PermissionError("in use") - ) as replace_mock, - patch("time.sleep") as sleep, - ): - with self.assertRaises(PermissionError): - core._write_local_db({"_default": {}}) + ) as replace_mock: + with patch("time.sleep") as sleep: + with self.assertRaises(PermissionError): + core._write_local_db({"_default": {}}) self.assertEqual(replace_mock.call_count, retries + 1) self.assertEqual(sleep.call_count, retries) self.assertEqual(self.read_db(), self.old_db) From 863d1a7e1f145488771f2e29f62bba3ee3ad9929 Mon Sep 17 00:00:00 2001 From: Arthit Suriyawongkul Date: Tue, 6 Oct 2026 22:02:34 +0100 Subject: [PATCH 8/8] Fix benchmark CLI output path for relative and Windows paths Signed-off-by: Arthit Suriyawongkul --- CLAUDE.md | 1 + GEMINI.md | 1 + pythainlp/cli/benchmark.py | 10 ++++++---- tests/core/test_cli_benchmark.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 40 insertions(+), 4 deletions(-) create mode 120000 CLAUDE.md create mode 120000 GEMINI.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/GEMINI.md b/GEMINI.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/pythainlp/cli/benchmark.py b/pythainlp/cli/benchmark.py index dc9eaa866..3b7945da6 100644 --- a/pythainlp/cli/benchmark.py +++ b/pythainlp/cli/benchmark.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING from pythainlp import cli -from pythainlp.tools import safe_print +from pythainlp.tools import safe_path_join, safe_print if TYPE_CHECKING: from collections.abc import Sequence @@ -156,15 +156,17 @@ def __init__(self, name: str, argv: Sequence[str]) -> None: if args.save_details: dir_name = os.path.dirname(args.input_file) - file_name = args.input_file.split("/")[-1].split(".")[0] + file_name = os.path.basename(args.input_file).split(".")[0] - res_path = "%s/eval-%s.yml" % (dir_name, file_name) + res_path = safe_path_join(dir_name, f"eval-{file_name}.yml") safe_print("Evaluation result is saved to %s" % res_path) with open(res_path, "w", encoding="utf-8") as outfile: yaml.dump(statistics, outfile, default_flow_style=False) - res_path = "%s/eval-details-%s.json" % (dir_name, file_name) + res_path = safe_path_join( + dir_name, f"eval-details-{file_name}.json" + ) safe_print("Details of comparisons is saved to %s" % res_path) with open(res_path, "w", encoding="utf-8") as f: diff --git a/tests/core/test_cli_benchmark.py b/tests/core/test_cli_benchmark.py index b2b6591a2..dda28a3fa 100644 --- a/tests/core/test_cli_benchmark.py +++ b/tests/core/test_cli_benchmark.py @@ -9,6 +9,7 @@ import io import json +import os import sys import tempfile import types @@ -150,6 +151,37 @@ def test_run(self) -> None: self.assertEqual(details["metrics"]["char_level:tp"], 16.0) self.assertTrue((self.root / "eval-sub.yml").exists()) + def test_save_details_with_relative_path(self) -> None: + # Regression: the output went to "/eval-sub.yml" (the filesystem + # root) when the input file had no directory part. + fake_yaml = types.ModuleType("yaml") + fake_yaml.dump = lambda data, f, **kw: f.write("{}") # type: ignore[attr-defined] + frame = _FakeFrame([dict(_RECORD)]) + old_cwd = os.getcwd() + self.addCleanup(os.chdir, old_cwd) + os.chdir(self.root) + self.write("sub.txt", "ก\n") + self.write("ref.txt", "ก\n") + with mock.patch.dict(sys.modules, {"yaml": fake_yaml}): + with mock.patch.object( + word_tokenization, "benchmark", return_value=frame + ): + with redirect_stdout(io.StringIO()): + WordTokenizationBenchmark( + "word-tokenization", + [ + "--input-file", + "sub.txt", + "--test-file", + "ref.txt", + "--save-details", + ], + ) + self.assertEqual( + sorted(p.name for p in self.root.iterdir()), + ["eval-details-sub.json", "eval-sub.yml", "ref.txt", "sub.txt"], + ) + def test_errors(self) -> None: with redirect_stdout(io.StringIO()): with self.assertRaisesRegex(ValueError, "same number of samples"):