Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .pydocstyle.ini
Original file line number Diff line number Diff line change
@@ -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
12 changes: 10 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,15 +384,23 @@ 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
import. Read comments near imports to get more information.
- [ ] 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.
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
1 change: 1 addition & 0 deletions GEMINI.md
9 changes: 6 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion notebooks/create_words.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
32 changes: 27 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,13 @@ select = [
"W",
"S",
"TC",
"B028",
"B",
"C4",
"FURB",
"ISC",
"PIE",
"RET",
"SIM",
"C901",
"F401",
"F811",
Expand All @@ -443,8 +449,24 @@ 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.
# 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"]
"notebooks/**" = ["S101"]

[tool.tox]
env_list = ["py39", "py310", "py311", "py312", "py313", "py314", "pypy310", "pypy311", "ruff", "flake8", "mypy"]
Expand All @@ -467,13 +489,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]
Expand Down
2 changes: 1 addition & 1 deletion pythainlp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pythainlp/ancient/aksonhan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pythainlp/augment/lm/wangchanberta.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("<s> ", "").replace("</s>", "")
Expand Down
4 changes: 2 additions & 2 deletions pythainlp/augment/wordnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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(
Expand Down
4 changes: 1 addition & 3 deletions pythainlp/benchmarks/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 10 additions & 14 deletions pythainlp/braille/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
Expand Down Expand Up @@ -256,11 +254,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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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]
5 changes: 2 additions & 3 deletions pythainlp/chunk/crfchunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
13 changes: 7 additions & 6 deletions pythainlp/cli/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,15 @@
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


def _read_file(path: str) -> list[str]:
with open(path, encoding="utf-8") as f:
lines = (r.strip() for r in f.readlines())
return list(lines)
return [r.strip() for r in f]


class App:
Expand Down Expand Up @@ -157,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:
Expand Down
18 changes: 9 additions & 9 deletions pythainlp/corpus/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions pythainlp/el/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
Expand Down
Loading
Loading