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
39 changes: 16 additions & 23 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,41 +24,34 @@ and this project adheres to
- `pythainlp.tokenize.deepcut`: built-in ONNX engine replaces the
TensorFlow-based `deepcut`; `custom_dict` is no longer applied ([#1372])
- Improve guardrails in `check_sara()` and `nighit()` ([#1453])
- `bleu_score()` raises `ValueError` on unequal reference and hypothesis
counts; `nighit()` requires `w1` to end with "ํ" ([#1548])

### Fixed

- `pythainlp.corpus.wordnet`: Thai WordNet with NLTK 3.10+; `all_synsets()`
`NameError`; `langs()` missing `tha` ([#1541])
- `check_klon()` and `get_corpus_db()` no longer swallow unexpected
exceptions ([#1542])
- `download()`: download and extract via temporary paths, so a failed
download keeps the installed corpus; handle empty `db.json` keys ([#1546])
- `db.json` is written atomically and keeps its mode and symlink ([#1546])
- `remove()` no longer downloads a missing corpus before deleting it ([#1546])
- `download()` uses temporary paths, so a failed download keeps the installed
corpus; `remove()` no longer downloads a missing corpus ([#1546])
- `db.json` is written atomically and keeps its mode and symlink; handle
empty keys ([#1546])
- `ThaiTextProcessor.preprocess()` no longer raises `TypeError` when
`pre_rules` is not given ([#1547])
- `sound_syllable()` and `tone_detector()` no longer raise `IndexError` for a
syllable without a consonant, such as "ฤๅ" ([#1548])
- `thaiword_to_time()`: accept "ตีหก"; unknown hour words raise `ValueError`,
not `KeyError` ([#1548])
- `convert_years()` accepts the same source and target era ([#1548])
- `bleu_score()`: empty hypotheses give 0.0; unequal numbers of references
and hypotheses raise `ValueError` ([#1548])
- `puan()` keeps syllables that have no initial consonant, and no longer
raises `IndexError` ([#1548])
- `WunsenTransliterate.transliterate()` raises `NotImplementedError` for
`lang=None` ([#1548])
- `check_klon()` no longer raises `IndexError` after a stanza with an empty
Wak 4 ([#1548])
- `nighit()`: map ช to ญ; add ฆ, ญ, ฏ, ฒ, ต, ม; `w1` must
end with "ํ" ([#1548])
- `sound_syllable()`, `tone_detector()`, `puan()`, `check_klon()`,
`thaiword_to_time()`: no `IndexError` or `KeyError` on valid input ([#1548])
- `thaiword_to_time()` accepts "ตีหก"; `convert_years()` accepts the same
source and target era ([#1548])
- `bleu_score()` gives 0.0 for an empty hypothesis; `WunsenTransliterate`
raises `NotImplementedError` for `lang=None` ([#1548])
- `nighit()`: map ช to ญ; add ฆ, ญ, ฏ, ฒ, ต, ม ([#1548])

### Security

- Tar and zip extraction rejects absolute and escaping links; unsafe tar
members raise `ValueError` ([#1546])
- Without `tarfile.data_filter`, tar extraction rejects all links and special
files and drops owners ([#1546])
- Tar and zip extraction rejects absolute and escaping links; without
`tarfile.data_filter`, tar extraction also rejects special files and drops
owners ([#1546])

[#1372]: https://github.com/PyThaiNLP/pythainlp/pull/1372
[#1453]: https://github.com/PyThaiNLP/pythainlp/pull/1453
Expand Down
9 changes: 7 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ skip-magic-trailing-comma = false
# `# phase2-todo`.
mccabe.max-complexity = 10
select = [
"D1",
"E",
"F",
"I",
Expand Down Expand Up @@ -471,8 +472,12 @@ extend-ignore = ["B905", "E501", "RET504", "SIM108", "SIM117"]
"pythainlp/tokenize/__init__.py" = ["E402"]
# S101 (assert) is not allowed in production code. Tests and notebooks may use it.
# B010 (setattr) is for attributes that tests set on purpose.
"tests/**" = ["B010", "S101"]
"notebooks/**" = ["S101"]
# D1 (missing docstring) applies to the pythainlp package only.
"tests/**" = ["B010", "D1", "S101"]
"notebooks/**" = ["D1", "S101"]
"examples/**" = ["D1"]
"build_tools/**" = ["D1"]
"docs/**" = ["D1"]

[tool.tox]
env_list = ["py39", "py310", "py311", "py312", "py313", "py314", "pypy310", "pypy311", "ruff", "flake8", "mypy"]
Expand Down
3 changes: 3 additions & 0 deletions pythainlp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0

"""PyThaiNLP, a Thai natural language processing library."""

__version__ = "5.3.8"

thai_consonants: str = (
Expand Down
3 changes: 3 additions & 0 deletions pythainlp/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0

"""Run the PyThaiNLP command line with ``python -m pythainlp``."""

from __future__ import annotations

import argparse
Expand Down
2 changes: 2 additions & 0 deletions pythainlp/ancient/aksonhan.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Convert AksonHan (อักษรหัน) words to current Thai spelling."""

from __future__ import annotations

from itertools import chain
Expand Down
2 changes: 2 additions & 0 deletions pythainlp/ancient/currency.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Convert values between ancient Thai currency units."""

from __future__ import annotations


Expand Down
2 changes: 2 additions & 0 deletions pythainlp/augment/lm/fasttext.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using fastText."""

from __future__ import annotations

import itertools
Expand Down
16 changes: 16 additions & 0 deletions pythainlp/augment/lm/phayathaibert.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using PhayaThaiBERT."""

from __future__ import annotations

import random
Expand All @@ -16,12 +18,15 @@


class ThaiTextAugmenter:
"""Augment Thai text using PhayaThaiBERT."""

tokenizer: "AutoTokenizer"
model_for_masked_lm: "AutoModelForMaskedLM"
model: "Pipeline"
processor: "ThaiTextProcessor"

def __init__(self) -> None:
"""Initialize the PhayaThaiBERT fill-mask pipeline."""
from transformers import (
AutoModelForMaskedLM,
AutoTokenizer,
Expand All @@ -48,6 +53,17 @@ def generate(
max_length: int = 3,
sample: bool = False,
) -> str:
"""
Generate text by repeatedly filling a mask token.

:param str sample_text: text to start from
:param int word_rank: rank of the predicted word to use in each step
:param int max_length: number of mask-filling steps
:param bool sample: pick a random one of the top five predictions
instead of the one at ``word_rank``
:return: generated text
:rtype: str
"""
sample_txt = sample_text
final_text = ""

Expand Down
13 changes: 13 additions & 0 deletions pythainlp/augment/lm/wangchanberta.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using WangchanBERTa."""

from __future__ import annotations

from typing import TYPE_CHECKING
Expand All @@ -12,6 +14,8 @@


class Thai2transformersAug:
"""Augment Thai text using WangchanBERTa."""

model_name: str
target_tokenizer: type["CamembertTokenizer"]
tokenizer: "CamembertTokenizer"
Expand All @@ -20,6 +24,7 @@ class Thai2transformersAug:
input_text: str

def __init__(self) -> None:
"""Initialize the WangchanBERTa tokenizer and fill-mask pipeline."""
from transformers import (
CamembertTokenizer,
pipeline,
Expand Down Expand Up @@ -49,6 +54,14 @@ def __init__(self) -> None:
def generate(
self, sentence: str, num_replace_tokens: int = 3
) -> list[str]:
"""
Generate sentences by filling masked tokens.

:param str sentence: Thai text to augment
:param int num_replace_tokens: number of tokens to replace
:return: list of generated sentences
:rtype: list[str]
"""
sent2: list[str] = []
self.input_text: str = sentence
sent = [
Expand Down
9 changes: 9 additions & 0 deletions pythainlp/augment/word2vec/bpemb_wv.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using word2vec from BPEmb."""

from __future__ import annotations

from typing import TYPE_CHECKING, cast
Expand Down Expand Up @@ -31,6 +33,13 @@ class BPEmbAug:
def __init__(
self, lang: str = "th", vs: int = 100000, dim: int = 300
) -> None:
"""
Initialize the BPEmb word2vec augmenter.

:param str lang: language code
:param int vs: vocabulary size
:param int dim: embedding dimension
"""
from bpemb import BPEmb

self.bpemb_temp: BPEmb = BPEmb(lang=lang, dim=dim, vs=vs)
Expand Down
4 changes: 4 additions & 0 deletions pythainlp/augment/word2vec/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment text using word2vec word vectors."""

from __future__ import annotations

import itertools
Expand All @@ -19,6 +21,8 @@ def filter(self, record: logging.LogRecord) -> bool:


class Word2VecAug:
"""Augment text using word2vec word vectors."""

tokenizer: Callable[[str], list[str]]
model: "KeyedVectors"
dict_wv: list[str]
Expand Down
3 changes: 3 additions & 0 deletions pythainlp/augment/word2vec/ltw2v.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using word2vec from LTW2V."""

from __future__ import annotations

from typing import Optional
Expand All @@ -23,6 +25,7 @@ class LTW2VAug:
aug: Word2VecAug

def __init__(self) -> None:
"""Initialize the LTW2V word2vec augmenter."""
self.ltw2v_wv: Optional[str] = get_corpus_path("ltw2v")
self.load_w2v()

Expand Down
3 changes: 3 additions & 0 deletions pythainlp/augment/word2vec/thai2fit.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Augment Thai text using word2vec from Thai2Fit."""

from __future__ import annotations

from typing import Optional
Expand All @@ -22,6 +24,7 @@ class Thai2fitAug:
aug: Word2VecAug

def __init__(self) -> None:
"""Initialize the Thai2Fit word2vec augmenter."""
self.thai2fit_wv: Optional[str] = get_corpus_path("thai2fit_wv")
self.load_w2v()

Expand Down
2 changes: 1 addition & 1 deletion pythainlp/augment/wordnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ class WordNetAug:
temp: list[str]

def __init__(self) -> None:
pass
"""Initialize the WordNet augmenter."""

def find_synonyms(
self,
Expand Down
3 changes: 3 additions & 0 deletions pythainlp/benchmarks/word_tokenization.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0

"""Benchmark metrics for word tokenization."""

from __future__ import annotations

import re
Expand Down
4 changes: 4 additions & 0 deletions pythainlp/chat/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""Chatbot using the WangChanGLM model."""

from __future__ import annotations

from typing import TYPE_CHECKING, Optional
Expand All @@ -14,6 +16,8 @@


class ChatBotModel:
"""Chat with the WangChanGLM model."""

history: list[tuple[str, str]]
model: "WangChanGLM"

Expand Down
5 changes: 5 additions & 0 deletions pythainlp/chunk/crfchunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ class CRFChunkParser:
xseq: list[dict[str, Union[str, bool]]]

def __init__(self, corpus: str = "orchidpp") -> None:
"""
Initialize the chunker.

:param str corpus: corpus for the CRF model
"""
self.corpus = corpus
self._model_file_ctx = None
self.load_model(self.corpus)
Expand Down
16 changes: 16 additions & 0 deletions pythainlp/classify/param_free.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0

"""Parameter-free text classification."""

from __future__ import annotations

import gzip
Expand Down Expand Up @@ -33,6 +36,13 @@ def __init__(
training_data: Optional[list[tuple[str, str]]] = None,
model_path: str = "",
) -> None:
"""
Initialize the model.

:param Optional[list[tuple[str, str]]] training_data: list of
(text, label) tuples
:param str model_path: path to load a saved model from
"""
import numpy as np

if model_path:
Expand All @@ -42,6 +52,12 @@ def __init__(
self.cx2_list = self.train()

def train(self) -> list[int]:
"""
Compute the compressed length of each training text.

:return: compressed length of each training text
:rtype: list[int]
"""
temp_list = []
for i in range(len(self.training_data)):
temp_list.append(
Expand Down
7 changes: 7 additions & 0 deletions pythainlp/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@


def make_usage(command: str) -> dict[str, str]:
"""
Build the usage arguments of a command.

:param str command: command name
:return: ``prog`` and ``usage`` strings for argparse
:rtype: dict[str, str]
"""
prog = f"{CLI_NAME} {command}"

return {"prog": prog, "usage": f"{prog} [options]"}
Expand Down
Loading
Loading