tokenizer.py 11.2 KB
Newer Older
huchen's avatar
huchen committed
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
#
#-------------------------------------------------------------------------
#
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
from collections import Counter
import re

import torch


SPACE_NORMALIZER = re.compile("\s+")

path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'prefixes/nonbreaking_prefix.en')
prefixes ={}

with open(path, 'r') as f:
    for line in f:
        line = line.strip()
        if line and not line[0] == '#':
            match = re.search(r'(.*)[\s]+(\#NUMERIC_ONLY\#)', line)
            if match:
                prefixes[match.group(1)] = 2
            else:
                prefixes[line] = 1

def get_unicode_categories():
    import sys
    from collections import defaultdict
    import unicodedata
    cats = defaultdict(list)
    for c in map(chr, range(sys.maxunicode + 1)):
        cats[unicodedata.category(c)].append(c)
    return cats

NUMERICS = ''.join(get_unicode_categories()['No'])

def tokenize_line(line):
    line = SPACE_NORMALIZER.sub(" ", line)
    line = line.strip()
    return line

def tokenize_en(line):
    line = line.strip()
    line = ' ' + line + ' '
    # remove ASCII junk
    line = re.sub(r'\s+', ' ', line)
    line = re.sub(r'[\x00-\x1F]', '', line)
    #fix whitespaces
    line = re.sub('\ +', ' ', line)
    line = re.sub('^ ', '', line)
    line = re.sub(' $', '', line)
    #separate other special characters
    line = re.sub(r'([^\s\.\'\`\,\-\w]|[_'+NUMERICS+'])', r' \g<1> ', line)
    line = re.sub(r'(\w)\-(?=\w)', r'\g<1> @-@ ', line)

    #multidots stay together
    line = re.sub(r'\.([\.]+)', r' DOTMULTI\g<1>', line)
    while re.search(r'DOTMULTI\.', line):
        line = re.sub(r'DOTMULTI\.([^\.])', r'DOTDOTMULTI \g<1>', line)
        line = re.sub(r'DOTMULTI\.', r'DOTDOTMULTI', line)

    # separate out "," except if within numbers (5,300)
    line = re.sub(r'([\D])[,]', r'\g<1> , ', line)
    line = re.sub(r'[,]([\D])', r' , \g<1>', line)

    # separate "," after a number if it's the end of sentence
    line = re.sub(r'(\d)[,]$', r'\g<1> ,', line)

    # split contractions right
    line = re.sub(r'([\W\d])[\']([\W\d])', '\g<1> \' \g<2>', line)
    line = re.sub(r'(\W)[\']([\w\D])', '\g<1> \' \g<2>', line)
    line = re.sub(r'([\w\D])[\']([\W\d])', '\g<1> \' \g<2>', line)
    line = re.sub(r'([\w\D])[\']([\w\D])', '\g<1> \'\g<2>', line)
    # special case for "1990's"
    line = re.sub(r'([\W\d])[\']([s])', '\g<1> \'\g<2>', line)

    # apply nonbreaking prefixes
    words = line.split()
    line = ''
    for i in range(len(words)):
        word = words[i]
        match =  re.search(r'^(\S+)\.$', word)
        if match:
            pre = match.group(1)
            if i==len(words)-1:
                # split last words independently as they are unlikely to be non-breaking prefixes
                word = pre+' .'
            elif ((re.search(r'\.', pre) and re.search(r'[^\.\W\d]', pre))
                    or (pre in prefixes and prefixes[pre]==1)
                    or re.search(r'^[a-z]', words[i+1])
                    or (pre in prefixes and prefixes[pre]==2 and re.search(r'^[0-9]+', words[i+1]))):
                pass
            else:
                word = pre+' .'

        word +=' '
        line += word

    # clean up extraneous spaces
    line = re.sub(' +', ' ', line)
    line = re.sub('^ ', '', line)
    line = re.sub(' $', '', line)

    # .' at end of sentence is missed
    line = re.sub(r'\.\' ?$', ' . \' ', line)

    #restore multi-dots
    while re.search('DOTDOTMULTI', line):
        line = re.sub('DOTDOTMULTI', 'DOTMULTI.', line)

    line = re.sub('DOTMULTI', '.', line)

    # escape special characters
    line = re.sub(r'\&', r'&amp;', line)
    line = re.sub(r'\|', r'&#124;', line)
    line = re.sub(r'\<', r'&lt;', line)
    line = re.sub(r'\>', r'&gt;', line)
    line = re.sub(r'\'', r'&apos;', line)
    line = re.sub(r'\"', r'&quot;', line)
    line = re.sub(r'\[', r'&#91;', line)
    line = re.sub(r'\]', r'&#93;', line)

    #ensure final line breaks
    if line[-1] != '\n':
        line += '\n'

    return line

def deescape(line):
    line = re.sub(r'&#124;', r'|', line)
    line = re.sub(r'&lt;', r'<', line)
    line = re.sub(r'&gt;', r'>', line)
    line = re.sub(r'&quot;', '\"', line)
    line = re.sub(r'&apos;', '\'', line)
    line = re.sub(r'&#91;', r'[', line)
    line = re.sub(r'&#93;', r']', line)
    line = re.sub(r'&amp;', r'&', line)
    return line


class Tokenizer:

    @staticmethod
    def add_file_to_dictionary(filename, dict, tokenize):
        with open(filename, 'r') as f:
            for line in f:
                for word in tokenize(line).split():
                    dict.add_symbol(word)
                dict.add_symbol(dict.eos_word)

    @staticmethod
    def binarize(filename, dict, consumer, tokenize=tokenize_line,
                 append_eos=True, reverse_order=False):
        nseq, ntok = 0, 0
        replaced = Counter()

        def replaced_consumer(word, idx):
            if idx == dict.unk_index and word != dict.unk_word:
                replaced.update([word])

        with open(filename, 'r') as f:
            for line in f:
                ids = Tokenizer.tokenize(
                    line=line,
                    dictionary=dict,
                    tokenize=tokenize,
                    add_if_not_exist=False,
                    consumer=replaced_consumer,
                    append_eos=append_eos,
                    reverse_order=reverse_order,
                )
                nseq += 1

                consumer(ids)
                ntok += len(ids)
        return {'nseq': nseq, 'nunk': sum(replaced.values()), 'ntok': ntok, 'replaced': len(replaced)}

    @staticmethod
    def tokenize(line, dictionary, tokenize=tokenize_line, add_if_not_exist=True,
                 consumer=None, append_eos=True, reverse_order=False, bpe=None):
        line = tokenize(line)
        if bpe:
            line = bpe.process_line(line)
        words = line.split()
        if reverse_order:
            words = list(reversed(words))
        nwords = len(words)
        ids = torch.IntTensor(nwords + 1 if append_eos else nwords)

        for i, word in enumerate(words):
            if add_if_not_exist:
                idx = dictionary.add_symbol(word)
            else:
                idx = dictionary.index(word)
            if consumer is not None:
                consumer(word, idx)
            ids[i] = idx
        if append_eos:
            ids[nwords] = dictionary.eos_index
        return ids
    
    @staticmethod
    def detokenize(line, lang):
        #don't try to detokenize XML/HTML tag lines
        if re.search(r'^<.+>$', line) or re.search(r'^\s*$', line):
            return line

        line = line.strip()
        line = ' '+line+' '
        line = re.sub(r' @-@ ', '-', line)
        line = deescape(line)
        words = line.split()
        line = ''
        quote_count = {'\'':0, '\"':0}
        prepend_space = ' '
        for i in range(len(words)):
            #perform rught shift of currency and some punctuation
            if re.search(r'^[\u20ac\x24\(\[\{]+$', words[i]):
                line += prepend_space + words[i]
                prepend_space = ''
            elif re.search(r'^[\,\.\?\!\:\;\\\%\}\]\)]+$', words[i]):
                if lang=='fr' and re.search(r'^[\?\!\:\;\\\%]$', words[i]):
                    line += ' '
                line += words[i]
                prepend_space = ' '
            elif lang=='en' and i>0 and re.search(r'^[\'][\w\D]', words[i]) and re.search(r'\w$', words[i-1]):
                line += words[i]
                prepend_space = ' '
            elif lang=='cs' and i>1 and re.search(r'^\d+$', words[i-2]) and re.search(r'^[.,]$', words[i-1]) and re.search(r'^\w+$', words[i]):
                line += words[i]
                prepend_space = ' '
            elif (lang=='fr' or lang=='it') and i<len(words)-1 and re.search(r'[\w\D][\']$', words[i]) and re.search(r'^[\w\D]', words[i+1]):
                line += prepend_space + words[i]
                prepend_space = ''
            elif lang=='cs' and i<len(words)-3 and \
                    re.search(r'[\w\D]$', words[i]) and \
                    re.search(r'^-$', words[i+1]) and \
                    re.search(r'^li$|^mail.*', words[i+2], re.I):
                #line += ' '+words[i]+words[i+1]
                pass #TODO: skip one word
            elif re.search(r'^[\'\"\x60\u201c\u201d]+$', words[i]):
                normalized_quo = '\"' if re.search(r'^[\u201c\u201d]+$', words[i]) else words[i]
                quote_count[normalized_quo] = 0 if normalized_quo not in quote_count.keys() else quote_count[normalized_quo]
                if lang=='cs' and words[i] == '\u201c':
                    quote_count[normalized_quo] = 0
                if lang=='cs' and words[i] == '\u201d':
                    quote_count[normalized_quo] = 1
                if quote_count[normalized_quo] % 2 == 0:
                    if lang=='en' and words[i]=='\'' and i > 0 and re.search(r'[s]$', words[i-1]):
                        #single quote for posessives ending in s... "The Jones' house"
                        #left shift
                        line += words[i]
                        prepend_space = ' '
                    else:
                        #right shift
                        line += prepend_space + words[i]
                        prepend_space = ''
                        quote_count[normalized_quo] += 1
                else:
                    #left shift
                    line += words[i]
                    prepend_space = ' '
                    quote_count[normalized_quo] += 1
            elif lang=='fi' and re.search(r':$', words[i-1]) and re.search(r'^(N|n|A|a|Ä|ä|ssa|Ssa|ssä|Ssä|sta|stä|Sta|Stä|hun|Hun|hyn|Hyn|han|Han|hän|Hän|hön|Hön|un|Un|yn|Yn|an|An|än|Än|ön|Ön|seen|Seen|lla|Lla|llä|Llä|lta|Lta|ltä|Ltä|lle|Lle|ksi|Ksi|kse|Kse|tta|Tta|ine|Ine)(ni|si|mme|nne|nsa)?(ko|kö|han|hän|pa|pä|kaan|kään|kin)?$', words[i]):
                line += words[i].lower()
                prepend_space = ' '
            else:
                line += prepend_space + words[i]
                prepend_space = ' '

        #clean up spaces at head and tail of each line as well as any double-spacing
        line = re.sub(r' +', ' ', line)
        line = re.sub(r'\n ', '\n', line)
        line = re.sub(r' \n', '\n', line)
        line = re.sub(r'^ ', '', line)
        line = re.sub(r' $', '', line)

        #add trailing break
        line += '\n' if line[-1] != '\n' else ''

        return line