-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_tokenizer.py
271 lines (222 loc) · 9.08 KB
/
custom_tokenizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import re
import spacy
from spacy.util import compile_prefix_regex, compile_infix_regex, compile_suffix_regex
from spacy.tokenizer import Tokenizer
import inspect
from emoji import EMOJI_DATA
import json
import progressbar
import ast
def get_progressbar(N, name=""):
return progressbar.ProgressBar(
maxval=N,
widgets=[progressbar.Bar('#', '[', ']'),
name,
progressbar.Percentage()])
class CustomToken:
def __init__(self, text, lex=None, is_stop=False,
is_sy=False, is_title=False, is_end=False,
pos='', tag='', vector=None, dep='', sent='') -> None:
self.text = text
self.is_stop = is_stop
# self.is_date = False
self.is_symbol = is_sy
self.lemma = lex
self.syntax = (is_title, pos, tag, dep, is_end)
self.vector = None if vector is None else tuple(vector)
self.sent = sent
def clone(self):
token = CustomToken(self.text)
token.__dict__ = self.__dict__
return token
@staticmethod
def cluster_list(list):
clusters, token = {}, CustomToken('')
for name, method in inspect.getmembers(token, predicate=inspect.ismethod):
if name.startswith('_') or name == 'cluster_list':
continue
clusters[name] = []
for word in list:
token.text = word.text
if method():
clusters[name].append(word)
return clusters
def unknown(self):
result = True
for name, method in inspect.getmembers(self, predicate=inspect.ismethod):
if name.startswith('_') or name == 'cluster_list' or 'unknown' == name:
continue
result = result and not method()
return result
def space(self):
return re.fullmatch(r'\s+', self.text) != None or not any(self.text)
def is_emoji(self):
return self.text in EMOJI_DATA
def is_digit(self):
return re.fullmatch(r'[0-9\%ª]+', self.text) != None
def is_hashtag(self):
return re.fullmatch(r'\#.*', self.text) != None
def is_user_tag(self):
return re.fullmatch('@.*', self.text) != None
def is_url(self):
return re.fullmatch(r'''^https?://.*''', self.text) != None
def is_date(self):
return re.fullmatch(r'[(0-9)+\/(pm)(am)\s\-]+', self.text) != None and not self.space() and not self.is_digit()
def natural_word(self):
return re.fullmatch(r'[a-zA-ZáéíóúñÁÉÍÓÚüUÜÑ]+', self.text) != None
def combined_word(self):
return re.fullmatch(r'[a-zA-ZáéíóúñÁÉÍÓÚüUÜÑ\-\_]+', self.text) != None and not self.natural_word()
def contract_word(self):
return re.fullmatch(r'[a-zA-ZáéíóúñÁÉÍÓÚüUÜÑ\-\_\'’`]+', self.text) != None and not self.combined_word() and not self.natural_word()
def numeral_word(self):
return (
re.fullmatch(r'[a-zA-ZáéíóúñÁÉÍÓÚüUÜÑ\-\_\_0-9\@]+', self.text) != None and
not self.combined_word() and
not self.natural_word() and
not self.is_user_tag() and
not self.is_digit()
)
def __eq__(self, __o: object) -> bool:
return __o.text == self.text
def __hash__(self) -> int:
return hash(self.text)
class SpacyCustomTokenizer:
basic_regex = [r'[\(\)\[\]\{\},;\!\?\+\*\"¬¨\.¿¡:“”|\$\/=]+', r'\s+']
sp_fix_regex = [r'[\'\-\_\\/″]+']
prefix_regex = []
delete_prefix_regex = ['#']
suffix_regex = []
delete_suffix_regex = []
infix_regex = []
delete_infix_regex = []
def __init__(self, special_cases={}) -> None:
self.memory = {}
self.embedding = {}
self.nlp = spacy.load("es_core_news_sm")
emoji = [str(key) for key in EMOJI_DATA.keys()]
emoji = ''.join(emoji)
emoji = f'[{emoji}]+'
self.sp_fix_regex.append(emoji)
prefixes = list(self.nlp.Defaults.prefixes)
for reg in self.delete_prefix_regex:
prefixes.remove(reg)
self.prefix_regex = compile_prefix_regex(
prefixes + self.prefix_regex + self.basic_regex + self.sp_fix_regex)
suffixes = list(self.nlp.Defaults.suffixes)
for reg in self.delete_suffix_regex:
suffixes.remove(reg)
self.suffix_regex = compile_suffix_regex(
suffixes + self.suffix_regex + self.basic_regex + self.sp_fix_regex)
infixes = list(self.nlp.Defaults.infixes)
for reg in self.delete_infix_regex:
infixes.remove(reg)
self.infix_regex = compile_infix_regex(
infixes + self.infix_regex + self.basic_regex)
simple_url_re = re.compile(r'''^https?://.*''')
self.nlp.tokenizer = Tokenizer(self.nlp.vocab, rules=special_cases,
prefix_search=self.prefix_regex.search,
suffix_search=self.suffix_regex.search,
infix_finditer=self.infix_regex.finditer,
url_match=simple_url_re.match
)
def __save__(self, path='token_text.json'):
with open(path, 'w+') as f:
f.write(str(self.memory))
f.close()
def __load__(self, path='token_text.json'):
try:
with open(path, 'r') as f:
text = f.read()
if not any(text):
return
self.memory = ast.literal_eval(text)
f.close()
except:
pass
def __ents__(self, text):
return self.nlp(text).ents
def __transform__(self, token):
return CustomToken(token.text, is_stop=token.is_stop, is_sy=token.is_punct or token.is_left_punct,
lex=token.lemma_, is_title=token.is_title or token.is_sent_start, is_end=token.is_sent_end,
pos=token.pos_, tag=token.tag_, dep=token.dep_,
vector=token.vector, sent=token.sent.text)
def __call__(self, text):
hsh = str(hash(text))
if hsh in self.memory:
for obj in self.memory[hsh]:
t = CustomToken('')
t.text = obj["text"]
t.is_stop = obj["is_stop"]
t.is_symbol = obj["is_symbol"]
t.lemma = obj["lemma"]
t.syntax = obj["syntax"]
# t.vector = obj["vector"]
t.sent = obj["sent"]
yield t
else:
self.memory[hsh] = []
for token in self.nlp(text):
for t in self.__check_token__(token.text, self.__transform__(token)):
t.sent = token.sent.text
self.memory[hsh].append({
"text": t.text,
"is_stop": t.is_stop,
"is_symbol": t.is_symbol,
"lemma": t.lemma,
"syntax": t.syntax,
# "vector": t.vector,
"sent": t.sent
})
self.embedding[t.text] = tuple(t.vector)
yield t
self.memory[hsh] = tuple(self.memory[hsh])
def __check_token__(self, text, h_token):
for name, method in inspect.getmembers(self, predicate=inspect.ismethod):
if name.startswith('_'):
continue
tokens = method(text, h_token)
if any(tokens):
for t in tokens:
yield t
break
else:
h_token.text = text
yield h_token
def prefix_re_check(self, text, h_token):
m = self.prefix_regex.search(text)
if m is None:
return []
if m.start() == 0 and m.end != len(text):
token = self.nlp(text[0: m.end()])[0]
return [self.__transform__(token)] + list(self.__check_token__(text[m.end():], h_token))
return []
def suffix_re_check(self, text, h_token):
m = self.suffix_regex.search(text)
if m is None:
return []
if m.start() != 0 and m.end == len(text):
token = self.nlp(text[m.start():])[0]
return list(self.__check_token__(text[0: m.start():], h_token)) + [self.__transform__(token)]
return []
def emoji_check(self, text, h_token):
if text in EMOJI_DATA:
return []
result = []
previous_text = ''
for c in text:
if c in EMOJI_DATA:
if previous_text != '':
result += list(self.__check_token__(previous_text, h_token))
previous_text = ''
token = self.__transform__(self.nlp(c)[0])
result.append(token)
else:
previous_text += c
if previous_text == text:
return []
return result
# def space_check(self, text, h_token):
# l = text.split(' ')
# if len(l) > 1:
# return [self.__check_token__(t, h_token) for t in l]
# return []