Taizo Kaneko
commited on
Commit
·
6ee9897
1
Parent(s):
64ec444
commit files to HF hub
Browse files- fasttext_jp_embedding.py +10 -1
- fasttext_jp_tokenizer.py +62 -11
- mecab_tokenizer.py +2 -0
fasttext_jp_embedding.py
CHANGED
@@ -6,11 +6,18 @@ import torch
|
|
6 |
|
7 |
|
8 |
class FastTextJpConfig(PretrainedConfig):
|
9 |
-
"""
|
10 |
"""
|
11 |
model_type = "fasttext_jp"
|
12 |
|
13 |
def __init__(self, tokenizer_class="FastTextJpTokenizer", **kwargs):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
kwargs["tokenizer_class"] = tokenizer_class
|
15 |
super().__init__(**kwargs)
|
16 |
|
@@ -29,5 +36,7 @@ class FastTextJpModel(PreTrainedModel):
|
|
29 |
return self.word_embeddings(torch.tensor([0]))
|
30 |
|
31 |
|
|
|
|
|
32 |
FastTextJpConfig.register_for_auto_class()
|
33 |
FastTextJpModel.register_for_auto_class("AutoModel")
|
|
|
6 |
|
7 |
|
8 |
class FastTextJpConfig(PretrainedConfig):
|
9 |
+
"""FastTextJpModelのConfig
|
10 |
"""
|
11 |
model_type = "fasttext_jp"
|
12 |
|
13 |
def __init__(self, tokenizer_class="FastTextJpTokenizer", **kwargs):
|
14 |
+
"""初期化処理
|
15 |
+
|
16 |
+
Args:
|
17 |
+
tokenizer_class (str, optional):
|
18 |
+
tokenizer_classを指定しないと、pipelineから読み込まれません。
|
19 |
+
config.jsonに記載されます。
|
20 |
+
"""
|
21 |
kwargs["tokenizer_class"] = tokenizer_class
|
22 |
super().__init__(**kwargs)
|
23 |
|
|
|
36 |
return self.word_embeddings(torch.tensor([0]))
|
37 |
|
38 |
|
39 |
+
# AutoModelに登録が必要だが、いろいろやり方が変わっているようで定まっていない。(2022/11/6)
|
40 |
+
# https://huggingface.co/docs/transformers/custom_models#sending-the-code-to-the-hub
|
41 |
FastTextJpConfig.register_for_auto_class()
|
42 |
FastTextJpModel.register_for_auto_class("AutoModel")
|
fasttext_jp_tokenizer.py
CHANGED
@@ -6,6 +6,16 @@ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
|
6 |
|
7 |
|
8 |
def save_stoi(stoi: dict[str, int], vocab_file: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
with open(vocab_file, "w", encoding="utf-8") as writer:
|
10 |
index = 0
|
11 |
for token, token_index in sorted(stoi.items(), key=lambda kv: kv[1]):
|
@@ -18,9 +28,21 @@ def save_stoi(stoi: dict[str, int], vocab_file: str):
|
|
18 |
|
19 |
|
20 |
def load_stoi(vocab_file: str) -> dict[str, int]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
stoi: dict[str, int] = {}
|
|
|
22 |
with open(vocab_file, "r", encoding="utf-8") as reader:
|
23 |
tokens = reader.readlines()
|
|
|
|
|
24 |
for index, token in enumerate(tokens):
|
25 |
token = token.rstrip("\n")
|
26 |
stoi[token] = index
|
@@ -28,8 +50,12 @@ def load_stoi(vocab_file: str) -> dict[str, int]:
|
|
28 |
|
29 |
|
30 |
class FastTextJpTokenizer(MeCabTokenizer):
|
|
|
|
|
|
|
31 |
model_type = "fasttext_jp"
|
32 |
|
|
|
33 |
vocab_files_names = VOCAB_FILES_NAMES
|
34 |
|
35 |
def __init__(self,
|
@@ -53,35 +79,58 @@ class FastTextJpTokenizer(MeCabTokenizer):
|
|
53 |
)
|
54 |
self.stoi = load_stoi(vocab_file)
|
55 |
self.itos = dict([(ids, tok) for tok, ids in self.stoi.items()])
|
56 |
-
self.v_size = len(self.stoi)
|
57 |
-
|
58 |
-
# self._auto_map = {
|
59 |
-
# "AutoTokenizer": ["modeling.FastTextMeCabTokenizer", None]
|
60 |
-
# }
|
61 |
-
# self.init_inputs = ["vocab.txt"]
|
62 |
|
63 |
@property
|
64 |
def vocab_size(self) -> int:
|
|
|
|
|
|
|
|
|
|
|
65 |
"""
|
66 |
-
|
67 |
-
"""
|
68 |
-
return self.v_size
|
69 |
|
70 |
def _convert_token_to_id(self, token: str) -> int:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
return self.stoi[token]
|
72 |
|
73 |
def _convert_id_to_token(self, index: int) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
return self.itos[index]
|
75 |
|
76 |
def save_vocabulary(self,
|
77 |
save_directory: str,
|
78 |
filename_prefix: str | None = None) -> tuple[str]:
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
if os.path.isdir(save_directory):
|
81 |
vocab_file = os.path.join(
|
82 |
save_directory,
|
83 |
(filename_prefix + "-" if filename_prefix else "") +
|
84 |
-
"
|
85 |
else:
|
86 |
vocab_file = (filename_prefix +
|
87 |
"-" if filename_prefix else "") + save_directory
|
@@ -89,4 +138,6 @@ class FastTextJpTokenizer(MeCabTokenizer):
|
|
89 |
return (vocab_file, )
|
90 |
|
91 |
|
|
|
|
|
92 |
FastTextJpTokenizer.register_for_auto_class("AutoTokenizer")
|
|
|
6 |
|
7 |
|
8 |
def save_stoi(stoi: dict[str, int], vocab_file: str):
|
9 |
+
"""単語IDの辞書を配列にしてvocab_fileに保存します。
|
10 |
+
|
11 |
+
Args:
|
12 |
+
stoi (dict[str, int]): 単語IDのマッピング
|
13 |
+
vocab_file (str): 保存するパス
|
14 |
+
|
15 |
+
Raises:
|
16 |
+
ValueError: IDが途切れているとエラーを起こします。
|
17 |
+
"""
|
18 |
+
|
19 |
with open(vocab_file, "w", encoding="utf-8") as writer:
|
20 |
index = 0
|
21 |
for token, token_index in sorted(stoi.items(), key=lambda kv: kv[1]):
|
|
|
28 |
|
29 |
|
30 |
def load_stoi(vocab_file: str) -> dict[str, int]:
|
31 |
+
"""ファイルから単語IDの辞書をロードします。
|
32 |
+
|
33 |
+
Args:
|
34 |
+
vocab_file (str): ファイルのパス
|
35 |
+
|
36 |
+
Returns:
|
37 |
+
dict[str, int]: 単語IDのマッピング
|
38 |
+
"""
|
39 |
+
|
40 |
stoi: dict[str, int] = {}
|
41 |
+
# ファイルから読み出し
|
42 |
with open(vocab_file, "r", encoding="utf-8") as reader:
|
43 |
tokens = reader.readlines()
|
44 |
+
|
45 |
+
# 単語IDのマッピングを生成します。
|
46 |
for index, token in enumerate(tokens):
|
47 |
token = token.rstrip("\n")
|
48 |
stoi[token] = index
|
|
|
50 |
|
51 |
|
52 |
class FastTextJpTokenizer(MeCabTokenizer):
|
53 |
+
|
54 |
+
# Configが認識するのに必要です。
|
55 |
+
# https://huggingface.co/docs/transformers/custom_models#writing-a-custom-configuration
|
56 |
model_type = "fasttext_jp"
|
57 |
|
58 |
+
# vocab.txtを認識するのにおそらく必要。
|
59 |
vocab_files_names = VOCAB_FILES_NAMES
|
60 |
|
61 |
def __init__(self,
|
|
|
79 |
)
|
80 |
self.stoi = load_stoi(vocab_file)
|
81 |
self.itos = dict([(ids, tok) for tok, ids in self.stoi.items()])
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
@property
|
84 |
def vocab_size(self) -> int:
|
85 |
+
"""ボキャブラリのサイズ
|
86 |
+
※PreTrainedTokenizerで実装すべき必須の関数。
|
87 |
+
|
88 |
+
Returns:
|
89 |
+
int: ボキャブラリのサイズ
|
90 |
"""
|
91 |
+
return len(self.stoi)
|
|
|
|
|
92 |
|
93 |
def _convert_token_to_id(self, token: str) -> int:
|
94 |
+
"""単語からID
|
95 |
+
※PreTrainedTokenizerで実装すべき必須の関数。
|
96 |
+
|
97 |
+
Args:
|
98 |
+
token (str): 単語
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
int: ID
|
102 |
+
"""
|
103 |
return self.stoi[token]
|
104 |
|
105 |
def _convert_id_to_token(self, index: int) -> str:
|
106 |
+
"""IDから単語
|
107 |
+
※PreTrainedTokenizerで実装すべき必須の関数。
|
108 |
+
|
109 |
+
Args:
|
110 |
+
index (int): ID
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
str: 単語
|
114 |
+
"""
|
115 |
return self.itos[index]
|
116 |
|
117 |
def save_vocabulary(self,
|
118 |
save_directory: str,
|
119 |
filename_prefix: str | None = None) -> tuple[str]:
|
120 |
+
"""ボキャブラリの保存
|
121 |
+
|
122 |
+
Args:
|
123 |
+
save_directory (str): 保存するディレクトリ。ファイル名はvocab.txtに固定
|
124 |
+
filename_prefix (str | None, optional): ファイルのprefix
|
125 |
+
|
126 |
+
Returns:
|
127 |
+
tuple[str]: ファイル名を返す。
|
128 |
+
"""
|
129 |
if os.path.isdir(save_directory):
|
130 |
vocab_file = os.path.join(
|
131 |
save_directory,
|
132 |
(filename_prefix + "-" if filename_prefix else "") +
|
133 |
+
VOCAB_FILES_NAMES["vocab_file"])
|
134 |
else:
|
135 |
vocab_file = (filename_prefix +
|
136 |
"-" if filename_prefix else "") + save_directory
|
|
|
138 |
return (vocab_file, )
|
139 |
|
140 |
|
141 |
+
# AutoTokenizerに登録が必要だが、いろいろやり方が変わっているようで定まっていない。(2022/11/6)
|
142 |
+
# https://huggingface.co/docs/transformers/custom_models#sending-the-code-to-the-hub
|
143 |
FastTextJpTokenizer.register_for_auto_class("AutoTokenizer")
|
mecab_tokenizer.py
CHANGED
@@ -5,6 +5,8 @@ from transformers import PreTrainedTokenizer
|
|
5 |
|
6 |
|
7 |
class MeCabResult(NamedTuple):
|
|
|
|
|
8 |
hyosokei: str
|
9 |
hinshi: str
|
10 |
hinshi_saibunrui_1: str
|
|
|
5 |
|
6 |
|
7 |
class MeCabResult(NamedTuple):
|
8 |
+
"""MeCab解析結果の型
|
9 |
+
"""
|
10 |
hyosokei: str
|
11 |
hinshi: str
|
12 |
hinshi_saibunrui_1: str
|