-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdptree_tokenizer.py
More file actions
executable file
·700 lines (586 loc) · 24 KB
/
dptree_tokenizer.py
File metadata and controls
executable file
·700 lines (586 loc) · 24 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
# 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.
from collections import Counter
import os, re
import datetime
import torch
from multiprocessing import Pool
from nltk import Tree
from torch.utils import data
from fairseq.data import Dictionary
from dptree import tree_process, tree_builder
SPACE_NORMALIZER = re.compile(r"\s+")
PRINT_INTERVAL = int(os.environ.get('PRINT_INTERVAL', 10000))
PLACE_HOLDER = '<placeholder>'
def tokenize_line(line):
line = SPACE_NORMALIZER.sub(" ", line)
line = line.strip()
return line.split()
def safe_readline(f):
pos = f.tell()
while True:
try:
return f.readline()
except UnicodeDecodeError:
pos -= 1
f.seek(pos) # search where this character begins
def tree_str_post_process(tree_string):
tree_string = tree_string.replace('-LRB- (', '-LRB- -LRB-').replace('-RRB- )', '-RRB- -RRB-')
return tree_string
def try_parse(s):
try:
tree_string = s
tree_string = tree_str_post_process(tree_string)
tree_line = Tree.fromstring(tree_string)
except Exception as e:
print(f'Tree.fromstring(tree_string) failed, try to omit the post_process')
print(s)
try:
tree_string = s
tree_line = Tree.fromstring(tree_string)
except Exception as e:
print(f'ERROR: unable to parse the tree')
print(s)
raise e
return tree_line
def read_parse(file):
with open(file, 'r') as f:
sents = f.read().strip().split('\n')
lines = [try_parse(x) for x in sents]
return lines
def tree_from_string(s):
try:
tree_string = s
tree_string = tree_str_post_process(tree_string)
tree_line = Tree.fromstring(tree_string)
except Exception as e:
try:
tree_string = s
tree_line = Tree.fromstring(tree_string)
except Exception as e:
print(f'ERROR: unable to parse the tree')
print(s)
raise e
return tree_line
class DPTreeTokenizer(object):
@staticmethod
def line2example(s, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1, noat=False, cnf=True):
tree_string = s
tree_line = tree_from_string(tree_string)
tree_process.padding_leaves(tree_line)
tree_line = tree_process.clean_node(tree_line)
line_leaves, line_matrix, line_node_label, line_leaf_label = tree_process.tree2matrix(tree_line, cnf=cnf)
# try:
line_node, line_label, line_index = tree_process.generate_data(tree_line, cnf)
# except RecursionError as e:
if noat:
line_node = [x[1:] if x[0] == '@' else x for x in line_node]
node_indices = DPTreeTokenizer.tokenize(
words=line_node,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
labels_indices = DPTreeTokenizer.tokenize(
words=line_label,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
line_length = len(line_leaves)
# TODO: add pads
# FIXME: MUST CHECK pad_index = 1 systematically!
pad_index = 1
node_indices = torch.cat([node_indices, torch.tensor([pad_index]).int()], 0)
labels_indices = torch.cat([labels_indices, torch.tensor([pad_index]).int()], 0)
line_index += [[line_length, line_length]]
line_indices = torch.tensor(line_index).int()
line_len = torch.tensor([line_length]).int()
example = {
"nodes": node_indices,
"labels": labels_indices,
"indices": line_indices,
"length": line_len
}
return example
@staticmethod
def convert2stt5_lines(line_node, line_label):
line_tokens = []
line_sentiments = []
for i, (x, y) in enumerate(zip(line_node, line_label)):
# pad in line_label is phrase_label in line_node
if y == '<pad>':
line_tokens.append(PLACE_HOLDER)
line_sentiments.append(int(x.replace('_node_label', '')))
else:
line_tokens.append(x)
line_sentiments.append(int(y.replace('_leaf_label', '')))
return line_tokens, line_sentiments
@staticmethod
def line2example_sst5(s, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1, noat=False):
"""This one has no node-label, instead return objects that has labeling index"""
tree_string = s
# tree_string = tree_str_post_process(tree_string)
tree_line = tree_from_string(tree_string)
tree_process.padding_leaves(tree_line)
tree_line = tree_process.clean_node(tree_line)
line_leaves, line_matrix, line_node_label, line_leaf_label = tree_process.tree2matrix(tree_line)
line_node, line_label, line_index = tree_process.generate_data(tree_line)
line_tokens, line_sentiments = DPTreeTokenizer.convert2stt5_lines(line_node, line_label)
if noat:
line_tokens = [x[1:] if x[0] == '@' else x for x in line_tokens]
node_indices = DPTreeTokenizer.tokenize(
words=line_tokens,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
if append_eos:
line_sentiments.append(0)
sentiment_indices = torch.tensor(line_sentiments).int()
line_length = len(line_leaves)
# TODO: add pads
# FIXME: MUST CHECK pad_index = 1 systematically!
pad_index = 1
node_indices = torch.cat([node_indices, torch.tensor([pad_index]).int()], 0)
sentiment_indices = torch.cat([sentiment_indices, torch.tensor([pad_index]).int()], 0)
line_index += [[line_length, line_length]]
line_indices = torch.tensor(line_index).int()
line_len = torch.tensor([line_length]).int()
example = {
"nodes": node_indices,
"labels": sentiment_indices,
"indices": line_indices,
"length": line_len
}
return example
@staticmethod
def line2example_sst5_plb(
s, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1):
"""This one has node-label, instead return objects that has labeling index"""
tree_string = s
# tree_string = tree_str_post_process(tree_string)
tree_line = tree_from_string(tree_string)
tree_process.padding_leaves(tree_line)
tree_line = tree_process.clean_node(tree_line)
line_leaves, line_matrix, line_node_label, line_leaf_label = tree_process.tree2matrix(tree_line)
line_node, line_label, line_index = tree_process.generate_data(tree_line)
line_tokens, line_sentiments = DPTreeTokenizer.convert2stt5_lines(line_node, line_label)
node_indices = DPTreeTokenizer.tokenize(
words=line_tokens,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
if append_eos:
line_sentiments.append(0)
sentiment_indices = torch.tensor(line_sentiments).int()
line_length = len(line_leaves)
# TODO: add pads
# FIXME: MUST CHECK pad_index = 1 systematically!
pad_index = 1
node_indices = torch.cat([node_indices, torch.tensor([pad_index]).int()], 0)
sentiment_indices = torch.cat([sentiment_indices, torch.tensor([pad_index]).int()], 0)
line_index += [[line_length, line_length]]
line_indices = torch.tensor(line_index).int()
line_len = torch.tensor([line_length]).int()
example = {
"nodes": node_indices,
"labels": sentiment_indices,
"indices": line_indices,
"length": line_len
}
return example
@staticmethod
def line2multi_example(
s, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1,
line2example=None,
noat=False,
cnf=True,
):
tree_strings = s.split(tree_builder.TreeBuilder.SENT_SPLITTER)
try:
if line2example is None:
line2example = DPTreeTokenizer.line2example
examples = [line2example(
x, vocab, consumer, tokenize, append_eos, reverse_order, add_if_not_exist,
offset, end, noat=noat, cnf=cnf,
) for x in tree_strings]
except ValueError as ve:
print(f'Error in this example')
print(s)
raise ve
keys = list(examples[0].keys())
def merge_trees(tensors, pad_idx=1):
"""
[(n1, d...), (n2, d...), (nm]
:param tensors:
:return: [m, max(n1...nm), d...]
"""
size = max(v.size(0) for v in tensors)
rest_size = list(tensors[0].size()[1:])
res = tensors[0].new(len(tensors), size, *rest_size).fill_(pad_idx)
def copy_tensor(src, dst):
assert dst.numel() == src.numel()
dst.copy_(src)
for i, v in enumerate(tensors):
copy_tensor(v, res[i][:len(v)])
return res
ntok = sum([len(x['nodes']) for x in examples])
examples_d = {
"nodes": merge_trees([x['nodes'] for x in examples], 1),
"labels": merge_trees([x['labels'] for x in examples], 1),
"indices": merge_trees([x['indices'] for x in examples], 0),
"length": torch.cat([x['length'] for x in examples], 0),
}
return examples_d, ntok
@staticmethod
def line2leaves_n_nodes(s, noat=False, cnf=True):
line_nodes = []
line_labels = []
strings = s.split(tree_builder.TreeBuilder.SENT_SPLITTER)
for s in strings:
tree_string = s
# tree_string = tree_str_post_process(tree_string)
tree_line = tree_from_string(tree_string)
tree_process.padding_leaves(tree_line)
tree_line = tree_process.clean_node(tree_line)
try:
line_node, line_label, line_index = tree_process.generate_data(tree_line, cnf=cnf)
if noat:
line_node = [x[1:] if x[0] == '@' else x for x in line_node]
except IndexError as e:
print(tree_string)
tree_line.pretty_print()
raise e
except RecursionError as er:
print("Recursion error due to too long tree -> omit the tree")
continue
line_nodes += line_node
line_labels += line_label
return line_nodes, line_labels
@staticmethod
def add_file_to_dictionary_single_worker(filename, tokenize, eos_word, worker_id=0, num_workers=1):
counter = Counter()
with open(filename, 'r') as f:
size = os.fstat(f.fileno()).st_size
chunk_size = size // num_workers
offset = worker_id * chunk_size
end = offset + chunk_size
f.seek(offset)
if offset > 0:
safe_readline(f) # drop first incomplete line
line = f.readline()
while line:
for word in tokenize(line):
counter.update([word])
counter.update([eos_word])
if f.tell() > end:
break
line = f.readline()
return counter
@staticmethod
def add_file_to_dictionary(filename, vocab, tokenize, num_workers):
def merge_result(counter):
for w, c in counter.items():
vocab.add_symbol(w, c)
if num_workers > 1:
pool = Pool(processes=num_workers)
results = []
for worker_id in range(num_workers):
results.append(pool.apply_async(
DPTreeTokenizer.add_file_to_dictionary_single_worker,
(filename, tokenize, vocab.eos_word, worker_id, num_workers)
))
pool.close()
pool.join()
for r in results:
merge_result(r.get())
else:
merge_result(DPTreeTokenizer.add_file_to_dictionary_single_worker(filename, tokenize, vocab.eos_word))
@staticmethod
def binarize(filename, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1, **kwargs):
nseq, ntok = 0, 0
replaced = Counter()
def replaced_consumer(word, idx):
if idx == vocab.unk_index and word != vocab.unk_word:
replaced.update([word])
with open(filename, 'r') as f:
f.seek(offset)
# next(f) breaks f.tell(), hence readline() must be used
line = safe_readline(f)
while line:
if end > 0 and f.tell() > end:
break
example = DPTreeTokenizer.line2example(
s=line,
vocab=vocab,
consumer=replaced_consumer,
tokenize=tokenize,
append_eos=append_eos,
reverse_order=reverse_order,
add_if_not_exist=add_if_not_exist,
offset=offset,
end=end
)
nseq += 1
ntok += len(example['nodes'])
consumer(example)
line = f.readline()
if nseq == 1 or nseq % PRINT_INTERVAL == 0:
now = str(datetime.datetime.now().time())
print(f'Dptree:binarize:[{now}] offset={offset}: '
f'nseq={nseq}, dict={len(vocab)}')
return {'nseq': nseq, 'nunk': sum(replaced.values()), 'ntok': ntok, 'replaced': replaced}
@staticmethod
def binarize_separate(
filename, vocab, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=False,
offset=0, end=-1,
worker_id=None
):
nseq, ntok = 0, 0
replaced = Counter()
def replaced_consumer(word, idx):
if idx == vocab.unk_index and word != vocab.unk_word:
replaced.update([word])
with open(filename, 'r') as f:
f.seek(offset)
# next(f) breaks f.tell(), hence readline() must be used
line = safe_readline(f)
while line:
if 0 < end < f.tell():
break
example, ntok_ = DPTreeTokenizer.line2multi_example(
s=line,
vocab=vocab,
consumer=replaced_consumer,
tokenize=tokenize,
append_eos=append_eos,
reverse_order=reverse_order,
add_if_not_exist=add_if_not_exist,
offset=offset,
end=end
)
nseq += 1
# ntok += sum([len(x) for x in example['nodes']])
ntok += ntok_
consumer(example)
line = f.readline()
if nseq == 1 or nseq % PRINT_INTERVAL == 0:
now = str(datetime.datetime.now().time())
print(f'Dptree:binarize:[{now}]-[worker_id={worker_id}] offset={offset}: '
f'nseq={nseq}, dict={len(vocab)}')
return {'nseq': nseq, 'nunk': sum(replaced.values()), 'ntok': ntok, 'replaced': replaced}
@staticmethod
def acquire_vocab(filename, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=True,
offset=0, end=-1):
nseq, ntok = 0, 0
replaced = Counter()
vocab = Dictionary()
def replaced_consumer(word, idx):
if idx == vocab.unk_index and word != vocab.unk_word:
replaced.update([word])
with open(filename, 'r') as f:
f.seek(offset)
line = safe_readline(f)
while line:
if end > 0 and f.tell() > end:
break
line_node, line_label = DPTreeTokenizer.line2leaves_n_nodes(line)
node_indices = DPTreeTokenizer.tokenize(
words=line_node,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=replaced_consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
labels_indices = DPTreeTokenizer.tokenize(
words=line_label,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=replaced_consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
nseq += 1
# ntok += len(example['nodes'])
# consumer(example)
line = f.readline()
if nseq == 1 or nseq % PRINT_INTERVAL == 0:
print(f'Dptree:binarize: offset={offset}: nseq={nseq}, dict={len(vocab)}')
return vocab
@staticmethod
def acquire_vocab_stt5(
filename, consumer, tokenize=tokenize_line,
append_eos=False, reverse_order=False,
add_if_not_exist=True,
offset=0, end=-1):
nseq, ntok = 0, 0
replaced = Counter()
vocab = Dictionary()
def replaced_consumer(word, idx):
if idx == vocab.unk_index and word != vocab.unk_word:
replaced.update([word])
with open(filename, 'r') as f:
f.seek(offset)
line = safe_readline(f)
while line:
if end > 0 and f.tell() > end:
break
line_node, line_label = DPTreeTokenizer.line2leaves_n_nodes(line)
line_tokens, line_sentiments = DPTreeTokenizer.convert2stt5_lines(line_node, line_label)
node_indices = DPTreeTokenizer.tokenize(
words=line_tokens,
vocab=vocab,
tokenize=tokenize,
add_if_not_exist=add_if_not_exist,
consumer=replaced_consumer,
append_eos=append_eos,
reverse_order=reverse_order,
)
nseq += 1
line = f.readline()
if nseq == 1 or nseq % PRINT_INTERVAL == 0:
now = str(datetime.datetime.now().time())
print(f'Dptree:binarize:[{now}] offset={offset}: '
f'nseq={nseq}, dict={len(vocab)}')
return vocab
@staticmethod
def acquire_vocab_multithread(
filename, vocab, tokenize=tokenize_line, num_workers=1,
add_single_thread=None, noat=False, cnf=True,
):
def merge_result(counter):
for w, c in counter.items():
vocab.add_symbol(w, c)
if add_single_thread is None:
add_single_thread = DPTreeTokenizer.add_to_vocab_single_thread
if num_workers > 1:
pool = Pool(processes=num_workers)
results = []
for worker_id in range(num_workers):
results.append(pool.apply_async(
add_single_thread,
(filename, tokenize, vocab.eos_word, worker_id, num_workers, noat, cnf)
))
pool.close()
pool.join()
assert len(results) == num_workers, f'{len(results)} processes died!'
for r in results:
merge_result(r.get())
else:
merge_result(DPTreeTokenizer.add_to_vocab_single_thread(filename, tokenize, vocab.eos_word, noat=noat, cnf=cnf))
@staticmethod
def add_to_vocab_single_thread(filename, tokenize, eos_word, worker_id=0, num_workers=1, noat=False, cnf=True):
counter = Counter()
with open(filename, 'r', encoding='utf-8') as f:
size = os.fstat(f.fileno()).st_size
chunk_size = size // num_workers
offset = worker_id * chunk_size
end = offset + chunk_size
f.seek(offset)
if offset > 0:
safe_readline(f) # drop first incomplete line
line = f.readline()
while line:
line_node, line_label = DPTreeTokenizer.line2leaves_n_nodes(line, noat=noat, cnf=cnf)
for word in line_node:
counter.update([word])
counter.update([eos_word])
for word in line_label:
counter.update([word])
counter.update([eos_word])
if f.tell() > end:
break
line = f.readline()
return counter
@staticmethod
def add_to_vocab_single_thread_stt5(filename, tokenize, eos_word, worker_id=0, num_workers=1):
counter = Counter()
with open(filename, 'r', encoding='utf-8') as f:
size = os.fstat(f.fileno()).st_size
chunk_size = size // num_workers
offset = worker_id * chunk_size
end = offset + chunk_size
f.seek(offset)
if offset > 0:
safe_readline(f) # drop first incomplete line
line = f.readline()
while line:
line_node, line_label = DPTreeTokenizer.line2leaves_n_nodes(line)
line_tokens, line_sentiments = DPTreeTokenizer.convert2stt5_lines(line_node, line_label)
for word in line_tokens:
counter.update([word])
counter.update([eos_word])
if f.tell() > end:
break
line = f.readline()
return counter
@staticmethod
def find_offsets(filename, num_chunks):
with open(filename, 'r') as f:
size = os.fstat(f.fileno()).st_size
chunk_size = size // num_chunks
offsets = [0 for _ in range(num_chunks + 1)]
for i in range(1, num_chunks):
f.seek(chunk_size * i)
safe_readline(f)
offsets[i] = f.tell()
return offsets
@staticmethod
def tokenize(words, vocab, tokenize=tokenize_line, add_if_not_exist=True,
consumer=None, append_eos=True, reverse_order=False):
# words = tokenize(line)
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 = vocab.add_symbol(word)
else:
idx = vocab.index(word)
if consumer is not None:
consumer(word, idx)
ids[i] = idx
if append_eos:
ids[nwords] = vocab.eos_index
return ids