-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexsubsitution.py
1282 lines (994 loc) · 48 KB
/
lexsubsitution.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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
import sys
import numpy as np
import pandas
import tensorflow as tf
import collections
import six
import copy
import unicodedata
import re
from operator import itemgetter
from nltk.stem.wordnet import WordNetLemmatizer
from bert_serving.client import BertClient
from nltk.corpus import wordnet
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, "r") as reader:
while True:
token = convert_to_unicode(reader.readline())
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def printable_text(text):
"""Returns text encoded in a way suitable for print or `tf.logging`."""
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text
elif isinstance(text, unicode):
return text.encode("utf-8")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, "r") as reader:
while True:
token = convert_to_unicode(reader.readline())
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
output.append(vocab[item])
return output
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
class FullTokenizer(object):
"""Runs end-to-end tokenziation."""
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for k, v in self.vocab.items()}
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
def tokenize(self, text):
split_tokens = []
for token in self.basic_tokenizer.tokenize(text):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def convert_tokens_to_ids(self, tokens):
return convert_by_vocab(self.vocab, tokens)
def convert_ids_to_tokens(self, ids):
return convert_by_vocab(self.inv_vocab, ids)
class BasicTokenizer(object):
"""Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
def __init__(self, do_lower_case=True):
"""Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
"""
self.do_lower_case = do_lower_case
def tokenize(self, text):
"""Tokenizes a piece of text."""
text = convert_to_unicode(text)
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
# characters in the vocabulary because Wikipedia does have some Chinese
# words in the English Wikipedia.).
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xfffd or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class WordpieceTokenizer(object):
"""Runs WordPiece tokenziation."""
def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer.
Returns:
A list of wordpiece tokens.
"""
text = convert_to_unicode(text)
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat.startswith("C"):
return True
return False
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
def line2bert_service(line, target2candidates, tokenizer):
instances = [] # returned input lines for bert
full_target_key = line.split('\t')[0]
target = '.'.join(full_target_key.split('.')[:2])
index = line.split('\t')[1]
candidate_words = list(target2candidates[target])
#print(candidate_words)
text_a_raw = line.split('\t')[3].split(' ') # text_a untokenized
masked_id = int(line.split('\t')[2])
masked_word = text_a_raw[masked_id] # get the target word
#text_a_raw.insert(masked_id + 1,'and')
#text_a_raw.insert(masked_id + 2, 'MASK')
text_a_raw = ' '.join(text_a_raw)
#pat_letter = re.compile(r'[^a-zA-Z \']+')
#text_a_raw = pat_letter.sub(' ', text_a_raw).strip().lower()
pat_is = re.compile("(it|he|she|that|this|there|here)(\'s)", re.I)
# to find the 's following the letters
pat_s = re.compile("(?<=[a-zA-Z])\'s")
# to find the ' following the words ending by s
pat_s2 = re.compile("(?<=s)\'s?")
# to find the abbreviation of not
pat_not = re.compile("(?<=[a-zA-Z])n\'t")
# to find the abbreviation of would
pat_would = re.compile("(?<=[a-zA-Z])\'d")
# to find the abbreviation of will
pat_will = re.compile("(?<=[a-zA-Z])\'ll")
# to find the abbreviation of am
pat_am = re.compile("(?<=[I|i])" "\'m")
# to find the abbreviation of are
pat_are = re.compile("(?<=[a-zA-Z])\'re")
# to find the abbreviation of have
pat_ve = re.compile("(?<=[a-zA-Z])\'ve")
new_text = pat_is.sub(r"\1 is", text_a_raw)
new_text = pat_s.sub("", new_text)
new_text = pat_s2.sub("", new_text)
new_text = pat_not.sub(" not", new_text)
new_text = pat_would.sub(" would", new_text)
new_text = pat_will.sub(" will", new_text)
new_text = pat_am.sub(" am", new_text)
new_text = pat_are.sub(" are", new_text)
new_text = pat_ve.sub(" have", new_text)
text_a_raw = new_text.replace('\'', ' ')
text_a_raw = text_a_raw.split(' ')
while '' in text_a_raw:
text_a_raw.remove('')
masked_id = text_a_raw.index(masked_word)
masked_word_tokenized = tokenizer.tokenize(masked_word)
text_a_tokenized = tokenizer.tokenize(' '.join(text_a_raw))
indexs = [i for (i,wordpiece) in enumerate(text_a_tokenized) if wordpiece == masked_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < masked_id:
continue
for i in range(len(masked_word_tokenized)):
if masked_word_tokenized[i] != text_a_tokenized[index_now + i]:
flag = False
if flag == True:
target_start_id = index_now
target_end_id = index_now + len(masked_word_tokenized) - 1
break
instances.append('\t'.join([full_target_key, index, ' '.join(text_a_tokenized), str(target_start_id), str(target_end_id)]))
text_target_masked = copy.deepcopy(text_a_tokenized)
text_target_masked[target_start_id] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_target_masked), str(offset)]))
candidates = []
for candidate_word in candidate_words:
if len(candidate_word.split(' ')) != 1 or len(candidate_word.split('-')) != 1:
#print("candidate word %s filtered" %(candidate_word))
continue
line_replaced = copy.deepcopy(text_a_raw)
line_replaced[masked_id] = candidate_word
line_replaced_tokenized = tokenizer.tokenize(' '.join(line_replaced))
candidates.append(candidate_word)
candidate_word_tokenized = tokenizer.tokenize(candidate_word)
indexs = [i for i,word in enumerate(line_replaced_tokenized) if word == candidate_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < target_start_id:
continue
for i in range(len(candidate_word_tokenized)):
if candidate_word_tokenized[i] != line_replaced_tokenized[index_now + i]:
flag = False
if flag == True:
candidate_start_id = index_now
break
candidate_end_id = candidate_start_id + len(candidate_word_tokenized) - 1
instances.append('\t'.join([full_target_key, index, ' '.join(line_replaced_tokenized), str(candidate_start_id), str(candidate_end_id)]))
return instances, candidates
def line2bert_service_mask_context(line, target2candidates, tokenizer, bow_size=6):
instances = [] # returned input lines for bert
full_target_key = line.split('\t')[0]
target = '.'.join(full_target_key.split('.')[:2])
index = line.split('\t')[1]
candidate_words = list(target2candidates[target])
#print(candidate_words)
text_a_raw = line.split('\t')[3].split(' ') # text_a untokenized
masked_id = int(line.split('\t')[2])
masked_word = text_a_raw[masked_id] # get the target word
#text_a_raw.insert(masked_id + 1,'and')
#text_a_raw.insert(masked_id + 2, 'MASK')
text_a_raw = ' '.join(text_a_raw)
#pat_letter = re.compile(r'[^a-zA-Z \']+')
#text_a_raw = pat_letter.sub(' ', text_a_raw).strip().lower()
pat_is = re.compile("(it|he|she|that|this|there|here)(\'s)", re.I)
# to find the 's following the letters
pat_s = re.compile("(?<=[a-zA-Z])\'s")
# to find the ' following the words ending by s
pat_s2 = re.compile("(?<=s)\'s?")
# to find the abbreviation of not
pat_not = re.compile("(?<=[a-zA-Z])n\'t")
# to find the abbreviation of would
pat_would = re.compile("(?<=[a-zA-Z])\'d")
# to find the abbreviation of will
pat_will = re.compile("(?<=[a-zA-Z])\'ll")
# to find the abbreviation of am
pat_am = re.compile("(?<=[I|i])" "\'m")
# to find the abbreviation of are
pat_are = re.compile("(?<=[a-zA-Z])\'re")
# to find the abbreviation of have
pat_ve = re.compile("(?<=[a-zA-Z])\'ve")
new_text = pat_is.sub(r"\1 is", text_a_raw)
new_text = pat_s.sub("", new_text)
new_text = pat_s2.sub("", new_text)
new_text = pat_not.sub(" not", new_text)
new_text = pat_would.sub(" would", new_text)
new_text = pat_will.sub(" will", new_text)
new_text = pat_am.sub(" am", new_text)
new_text = pat_are.sub(" are", new_text)
new_text = pat_ve.sub(" have", new_text)
text_a_raw = new_text.replace('\'', ' ')
text_a_raw = text_a_raw.split(' ')
while '' in text_a_raw:
text_a_raw.remove('')
masked_id = text_a_raw.index(masked_word)
masked_word_tokenized = tokenizer.tokenize(masked_word)
text_a_tokenized = tokenizer.tokenize(' '.join(text_a_raw))
target_sentence_length = len(text_a_tokenized)
indexs = [i for (i,wordpiece) in enumerate(text_a_tokenized) if wordpiece == masked_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < masked_id:
continue
for i in range(len(masked_word_tokenized)):
if masked_word_tokenized[i] != text_a_tokenized[index_now + i]:
flag = False
if flag == True:
target_start_id = index_now
target_end_id = index_now + len(masked_word_tokenized) - 1
break
instances.append('\t'.join([full_target_key, index, ' '.join(text_a_tokenized), str(target_start_id), str(target_end_id)]))
offset_before_allowed = min(target_start_id, bow_size)
offset_after_allowed = min(target_sentence_length - 1, target_end_id + bow_size) - target_end_id
for offset in range(offset_before_allowed):
text_offset = copy.deepcopy(text_a_tokenized)
text_offset[target_start_id - offset - 1] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_offset), str(-offset)]))
for offset in range(offset_after_allowed):
text_offset = copy.deepcopy(text_a_tokenized)
text_offset[target_start_id + offset + 1] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_offset), str(offset)]))
num_lines_before = offset_before_allowed
num_lines_after = offset_after_allowed
text_target_masked = copy.deepcopy(text_a_tokenized)
text_target_masked[target_start_id] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_target_masked), str(offset)]))
candidates = []
for candidate_word in candidate_words:
if len(candidate_word.split(' ')) != 1 or len(candidate_word.split('-')) != 1:
#print("candidate word %s filtered" %(candidate_word))
continue
line_replaced = copy.deepcopy(text_a_raw)
line_replaced[masked_id] = candidate_word
line_replaced_tokenized = tokenizer.tokenize(' '.join(line_replaced))
candidate_sentence_length = len(line_replaced_tokenized)
candidates.append(candidate_word)
candidate_word_tokenized = tokenizer.tokenize(candidate_word)
indexs = [i for i,word in enumerate(line_replaced_tokenized) if word == candidate_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < target_start_id:
continue
for i in range(len(candidate_word_tokenized)):
if candidate_word_tokenized[i] != line_replaced_tokenized[index_now + i]:
flag = False
if flag == True:
candidate_start_id = index_now
break
candidate_end_id = candidate_start_id + len(candidate_word_tokenized) - 1
instances.append('\t'.join([full_target_key, index, ' '.join(line_replaced_tokenized), str(candidate_start_id), str(candidate_end_id)]))
offset_before_allowed = min(candidate_start_id, bow_size)
offset_after_allowed = min(candidate_sentence_length - 1, candidate_end_id + bow_size) - candidate_end_id
for offset in range(offset_before_allowed):
text_offset = copy.deepcopy(line_replaced_tokenized)
text_offset[candidate_start_id - offset - 1] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_offset), str(-offset)]))
for offset in range(offset_after_allowed):
text_offset = copy.deepcopy(line_replaced_tokenized)
text_offset[candidate_start_id + offset + 1] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_offset), str(offset)]))
return instances, candidates
def proposal2bert_service_mask(line, candidate_words, tokenizer, context_indice, context_weight):
instances = [] # returned input lines for bert
full_target_key = line.split('\t')[0]
target = '.'.join(full_target_key.split('.')[:2])
index = line.split('\t')[1]
#print(candidate_words)
text_a_raw = line.split('\t')[3].split(' ') # text_a untokenized
masked_id = int(line.split('\t')[2])
masked_word = text_a_raw[masked_id] # get the target word
#text_a_raw.insert(masked_id + 1,'and')
#text_a_raw.insert(masked_id + 2, 'MASK')
text_a_raw = ' '.join(text_a_raw)
#pat_letter = re.compile(r'[^a-zA-Z \']+')
#text_a_raw = pat_letter.sub(' ', text_a_raw).strip().lower()
pat_is = re.compile("(it|he|she|that|this|there|here)(\'s)", re.I)
# to find the 's following the letters
pat_s = re.compile("(?<=[a-zA-Z])\'s")
# to find the ' following the words ending by s
pat_s2 = re.compile("(?<=s)\'s?")
# to find the abbreviation of not
pat_not = re.compile("(?<=[a-zA-Z])n\'t")
# to find the abbreviation of would
pat_would = re.compile("(?<=[a-zA-Z])\'d")
# to find the abbreviation of will
pat_will = re.compile("(?<=[a-zA-Z])\'ll")
# to find the abbreviation of am
pat_am = re.compile("(?<=[I|i])" "\'m")
# to find the abbreviation of are
pat_are = re.compile("(?<=[a-zA-Z])\'re")
# to find the abbreviation of have
pat_ve = re.compile("(?<=[a-zA-Z])\'ve")
new_text = pat_is.sub(r"\1 is", text_a_raw)
new_text = pat_s.sub("", new_text)
new_text = pat_s2.sub("", new_text)
new_text = pat_not.sub(" not", new_text)
new_text = pat_would.sub(" would", new_text)
new_text = pat_will.sub(" will", new_text)
new_text = pat_am.sub(" am", new_text)
new_text = pat_are.sub(" are", new_text)
new_text = pat_ve.sub(" have", new_text)
text_a_raw = new_text.replace('\'', ' ')
text_a_raw = text_a_raw.split(' ')
while '' in text_a_raw:
text_a_raw.remove('')
masked_id = text_a_raw.index(masked_word)
masked_word_tokenized = tokenizer.tokenize(masked_word)
text_a_tokenized = tokenizer.tokenize(' '.join(text_a_raw))
target_sentence_length = len(text_a_tokenized)
indexs = [i for (i,wordpiece) in enumerate(text_a_tokenized) if wordpiece == masked_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < masked_id:
continue
for i in range(len(masked_word_tokenized)):
if masked_word_tokenized[i] != text_a_tokenized[index_now + i]:
flag = False
if flag == True:
target_start_id = index_now
target_end_id = index_now + len(masked_word_tokenized) - 1
break
instances.append('\t'.join([full_target_key, index, ' '.join(text_a_tokenized), str(target_start_id), str(target_end_id)]))
selected_indice = []
selected_weight = []
for i,indice in enumerate(context_indice):
#print(indice)
if int(indice) - 1 >= target_start_id and int(indice) -1 <= target_end_id:
continue
if int(indice) - 1 >= len(text_a_tokenized):
continue
line = copy.deepcopy(text_a_tokenized)
if int(indice) != 0:
#print(line)
line[int(indice) - 1] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(line), str(1)]))
selected_indice.append(indice)
selected_weight.append(float(context_weight[i]))
selected_weight_sum = np.sum(selected_weight)
weights = [weight / selected_weight_sum for weight in selected_weight]
text_target_masked = copy.deepcopy(text_a_tokenized)
text_target_masked[target_start_id] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_target_masked), str(1)]))
candidates = []
for candidate_word in candidate_words[:-1]:
if len(candidate_word.split(' ')) != 1 or len(candidate_word.split('-')) != 1:
#print("candidate word %s filtered" %(candidate_word))
continue
line_replaced = copy.deepcopy(text_a_raw)
line_replaced[masked_id] = candidate_word
line_replaced_tokenized = tokenizer.tokenize(' '.join(line_replaced))
candidate_sentence_length = len(line_replaced_tokenized)
offset = candidate_sentence_length - target_sentence_length
candidates.append(candidate_word)
#print(candidate_word)
candidate_word_tokenized = tokenizer.tokenize(candidate_word)
#print(candidate_word_tokenized)
indexs = [i for i,word in enumerate(line_replaced_tokenized) if word == candidate_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < target_start_id:
continue
for i in range(len(candidate_word_tokenized)):
if candidate_word_tokenized[i] != line_replaced_tokenized[index_now + i]:
flag = False
if flag == True:
candidate_start_id = index_now
break
candidate_end_id = candidate_start_id + len(candidate_word_tokenized) - 1
instances.append('\t'.join([full_target_key, index, ' '.join(line_replaced_tokenized), str(candidate_start_id), str(candidate_end_id)]))
for indice in context_indice:
if int(indice) - 1 >= target_start_id and int(indice) -1 <= target_end_id:
continue
if int(indice) - 1 >= len(text_a_tokenized):
continue
assert(indice in selected_indice)
line = copy.deepcopy(line_replaced_tokenized)
if int(indice) -1 > target_start_id:
indice_p = int(indice) - 1 - target_end_id + candidate_end_id
else:
indice_p = int(indice) - 1
if indice_p >= 0:
line[indice_p] = '[MASK]'
instances.append('\t'.join([full_target_key, index, ' '.join(line), str(1)]))
return instances, candidates, selected_indice, weights
def proposal2bert_service(line, candidate_words, tokenizer):
instances = [] # returned input lines for bert
full_target_key = line.split('\t')[0]
target = '.'.join(full_target_key.split('.')[:2])
index = line.split('\t')[1]
#print(candidate_words)
text_a_raw = line.split('\t')[3].split(' ') # text_a untokenized
masked_id = int(line.split('\t')[2])
masked_word = text_a_raw[masked_id] # get the target word
#text_a_raw.insert(masked_id + 1,'and')
#text_a_raw.insert(masked_id + 2, 'MASK')
text_a_raw = ' '.join(text_a_raw)
#pat_letter = re.compile(r'[^a-zA-Z \']+')
#text_a_raw = pat_letter.sub(' ', text_a_raw).strip().lower()
pat_is = re.compile("(it|he|she|that|this|there|here)(\'s)", re.I)
# to find the 's following the letters
pat_s = re.compile("(?<=[a-zA-Z])\'s")
# to find the ' following the words ending by s
pat_s2 = re.compile("(?<=s)\'s?")
# to find the abbreviation of not
pat_not = re.compile("(?<=[a-zA-Z])n\'t")
# to find the abbreviation of would
pat_would = re.compile("(?<=[a-zA-Z])\'d")
# to find the abbreviation of will
pat_will = re.compile("(?<=[a-zA-Z])\'ll")
# to find the abbreviation of am
pat_am = re.compile("(?<=[I|i])" "\'m")
# to find the abbreviation of are
pat_are = re.compile("(?<=[a-zA-Z])\'re")
# to find the abbreviation of have
pat_ve = re.compile("(?<=[a-zA-Z])\'ve")
new_text = pat_is.sub(r"\1 is", text_a_raw)
new_text = pat_s.sub("", new_text)
new_text = pat_s2.sub("", new_text)
new_text = pat_not.sub(" not", new_text)
new_text = pat_would.sub(" would", new_text)
new_text = pat_will.sub(" will", new_text)
new_text = pat_am.sub(" am", new_text)
new_text = pat_are.sub(" are", new_text)
new_text = pat_ve.sub(" have", new_text)
text_a_raw = new_text.replace('\'', ' ')
text_a_raw = text_a_raw.split(' ')
while '' in text_a_raw:
text_a_raw.remove('')
masked_id = text_a_raw.index(masked_word)
masked_word_tokenized = tokenizer.tokenize(masked_word)
text_a_tokenized = tokenizer.tokenize(' '.join(text_a_raw))
indexs = [i for (i,wordpiece) in enumerate(text_a_tokenized) if wordpiece == masked_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < masked_id:
continue
for i in range(len(masked_word_tokenized)):
if masked_word_tokenized[i] != text_a_tokenized[index_now + i]:
flag = False
if flag == True:
target_start_id = index_now
target_end_id = index_now + len(masked_word_tokenized) - 1
break
instances.append('\t'.join([full_target_key, index, ' '.join(text_a_tokenized), str(target_start_id), str(target_end_id)]))
text_target_masked = copy.deepcopy(text_a_tokenized)
text_target_masked[target_start_id] = "[MASK]"
instances.append('\t'.join([full_target_key, index, ' '.join(text_target_masked), str(1)]))
candidates = []
for candidate_word in candidate_words[:-1]:
if len(candidate_word.split(' ')) != 1 or len(candidate_word.split('-')) != 1:
#print("candidate word %s filtered" %(candidate_word))
continue
line_replaced = copy.deepcopy(text_a_raw)
line_replaced[masked_id] = candidate_word
line_replaced_tokenized = tokenizer.tokenize(' '.join(line_replaced))
candidates.append(candidate_word)
candidate_word_tokenized = tokenizer.tokenize(candidate_word)
#print(candidate_word)
indexs = [i for i,word in enumerate(line_replaced_tokenized) if word == candidate_word_tokenized[0]]
for index_now in indexs:
flag = True
if index_now < target_start_id:
continue
for i in range(len(candidate_word_tokenized)):
if candidate_word_tokenized[i] != line_replaced_tokenized[index_now + i]:
flag = False
if flag == True:
candidate_start_id = index_now
break
candidate_end_id = candidate_start_id + len(candidate_word_tokenized) - 1
instances.append('\t'.join([full_target_key, index, ' '.join(line_replaced_tokenized), str(candidate_start_id), str(candidate_end_id)]))
return instances, candidates
def cosine_similarity(vector_a, vector_b):
nominator = np.dot(vector_a, vector_b)
denominator = np.linalg.norm(vector_a) * np.linalg.norm(vector_b)
return np.divide(nominator,denominator)
def target_sim(target_embedding, candidate_embedding, sim_methode='cosine_similarity'):
if sim_methode == 'cosine_similarity':
return cosine_similarity(target_embedding, candidate_embedding)
elif sim_methode == 'dot_product':
return np.dot(target_embedding, candidate_embedding)
elif sim_methode == 'euclidien distance':
return np.linalg.norm(target_embedding - candidate_embedding)
else:
print("sim methode not valid")
return
def context_sim(target_context, candidate_context, weights, context_methode='sim_first', sim_methode='cosine_similarity', rank_methode='balmult'):
#print(target_context.shape)
#print(candidate_context.shape)
assert(target_context.shape == candidate_context.shape)
context_length = target_context.shape[0]
if context_methode == 'average_first':
#print(candidate_context.shape)
weights = np.array(weights)
target_context = np.average(target_context, axis = 0, weights = weights)
candidate_context = np.average(candidate_context, axis = 0, weights = weights)
target_context = np.reshape(target_context,-1)
candidate_context = np.reshape(candidate_context,-1)
#print(target_context.shape)
#print(candidate_context.shape)
if rank_methode == 'balmult' or rank_methode == 'mult':
return target_sim(target_context, candidate_context, sim_methode) ** context_length
elif rank_methode == 'add' or rank_methode == 'baladd':
return target_sim(target_context, candidate_context, sim_methode)
else:
print("rank methode not valid")
return
elif context_methode == 'sim_first':
context_similarity = []
for i in range(context_length):
context_similarity.append(target_sim(target_context[i,:], candidate_context[i,:], sim_methode))
if rank_methode == 'balmult' or rank_methode == 'mult':
return np.prod(context_similarity)
elif rank_methode == 'add' or rank_methode == 'baladd':
weights = np.array(weights)
context_similarity = np.array(context_similarity)
assert(weights.shape == context_similarity.shape)
return np.dot(context_similarity,weights)
else:
print("rank methode not valid")
return
else:
print("context methode not valid")
return
def score(target_candidate_similarity, context_context_similarity, context_length, rank_methode='balmult'):
if rank_methode == 'balmult':
return pow((target_candidate_similarity ** context_length) * context_context_similarity, 1/(context_length * 2))
elif rank_methode == 'mult':
return pow(target_candidate_similarity * context_context_similarity, 1/(context_length + 1))
elif rank_methode == 'baladd':
return (target_candidate_similarity * context_length + context_context_similarity) / (2 * context_length)
elif rank_methode == 'add':
return (target_candidate_similarity + 2 * context_context_similarity) / 3
elif rank_methode == 'target_only':
return target_candidate_similarity
else:
print("rank methode not valid")
return
def rank_one_instance(instances, candidates, lemmatizer, bow_size=5, sim_methode='cosine_similarity', context_methode='average_first', rank_methode='balmult'):
#print(instances)
to_embedding_list = [instance.split('\t')[2].split(' ') for instance in instances]
#print(to_embedding_list)
embedded = bc.encode(to_embedding_list, is_tokenized=True)
target_line = instances[0]
target = target_line.split('\t')[0]
target_word = target.split('.')[0]
target_pos = target.split('.')[-1]