Skip to content

Commit eef69e9

Browse files
Copilotbact
andcommitted
Add type hints to spell and tag modules for noauto test suite
Co-authored-by: bact <128572+bact@users.noreply.github.com>
1 parent 348e0e3 commit eef69e9

4 files changed

Lines changed: 42 additions & 27 deletions

File tree

pythainlp/spell/wanchanberta_thai_grammarly.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
from __future__ import annotations
1414

15+
from typing import Any, Optional
16+
1517
import torch
1618
from transformers import (
1719
AutoModelForMaskedLM,
@@ -27,13 +29,18 @@
2729

2830

2931
class BertModel(torch.nn.Module):
30-
def __init__(self):
32+
def __init__(self) -> None:
3133
super().__init__()
3234
self.bert = BertForTokenClassification.from_pretrained(
3335
"bookpanda/wangchanberta-base-att-spm-uncased-tagging"
3436
)
3537

36-
def forward(self, input_id, mask, label):
38+
def forward(
39+
self,
40+
input_id: torch.Tensor,
41+
mask: torch.Tensor,
42+
label: Optional[torch.Tensor],
43+
) -> Any:
3744
output = self.bert(
3845
input_ids=input_id,
3946
attention_mask=mask,
@@ -67,7 +74,7 @@ def align_word_ids(texts: str) -> list[int]:
6774
return label_ids
6875

6976

70-
def evaluate_one_text(model, sentence):
77+
def evaluate_one_text(model: BertModel, sentence: str) -> list[str]:
7178
text = tokenizer(
7279
sentence,
7380
padding="max_length",

pythainlp/spell/words_spelling_correction.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from __future__ import annotations
55

66
import os
7-
from typing import Union
7+
from typing import Any, Union
88

99
from pythainlp.corpus import get_hf_hub
1010

@@ -19,14 +19,14 @@ class FastTextEncoder:
1919

2020
def __init__(
2121
self,
22-
model_dir,
23-
nn_model_path,
24-
words_list,
25-
bucket=2000000,
26-
nb_words=2000000,
27-
minn=5,
28-
maxn=5,
29-
):
22+
model_dir: str,
23+
nn_model_path: str,
24+
words_list: list[str],
25+
bucket: int = 2000000,
26+
nb_words: int = 2000000,
27+
minn: int = 5,
28+
maxn: int = 5,
29+
) -> None:
3030
"""Initializes the FastTextEncoder, loading embeddings, vocabulary,
3131
nearest neighbor model, and suggestion words list.
3232
@@ -63,7 +63,7 @@ def __init__(
6363
self.nn_session = self._load_onnx_session(nn_model_path)
6464
self.embedding_dim = self.embeddings.shape[1]
6565

66-
def _load_embeddings(self):
66+
def _load_embeddings(self) -> tuple[list[str], Any]:
6767
"""Loads embeddings matrix and vocabulary list."""
6868
input_matrix = self.np.load(
6969
os.path.join(self.model_dir, "embeddings.npy")
@@ -75,12 +75,12 @@ def _load_embeddings(self):
7575
words.append(line.rstrip())
7676
return words, input_matrix
7777

78-
def _load_suggestion_words(self, words_list):
78+
def _load_suggestion_words(self, words_list: list[str]) -> Any:
7979
"""Loads the list of words used for suggestions."""
8080
words = self.np.array(words_list)
8181
return words
8282

83-
def _load_onnx_session(self, onnx_path):
83+
def _load_onnx_session(self, onnx_path: str) -> Any:
8484
"""Loads the ONNX inference session."""
8585
# Note: Using providers=["CPUExecutionProvider"] for platform independence
8686
import onnxruntime as rt
@@ -92,7 +92,7 @@ def _load_onnx_session(self, onnx_path):
9292

9393
# --- Helper Methods for Encoding ---
9494

95-
def _get_hash(self, subword):
95+
def _get_hash(self, subword: str) -> int:
9696
"""Computes the FastText-like hash for a subword."""
9797
h = 2166136261 # FNV-1a basis
9898
for c in subword:
@@ -101,7 +101,7 @@ def _get_hash(self, subword):
101101
h = (h * 16777619) % 2**32 # FNV-1a prime
102102
return h % self.bucket + self.nb_words
103103

104-
def _get_subwords(self, word):
104+
def _get_subwords(self, word: str) -> tuple[list[str], Any]:
105105
"""Extracts subwords and their corresponding indices for a given word."""
106106
_word = "<" + word + ">"
107107
_subwords = []
@@ -128,7 +128,7 @@ def _get_subwords(self, word):
128128

129129
return _subwords, self.np.array(_subword_ids)
130130

131-
def get_word_vector(self, word):
131+
def get_word_vector(self, word: str) -> Any:
132132
"""Computes the normalized vector for a single word."""
133133
# subword_ids[1] contains the array of indices for the word and its subwords
134134
subword_ids = self._get_subwords(word)[1]
@@ -150,7 +150,7 @@ def get_word_vector(self, word):
150150

151151
return vector
152152

153-
def _tokenize(self, sentence):
153+
def _tokenize(self, sentence: str) -> list[str]:
154154
"""Tokenizes a sentence based on whitespace."""
155155
tokens = []
156156
word = ""
@@ -167,7 +167,7 @@ def _tokenize(self, sentence):
167167
tokens.append(word)
168168
return tokens
169169

170-
def get_sentence_vector(self, line):
170+
def get_sentence_vector(self, line: str) -> Any:
171171
"""Computes the mean vector for a sentence."""
172172
tokens = self._tokenize(line)
173173
vectors = []
@@ -184,7 +184,9 @@ def get_sentence_vector(self, line):
184184

185185
# --- Nearest Neighbor Method ---
186186

187-
def get_word_suggestion(self, list_word):
187+
def get_word_suggestion(
188+
self, list_word: Union[str, list[str]]
189+
) -> Union[list[str], list[list[str]]]:
188190
"""Queries the ONNX model to find the nearest neighbor word(s)
189191
for the given word or list of words.
190192
@@ -227,7 +229,7 @@ def get_word_suggestion(self, list_word):
227229

228230

229231
class Words_Spelling_Correction(FastTextEncoder):
230-
def __init__(self):
232+
def __init__(self) -> None:
231233
self.model_name = "pythainlp/word-spelling-correction-char2vec"
232234
self.model_path = get_hf_hub(self.model_name)
233235
self.model_onnx = get_hf_hub(self.model_name, "nearest_neighbors.onnx")
@@ -272,4 +274,4 @@ def get_words_spell_suggestion(
272274
global _WSC
273275
if _WSC is None:
274276
_WSC = Words_Spelling_Correction()
275-
return _WSC.get_word_suggestion(list_words) # type: ignore[no-any-return]
277+
return _WSC.get_word_suggestion(list_words)

pythainlp/tag/named_entity.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def load_engine(self, engine: str, corpus: str) -> None:
7070
)
7171

7272
def tag(
73-
self, text, pos=False, tag=False
73+
self, text: str, pos: bool = False, tag: bool = False
7474
) -> Union[list[tuple[str, str]], list[tuple[str, str, str]], str]:
7575
"""This function tags named entities in text in IOB format.
7676
@@ -123,7 +123,7 @@ def load_engine(self, engine: str = "thai_nner") -> None:
123123

124124
self.engine = Thai_NNER()
125125

126-
def tag(self, text) -> tuple[list[str], list[dict]]:
126+
def tag(self, text: str) -> tuple[list[str], list[dict[Any, Any]]]:
127127
"""This function tags nested named entities.
128128
129129
:param str text: text in Thai to be tagged

pythainlp/tag/thai_nner.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,20 @@
33
# SPDX-License-Identifier: Apache-2.0
44
from __future__ import annotations
55

6+
from typing import Any, Optional
7+
68
from thai_nner import NNER
79

810
from pythainlp.corpus import get_corpus_path
911

1012

1113
class Thai_NNER:
12-
def __init__(self, path_model=get_corpus_path("thai_nner", "1.0")) -> None:
14+
def __init__(
15+
self, path_model: Optional[str] = None
16+
) -> None:
17+
if path_model is None:
18+
path_model = get_corpus_path("thai_nner", "1.0")
1319
self.model = NNER(path_model=path_model)
1420

15-
def tag(self, text) -> tuple[list[str], list[dict[str, str]]]:
21+
def tag(self, text: str) -> tuple[list[str], list[dict[str, Any]]]:
1622
return self.model.get_tag(text) # type: ignore[no-any-return]

0 commit comments

Comments
 (0)