-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtext_augment.py
2654 lines (2504 loc) · 126 KB
/
text_augment.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
"""
Copyright, 2021-2022 Ontocord, LLC, 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 re
import fsspec
import copy
from collections import Counter
from datasets import load_dataset
from transformers import AutoConfig, AutoModel, AutoTokenizer, RobertaForTokenClassification, M2M100ForConditionalGeneration, M2M100Tokenizer, pipelines
import spacy
from tqdm import tqdm
import difflib
from transformers import pipeline, MarianMTModel, XLMRobertaForTokenClassification, BertForTokenClassification, ElectraForTokenClassification
import random
from sentence_transformers import SentenceTransformer
from torch.nn.functional import cosine_similarity
import langid
import json
import os
import time
import gzip
from functools import partial
import argparse
import re, regex
import itertools
import torch
from torch import multiprocessing
import sys
from huggingface_hub import hf_hub_url, cached_download
import argparse
from torch import multiprocessing
import time
from functools import partial
from faker import Faker
from faker.providers import person, company, geo, address, ssn, internet
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(
format='%(asctime)s : %(processName)s : %(levelname)s : %(message)s',
level=logging.INFO)
try:
import neuralcoref
except:
neuralcoref = None
pass
import sys
try:
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
except:
pass
from marian_mt import marian_mt
from kenlm_manager import *
from fake_names import *
from faker_manager import *
from ner_manager import *
from banned_words import *
from char_manager import *
import regex_manager
from cjk import cjk_detect
from dictionary_manager import detect_in_dictionary
try:
if not stopwords:
from stopwords import stopwords
except:
try:
from stopwords import stopwords
except:
stopwords = {}
try:
if not english_flagged_words:
from flagged_words import *
except:
try:
from flagged_words import *
except:
english_flagged_words = {}
flagged_words = {}
import qg_pipeline
def try_decode(text):
try:
return text.decode().strip()
except:
return None
trannum = str.maketrans("0123456789", "1111111111")
m2m100_lang = {
('en', 'yo'): "Davlan/m2m100_418M-eng-yor-mt",
('yo', 'en'): "Davlan/m2m100_418M-yor-eng-mt",
('en', 'zu'): "masakhane/m2m100_418M-en-zu-mt",
('zu', 'en'): "masakhane/m2m100_418M-zu-en-mt",
('*', '*') : "facebook/m2m100_418M"
}
class TextAugmentDeviceModel:
available_devices = [-1] if torch.cuda.device_count() == 0 else [torch.cuda.device(i).idx for i in range(torch.cuda.device_count())]
available_device_models = [None] if torch.cuda.device_count() == 0 else [None]* torch.cuda.device_count()
def __init__(self, device_id=None, device=None):
if device_id is not None:
self.device_id = int(device_id)
self.device = "cpu" if device_id < 0 else "cuda:"+str(device_id)
elif device is not None:
self.device=device
self.device_id = -1 if device == "cpu" else int(device.split(":")[-1])
else:
self.device = None
self.device_id = None
self.labse = None
self.qg = None
self.translation_pipelines = None
self.ner_model_name2pipelines = None
self.marian_mt = None
@staticmethod
def initializer_all(src_langs=["en"], target_langs=["en"], aug_langs=["en"]):
for available_device_model, device_id in zip(TextAugmentDeviceModel.available_device_models, TextAugmentDeviceModel.available_devices):
if available_device_model is None:
available_device_model = TextAugmentDeviceModel(device_id=device_id)
available_device_model.initializer(src_langs=src_langs, target_langs=target_langs, aug_langs=aug_langs,device_id=device_id)
TextAugmentDeviceModel.available_device_models[max(0,available_device_model.device_id)] = available_device_model
def initializer(self, device_id=None, device=None, src_langs=["en"], target_langs=["en"], aug_langs=["en"]):
if device is None and device_id is None:
device = self.device
if device_id is not None:
self.device_id = int(device_id)
self.device = "cpu" if device_id < 0 else "cuda:"+str(device_id)
elif device is not None:
self.device=device
self.device_id = -1 if device == "cpu" else int(device.split(":")[-1])
else:
self.device = None
self.device_id = None
if not hasattr(self, 'qg') or self.qg is None: self.qg = qg_pipeline.pipeline("multitask-qa-qg", device=self.device) # TODO make sure it's running in half mode
if not hasattr(self, 'labse') or self.labse is None:
try:
self.labse = SentenceTransformer(os.path.expanduser ('~')+"/.cache/"+"sentence-transformers/LaBSE").half().eval().to(self.device)
except:
self.labse = SentenceTransformer("sentence-transformers/LaBSE").half().eval().to(self.device)
if not hasattr(self, 'ner_model_name2pipelines') or self.ner_model_name2pipelines is None: self.ner_model_name2pipelines = {}
if not hasattr(self, 'translation_pipelines') or self.translation_pipelines is None:
self.translation_pipelines = {}
self.translation_pipelines["facebook/m2m100_418M"] = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M").eval().half().to(self.device)
seen = {}
pairs = list(set([(src_lang, target_lang) for src_lang, target_lang in zip(src_langs, target_langs+aug_langs)] + [(target_lang, src_lang) for src_lang,target_lang in zip(src_langs, target_langs+aug_langs)]))
for pair in pairs:
if pair not in seen:
model_name = marian_mt.get(pair)
seen[pair] = 1
if model_name is not None and model_name not in TextAugment.translation_pipelines:
tokenizer = AutoTokenizer.from_pretrained(model_name, model_max_length=512)
if self.device == "cpu":
model = MarianMTModel.from_pretrained(model_name).eval()
model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
else:
model = MarianMTModel.from_pretrained(model_name).eval().half().to(self.device)
if self.device == 'cpu':
mt_pipeline = pipeline("translation", model=model, tokenizer=tokenizer)
else:
mt_pipeline = pipeline("translation", model=model, tokenizer=tokenizer, device=self.device_id)
self.translation_pipelines[model_name] = mt_pipeline
for target_lang in list(set(target_langs + src_langs + aug_langs)):
for model_name, model_cls, hf_ner_weight2 in hf_ner_model_map.get(target_lang, []):
if model_name not in self.ner_model_name2pipelines:
try:
model = model_cls.from_pretrained(model_name).half().eval().to(self.device)
tokenizer = AutoTokenizer.from_pretrained(model_name, model_max_length=512,truncation=True)
if self.device == "cpu":
model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
ner_pipeline = pipeline("ner", model=model, tokenizer=tokenizer)
else:
ner_pipeline = pipeline("ner", model=model, tokenizer=tokenizer, device=self.device_id)
self.ner_model_name2pipelines[model_name] = ner_pipeline
logger.info("problems loading model and tokenizer for pipeline. attempting to load without passing in model")
except:
tokenizer = AutoTokenizer.from_pretrained(model_name, model_max_length=512,truncation=True)
if self.device == "cpu":
model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
ner_pipeline = pipeline("ner", model=model, tokenizer=(tokenizer, {"use_fast": True},), )
else:
ner_pipeline = pipeline("ner", model=model_name, tokenizer=(tokenizer, {"use_fast": True},), device=self.device_id)
self.ner_model_name2pipelines[model_name] = ner_pipeline
class TextAugment:
device_id = None
device = None
ner_model_name2pipelines = {}
translation_pipelines = {}
qg = None
labse = None
m2m_model_name = ""
m2m_tokenizer = None
en_spacy_nlp = None
faker_en_list = None
max_stoword_len_zh = max([0]+[len(a) for a in stopwords.get('zh', [])])
max_stoword_len_ko = max([0]+[len(a) for a in stopwords.get('ko', [])])
max_stoword_len_ja = max([0]+[len(a) for a in stopwords.get('ja', [])])
stopwords_en = set(stopwords.get('en',[]))
cache_dir = None
def __init__(self, device=None, single_process=1, available_device_model=None, labse=None, translation_pipelines=None, ner_model_name2pipelines=None, en_spacy_nlp=None, faker_en_list=None, qg=None, cache_dir=None):
if cache_dir is None:
cache_dir = os.path.expanduser ('~')+"/.cache"
if TextAugment.cache_dir is None:
TextAugment.cache_dir = cache_dir
if device is not None:
TextAugment.device = device
if device == "cpu":
TextAugment.device_id = -1
else:
TextAugment.device_id = int(device.split(":")[-1])
else:
if TextAugmentDeviceModel.available_devices:
TextAugment.device_id = -1 if TextAugmentDeviceModel.available_devices[0] == -1 else random.choice(TextAugmentDeviceModel.available_devices)
TextAugment.device = "cpu" if TextAugment.device_id == -1 else "cuda:"+str(TextAugment.device_id)
else:
TextAugment.device_id = -1
TextAugment.device = "cpu"
logger.info (('running on ', TextAugment.device))
if single_process:
self.initializer(available_device_model=available_device_model, device=TextAugment.device, labse=labse, translation_pipelines=translation_pipelines, ner_model_name2pipelines=ner_model_name2pipelines, en_spacy_nlp=en_spacy_nlp, faker_en_list=faker_en_list, qg=qg, cache_dir=cache_dir)
def initializer(self, device_id_by_proess_id=True, all_available_device_model=None, available_device_model=None, device=None, labse=None, translation_pipelines=None, ner_model_name2pipelines=None, en_spacy_nlp=None, faker_en_list=None, qg=None, cache_dir=None):
if all_available_device_model is not None:
TextAugmentDeviceModel.available_device_models = all_available_device_model
TextAugmentDeviceModel.available_devices = [d.device_id for d in all_available_device_model]
if cache_dir is None:
cache_dir = os.path.expanduser ('~')+"/.cache"
if TextAugment.cache_dir is None:
TextAugment.cache_dir = cache_dir
if device is not None:
TextAugment.device = device
if device == "cpu":
TextAugment.device_id = -1
else:
TextAugment.device_id = int(device.split(":")[-1])
else:
if TextAugmentDeviceModel.available_devices:
TextAugment.device_id = -1 if TextAugmentDeviceModel.available_devices[0] == -1 else random.choice(TextAugmentDeviceModel.available_devices)
TextAugment.device = "cpu" if TextAugment.device_id == -1 else "cuda:"+str(TextAugment.device_id)
else:
TextAugment.device_id = -1
TextAugment.device = "cpu"
device = TextAugment.device
if available_device_model is not None:
TextAugmentDeviceModel.available_device_models [max(0,available_device_model.device_id)] = available_device_model
device_id = available_device_model.device_id
TextAugment.device = device = available_device_model.device
labse = available_device_model.labse
qg = available_device_model.qg
translation_pipelines = available_device_model.translation_pipelines
ner_model_name2pipelines = available_device_model.ner_model_name2pipelines
else:
if device is None:
if TextAugmentDeviceModel.available_devices and TextAugmentDeviceModel.available_devices[0].device_id >= 0:
if device_id_by_proess_id:
process_id = torch.multiprocessing.current_process().name.split("-")[-1]
try:
process_id = int(process_id)
except:
process_id = 0
device_id = process_id % len(TextAugmentDeviceModel.available_devices)
else:
device_id = random.choice(TextAugmentDeviceModel.available_devices)
TextAugment.device_id = device_id
device = TextAugment.device = "cuda:"+str(TextAugment.device_id)
else:
device_id = TextAugment.device_id = -1
device = TextAugment.device = "cpu"
else:
device_id = -1 if device == "cpu" else int(device.split(":")[-1])
if True:
#print (device_id)
available_device_model = TextAugmentDeviceModel.available_device_models[max(0,device_id)]
if available_device_model is None:
TextAugmentDeviceModel.available_device_models[max(0,device_id)] = available_device_model = TextAugmentDeviceModel(device=TextAugment.device)
labse = available_device_model.labse
qg = available_device_model.qg
translation_pipelines = available_device_model.translation_pipelines
ner_model_name2pipelines = available_device_model.ner_model_name2pipelines
if labse is not None: TextAugment.labse = labse
if translation_pipelines is not None: TextAugment.translation_pipelines = translation_pipelines
if ner_model_name2pipelines is not None: TextAugment.ner_model_name2pipelines = ner_model_name2pipelines
if qg is not None: TextAugment.qg = qg
if en_spacy_nlp is not None: TextAugment.en_spacy_nlp = en_spacy_nlp
if faker_en_list is not None: TextAugment.faker_en_list = faker_en_list
if TextAugment.en_spacy_nlp is None: TextAugment.en_spacy_nlp = spacy.load('en_core_web_sm')
try:
coref = neuralcoref.NeuralCoref(TextAugment.en_spacy_nlp.vocab)
TextAugment.en_spacy_nlp.add_pipe(coref, name='neuralcoref')
#we could potentially add new items to the vocabulary to improve coref.
except:
logger.info("Neuralcoref not loaded. Using normal spacy")
pass
if TextAugment.faker_en_list is None:
TextAugment.faker_en_list = faker_en_list = [Faker(faker_lang) for faker_lang in faker_map["en"]]
for i, faker_en in enumerate(faker_en_list):
faker_en.add_provider(person)
faker_en.add_provider(ssn)
faker_en.add_provider(address)
faker_en.add_provider(geo)
faker_en.add_provider(internet)
faker_en.add_provider(company)
TextAugment.faker_en_list[i] = FakerExtensions(lang="en", faker=faker_en)
#print ("finished load")
#TODO - create an abstraction for faker, so when faker returns None, we fallback to faker_en
@staticmethod
def serialize_ner_items(docs, ner_keys=None, outfile=""):
#print ("serialize_ner_items")
# serialize ner keys
if ner_keys:
ner_keys = [k + '_ner' for k in ner_keys if '_ner' not in k]
else:
ner_keys = []
if type(docs) is dict:
serialize_docs = list(docs.values())
else:
serialize_docs = docs
serialize_docs = copy.deepcopy(serialize_docs)
serialize_docs.sort(key=lambda a: int(a.get('id', -1)))
for doc in serialize_docs:
for ner_key in ner_keys + ([] if ner_keys else [key for key in doc if '_ner' in key]):
ner_items = doc[ner_key]
serialize_items = []
if type(ner_items) is dict:
for (text, start, end), ner_value in ner_items.items():
ner_value = list(ner_value.items())
ner_dict = [text, start, end, ner_value]
serialize_items.append(ner_dict)
doc[ner_key] = serialize_items
if outfile:
with open(outfile, 'w', encoding='utf-8') as file:
for doc in serialize_docs:
doc = json.dumps(doc)
file.write(f'{doc}\n')
return serialize_docs
@staticmethod
def deserialize_ner_items(docs=None, infile="", return_dict=False):
def load_py_from_str(s, default=None):
if not s.strip(): return default
dat = None
try:
dat = json.loads(s)
except:
pass
if dat is not None: return dat
ret = {'__ret': None}
#print (s)
exec("__ret= "+s, ret)
return ret['__ret']
def deserialize_doc(doc):
for ner_key in [key for key in doc if key.endswith('_ner')]:
ner_items = doc[ner_key]
if ner_items and type(ner_items) is list:
deserialize_items = {}
for item in ner_items:
mention = (item[0], item[1], item[2])
aHash = dict([(tuple(a[0]) if type(a[0]) is list else a[0], float(a[1])) for a in item[3]])
deserialize_items[mention] = aHash
doc[ner_key] = deserialize_items
return doc
#print ("deserialize_ner_items")
if infile:
logger.info(infile)
docs= [load_py_from_str(s, {}) for s in open(infile, "rb").read().decode().split("\n")]
#print (docs)
elif docs:
if type(docs) is dict:
docs = copy.copy(docs.values())
return_dict = True
else:
docs = copy.copy(docs)
if return_dict:
return dict([(int(doc.get('id', idx)), deserialize_doc(doc)) for idx, doc in enumerate(docs)])
else:
return [deserialize_doc(doc) for doc in docs]
return docs
#WIP - we can use this question generation method to extract people, place and thing, and potentially age/date AND to get a relationship between a person and a PII info
def generate_questions_answers_rel(self, docs, chunks, src_lang, default_answers=[], text_key=None, ner_key=None, rel_key=None, signal='qg_rel', weight=1.0):
answers = {}
if ner_key is None:
ner_key = f'{src_lang}_signal_ner'
if text_key is None:
text_key = f'{src_lang}_text'
if rel_key is None:
rel_key = f'{src_lang}_rel'
i= 0
allqa = []
for chunk in chunks:
text = chunk[text_key]
_id = chunk['id']
ner = docs[_id][ner_key] = docs[_id].get(ner_key,{})
rel = docs[_id][rel_key] = docs[_id].get(rel_key,{})
default_answers = list(set([a[0] for a in ner.keys()]+default_answers))
answers1={}
#ti = time.time()
text = text.replace("\n", " ").replace(",", " , ").replace(" ", " ").strip().replace(" , ", ", ")
aHash = self.qg(text , default_answers=default_answers)[0]
allqa.append(aHash)
#default_answers = list(set([a['answer'] for a in aHash]+default_answers))
#print (aHash)
for aHash1 in aHash:
i+=1
quest=aHash1['question'].lower().strip("?").replace("'s", " 's").replace(" ", " ").split()
question=aHash1['question'].lower()
answer=aHash1['answer'].lower()
label=None
#TODO, use spacy_en to get NER and only fall back to "who", "when", "where" to determine ner if we find nothing
if quest[0] == "who" and aHash1['answer'][-1] =='s':
label="ORG"
elif quest[0] == "who":
label="PERSON"
if "'s" in quest:
for j in range(len(quest)):
if j > 0 and quest[j-1]=="'s":
label = "MISC"
break
elif quest[0] == "where":
label="LOC"
elif quest[0] == "when":
label = "DATE"
if "born" in quest or "died" in quest or "birthday" in quest or "birthdate" in quest:
label="AGE"
elif quest[0] == "why":
label="EVENT"
elif quest[0] == "how" and quest[1] in ("much", "many"):
label="ORDINAL"
elif quest[0] == "how":
label="EVENT"
elif quest[0] in ("which", "what") and quest[1] not in self.stopwords_en:
label="MISC"
else:
label = None
if label:
mentions = [mention for mention in ner if (mention[0] == aHash1['answer'] or mention[0].startswith(aHash1['answer']) or aHash1['answer'].startswith(mention[0]))]
if mentions:
for mention in mentions:
ner[mention][(label, signal)] = ner[mention].get((label, signal), 0) + weight
else:
pos = 0
while aHash1['answer'] in text[pos:]:
i = text[pos:].index(aHash1['answer'])
start = pos + i
end = start + len(aHash1['answer'])
pos = end + 1
ner[mention][(label, signal)] = ner[mention].get((label, signal), 0) + weight
for mention in ner:
ent = mention[0].lower()
if ent in question:
for mention0 in mentions:
rel[question] = rel.get(question, []) + [(mention0, mention)]
return docs
@staticmethod
def get_aligned_text(sent1, sent2, src_lang, prefer_split_char="]"):
"""
Given two sentences, find blocks of text that match and that don't match.
return the blocks, and a matching score.
Used to extract NER from original language sentence.
"""
#print ("get_aligned_text")
#will the below have a side-effect?
sent1 = sent1.replace("。", ".").replace("،", ",").replace("、", ",").replace("`", "'").replace("“", "\"").replace("”", "\"").replace("《", "\"").replace("》", "\"").replace("«", "\"").replace("»", "\"")
sent2 = sent2.replace("。", ".").replace("،", ",").replace("、", ",").replace("`", "'").replace("“", "\"").replace("”", "\"").replace("《", "\"").replace("》", "\"").replace("«", "\"").replace("»", "\"")
if True: # src_lang in ("ja", "ko", "zh"):
# splitting on spaces doesn't always work because some languages aren't space separated
sep = ""
else:
sep = " "
sent1 = sent1.split()
sent2 = sent2.split()
aMatch = difflib.SequenceMatcher(None,sent1, sent2)
score = aMatch.ratio()
blocks = aMatch.get_matching_blocks()
blocks2 = []
prevEndA = 0
prevEndB = 0
matchLen = 0
nonMatchLen = 0
#print (blocks)
for blockI in range(len(blocks)):
if blockI > 0 or (blockI==0 and (blocks[blockI][0] != 0 or blocks[blockI][1] != 0)):
blocks3 = []
if True:
a, b = sep.join(sent1[prevEndA:blocks[blockI][0]]), sep.join(sent2[prevEndB:blocks[blockI][1]])
if "]" in b:
blocks3 = []
a_arr = a.split(" ") if src_lang not in ("zh", "ja", "ki") else a
len_a_arr = len(a_arr)
b_cnt = b.count(prefer_split_char) + (1 if b.endswith(prefer_split_char) or b.endswith(prefer_split_char+" ") else 0)
a_step = int(len(a)/b_cnt)
#print (len(a), b_cnt)
a_arr2 = []
if a_step <= 0:
a_arr2.extend([a]+['']*len(a))
else:
for rng in range(0, len_a_arr, a_step):
a_arr2.append((" " if src_lang not in ("zh", "ja", "ki") else "").join(a_arr[rng:min(len_a_arr, rng+a_step)]))
for a1, b1 in zip(a_arr2, b.split("]")):
if src_lang not in ("zh", "ja", "ki"):
a1 = a1+" "
b1 = b1+prefer_split_char
blocks3.append([a1, b1, 0])
if blocks3:
blocks2.extend(blocks3)
else:
blocks2.append([sep.join(sent1[prevEndA:blocks[blockI][0]]), sep.join(sent2[prevEndB:blocks[blockI][1]]), 0])
nonMatchLen += max(blocks[blockI][0] - prevEndA, blocks[blockI][1] - prevEndB)
if blocks[blockI][2] != 0:
blocks2.append([sep.join(sent1[blocks[blockI][0]:blocks[blockI][0]+blocks[blockI][2]]), sep.join(sent2[blocks[blockI][1]:blocks[blockI][1]+blocks[blockI][2]]), 1])
prevEndA = blocks[blockI][0]+blocks[blockI][2]
prevEndB = blocks[blockI][1]+blocks[blockI][2]
matchLen += blocks[blockI][2]
score = float(matchLen+1)/float(nonMatchLen+1)
return (blocks2, score+score)
def do_translations(self, texts, src_lang='en', target_lang='hi', batch_size=16, do_marian_mt=False):
#print ("do_translations")
#print ([len(t.split()) for t in texts])
if not do_marian_mt:
m2m_model_name = m2m100_lang.get((src_lang, target_lang), m2m100_lang[('*', '*')])
if m2m_model_name != self.m2m_model_name or self.m2m_tokenizer is None:
self.m2m_tokenizer = M2M100Tokenizer.from_pretrained(m2m_model_name, model_max_length=512)
try:
self.m2m_tokenizer.src_lang = src_lang
target_lang_bos_token = self.m2m_tokenizer.get_lang_id(target_lang)
except:
do_marian_mt = True
pass
if not do_marian_mt:
if m2m_model_name != self.m2m_model_name or self.m2m_model is None:
if m2m_model_name in TextAugment.translation_pipelines:
self.m2m_model = TextAugment.translation_pipelines[m2m_model_name]
else:
if self.device == "cpu":
TextAugment.translation_pipelines[m2m_model_name] = self.m2m_model = M2M100ForConditionalGeneration.from_pretrained(m2m_model_name).eval()
TextAugment.translation_pipelines[m2m_model_name] = self.m2m_model = torch.quantization.quantize_dynamic(self.m2m_model, {torch.nn.Linear}, dtype=torch.qint8)
else:
TextAugment.translation_pipelines[m2m_model_name] = self.m2m_model = M2M100ForConditionalGeneration.from_pretrained(m2m_model_name).eval().half().to(self.device)
self.m2m_model_name = m2m_model_name
translations = []
for src_text_list in self.batch(texts, batch_size):
try:
batch = self.m2m_tokenizer(src_text_list, return_tensors="pt", padding=True, truncation=True, max_length=512).to(self.device)
except:
logger.info ("could not tokenize m2m batch. falling back to marian_mt")
do_marian_mt = True
break
gen = self.m2m_model.generate(**batch, forced_bos_token_id=target_lang_bos_token, no_repeat_ngram_size=4, ) #
outputs = self.m2m_tokenizer.batch_decode(gen, skip_special_tokens=True)
translations.extend(outputs)
if not do_marian_mt:
return translations
translations = []
#marian_mt = self.marian_mt
model_name = marian_mt.get((src_lang, target_lang))
mt_pipeline = None
if model_name is not None and model_name not in TextAugment.translation_pipelines:
tokenizer = AutoTokenizer.from_pretrained(model_name, model_max_length=512,truncation=True)
if self.device == "cpu":
model = MarianMTModel.from_pretrained(model_name).eval()
model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
else:
model = MarianMTModel.from_pretrained(model_name).eval().half().to(self.device)
if self.device == 'cpu':
mt_pipeline = pipeline("translation", model=model, tokenizer=tokenizer)
else:
mt_pipeline = pipeline("translation", model=model, tokenizer=tokenizer, device=self.device_id)
TextAugment.translation_pipelines[model_name] = mt_pipeline
if mt_pipeline is None:
raise RuntimeError("no translation pipeline") # we could do multi-step translation where there are no pairs
mt_pipeline = self.translation_pipelines[model_name]
for src_text_list in self.batch(texts, batch_size):
outputs = [t['translation_text'] for t in mt_pipeline(src_text_list, batch_size=batch_size, truncation=True, max_length=512)]
translations.extend(outputs)
return translations
@staticmethod
def batch(lst, n):
"""Generate batches"""
lst = list(lst)
for i in range(0, len(lst), n):
yield lst[i: i + n]
def apply_regex_ner(self, src_lang, docs, context_window = 20, weight = 1.0, text_key=None, ner_key=None, signal='regex', tag_type={'ID', 'KEY', 'EMAIL', 'USER', 'IP_ADDRESS', 'PHONE', 'LICENSE_PLATE'}):
"""
apply regexes from the rulebase. if there is a context, check if the context is met in the context_window.
"""
#print ("apply_regex_ner")
global regex_rulebase
if ner_key is None:
ner_key = f'{src_lang}_signal_ner'
if text_key is None:
text_key = f'{src_lang}_text'
for doc in docs.values():
ner = doc[ner_key] = doc.get(ner_key, {})
sentence = doc[text_key]
all_ner = regex_manager.detect_ner_with_regex_and_context(sentence, src_lang, context_window=context_window, tag_type=None)
for mention_tag in all_ner:
ent, start, end, tag = mention_tag
key = (ent, start, end)
aHash = ner.get(key, {})
aHash[(tag, signal)] = aHash.get((tag, signal), 0) + weight * (1.0 + len(ent)/100) # extra weight?
ner[key] = aHash
doc[ner_key] = ner
#print (docs)
return docs
def hf_ner(self, hf_pipeline, src_lang, docs, chunks, stopwords=None, weight=1.5, text_key=None, ner_key=None, offset_key=None, signal='hf'):
"""
run the text through a Huggingface ner pipeline.
any tags found by this method will be weighted by the weight param
TODO: use the predicted value of the logits to further weight prediction
NOTE: we don't use results_arr = hf_pipeline([chunk[text_key] for chunk in chunks], grouped_entities=True)
because grouped_entities does not properly group all entities as we do it below.
"""
#print ("hf_ner")
if stopwords is None:
stopwords = set(stopwords.get(src_lang, []))
if offset_key is None:
offset_key = f'{src_lang}_offset'
if ner_key is None:
ner_key = f'{src_lang}_signal_ner'
if text_key is None:
text_key = f'{src_lang}_text'
#print (chunks)
results_arr = hf_pipeline([chunk[text_key] for chunk in chunks], batch_size=len(chunks))
results_arr2 = []
offset = 0
for chunk, results in zip(chunks, results_arr):
text = chunk[text_key]
_id = chunk['id']
ner = docs[_id][ner_key] = docs[_id].get(ner_key,{})
offset = chunk[offset_key]
len_text= len(text)
results = [ner_result for ner_result in results if ner_result['word'] not in ("[UNK]", "<unk>")]
if not results:
results_arr2.append([])
continue
results2 = []
if results[0]['start'] is not None: #TODO, test for the case where all the 'start' are '0'.
results.sort(key=lambda a: a['start'])
else:
results.sort(key=lambda a: a['index'])
i = 0
for ner_result in results:
ner_result['word'] = word = ner_result['word'].rstrip('@@')
ner_result['start'] = text.index(word, i)
i = ner_result['start'] + 1
ner_result['end'] = ner_result['start'] + len(word)
for ner_result in results:
start = ner_result['start']
if start >= len_text: continue
if not cjk_detect(text[ner_result['start']:ner_result['end']]):
if text[start] not in strip_chars:
for j in range(1, start):
if start - j == -1 or text[start-j] in strip_chars:
start = max(start -j, 0)
break
end = ner_result['end']
if end < len_text and text[end] != ' ':
end += len(text[end:].split(' ', 1)[0])
else:
start = ner_result['start']
end = ner_result['end']
while text[start] in strip_chars and start < len_text:
start += 1
if start >= end: break
if start < len_text and start < end:
end = start + len(text[start:end].strip(strip_chars))
ner_result['word'] = text[start:end]
ner_result['start'] = start+offset
ner_result['end'] = end+offset
if results2 and results2[-1]['end'] > ner_result['start']:
continue
if start < len_text and start < end:
results2.append(ner_result)
results_arr2.append(results2)
results_arr = results_arr2
for chunk, results in zip(chunks, results_arr):
_id = chunk['id']
ner = docs[_id][ner_key]
text = docs[_id][text_key]
len_text = len(text)
results = [ner_result for ner_result in results if ner_result['word'] not in ("[UNK]", "<unk>")]
if not results: continue
prev_word = [0,0]
prev_label = None
prev_word2 = ""
for ner_result in results:
start = ner_result['start']
if start is None:
prev_word2 = ""
continue
end = ner_result['end']
if text[start:end] != ner_result['word']:
logger.info ('offset mismatch', text[start:end], ner_result['word'])
if "-" in ner_result['entity']:
_, label = ner_result['entity'].split('-')
else:
label = ner_result['entity']
label = label.upper()
if label in ('ADDRESS', 'STREET_ADDRESS'): label = 'ADDRESS'
elif label in ('PUBLIC_FIGURE',): label = 'PUBLIC_FIGURE'
elif label in ('NAME', 'PER', 'PERSON'): label = 'PERSON'
elif label in ('LOCATION', 'LOC', 'GPE'): label = 'LOC'
elif label in ('ORGANIZATION', 'ORG'): label = 'ORG'
elif label in ('AGE',): label = 'AGE'
elif label in ('NORP',): label = 'NORP'
elif label in ('BIO', 'SYMPTOM_AND_DISEASE', 'DISEASE' ): label = 'DISEASE'
elif label in ('PATIENT_ID', 'GOVT_ID' ): label = 'ID'
elif label in ('USER_ID', 'ID'): label = 'ID'
elif label in ('MISC', ) and '@' in ner_result['word']: label = 'ID'
else: label = 'MISC'
label = (label, signal)
if prev_label is not None:
if not ner_result['entity'].startswith('B-') and label == prev_label and (prev_word[1] >= start - 5):
prev_word[1] = max(prev_word[1], end)
prev_word2 = prev_word2 + " " + ner_result['word']
else:
if ner_result['entity'].startswith('B-'):
if prev_word[1] > start:
prev_word[1] = start
if prev_word[0] != prev_word[1]:
ner_word = text[prev_word[0]:prev_word[1]]
#if ner_word != prev_word2:
# print (ner_word, '**', prev_word2)
#ner_word.strip(strip_chars)
mention = (ner_word, prev_word[0], prev_word[1])
if ner_word and ner_word.lower() not in stopwords:
aHash = ner.get(mention, {})
aHash[prev_label] = aHash.get(prev_label, 0) + weight * (1.0 + len(ner_word)/100)
ner[mention] = aHash
prev_word = [start, end]
prev_word2 = ner_result['word']
elif prev_label is None:
prev_word = [start, end]
prev_word2 = ner_result['word']
prev_label = label
if prev_label is not None and prev_word[0] != prev_word[1]:
ner_word = text[prev_word[0]:prev_word[1]]
#if ner_word != prev_word2:
# print (ner_word, '**', prev_word2)
mention = (ner_word, prev_word[0], prev_word[1])
if ner_word and ner_word.lower() not in stopwords:
aHash = ner.get(mention, {})
aHash[prev_label] = aHash.get(prev_label, 0) + weight * (1.0 + len(ner_word)/100)
ner[mention] = aHash
def add_chunks_span(self, chunks, new_mention, old_mention, label, coref, chunk2ner, mention2ref, ref2mention):
""" add a span to the chunks sequence and update the various ref and NER hashes """
if old_mention in chunk2ner:
del chunk2ner[old_mention]
if label:
chunk2ner[new_mention] = label
if old_mention in mention2ref:
old_ref = mention2ref[old_mention]
ref2mention[old_ref].remove(old_mention)
if not ref2mention[old_ref]:
del ref2mention[old_ref]
del mention2ref[old_mention]
if new_mention in mention2ref and coref != mention2ref[new_mention]:
old_ref = mention2ref[new_mention]
ref2mention[old_ref].remove(new_mention)
if not ref2mention[old_ref]:
del ref2mention[old_ref]
del mention2ref[new_mention]
if coref:
mention2ref[new_mention] = coref
lst = ref2mention.get(coref, [])
if new_mention not in lst:
ref2mention[coref] = lst + [new_mention]
chunks.append(new_mention)
def del_ner_coref(self, old_mention, chunk2ner, mention2ref, ref2mention):
""" remove an old_mention from the various NER and ref hashes """
if old_mention in chunk2ner:
del chunk2ner[old_mention]
if old_mention in mention2ref:
old_ref = mention2ref[old_mention]
ref2mention[old_ref].remove(old_mention)
if not ref2mention[old_ref]:
del ref2mention[old_ref]
del mention2ref[old_mention]
def spacy_ner_coref(self, docs, nlp, stopwords, spacy_weight, src_lang, extra_weight=1.0, signal='neuralcoref', text_key=None, ner_key=None, connector="_", pronouns=("who", "whom", "whose", "our", "ours", "you", "your", "my", "i", "me", "mine", "he", "she", "his", "her", "him", "hers", "it", "its", "they", "their", "theirs", "them", "we")):
"""
Use the spacy English model to create chunks for English text
and gather NER and coreference information
"""
#print ("spacy_ner_coref")
if not nlp:
return
if stopwords is None:
stopwords = set(stopwords.get(src_lang, []))
offset_key=f'{src_lang}_offset'
if ner_key is None:
ner_key = f'{src_lang}_signal_ner'
if text_key is None:
text_key = f'{src_lang}_text'
mention2ref_key = f'{src_lang}_mention2ref'
ref2mention_key = f'{src_lang}_ref2mention'
mention2pronoun_key = f'{src_lang}_mention2pronoun'
for dat in docs.values():
chunk2ner = {}
ref2mention = {} # dat[ref2mention_key] = dat.get(ref2mention_key,{})
mention2ref = {} # dat[mention2ref_key] = dat.get(mention2ref_key,{})
mention2pronoun = dat[mention2pronoun_key] = dat.get(mention2pronoun_key,{})
ner = dat[ner_key] = dat.get(ner_key,{})
text = dat[text_key]
doc = nlp(text)
entities = list(doc.ents)
# spacy is not as high accuracy as transformers, but we use the spacey neuralcoref model so we can get pronoun coreference groups
# to be able to do proper gender swapping. We can also expand NER tags based on coreferences.
#store away NOUNs for potential label and coref reference
#rule for promoting a noun span into one considered for further processing:
# - length of the number of words > 2 or length of span > 2 and the span is all uppercase (for abbreviations)
# coref candidates:
# - create an abbreviation from noun phrases as a candidate coref.
# - use either the last two words of a span as a candidate coref, or
# - use the abbreviation as a candidate coref
for entity in list(doc.noun_chunks) + list(doc.ents):
chunk2ner[(entity.text, entity.start, entity.end)]= "NOUN"
mention_lower = entity.text.lower()
textArr = mention_lower.split()
if len(textArr) > 2:
short_span = " ".join(textArr[-2:])
ref2mention[short_span] = ref2mention.get(short_span, []) + [(entity.text, entity.start, entity.end)]
non_stopwords = [a for a in textArr if a not in self.stopwords_en]
if len(non_stopwords) > 2:
abrev = "".join([a[0] for a in non_stopwords])
ref2mention[abrev] = ref2mention.get(abrev, []) + [(entity.text, entity.start, entity.end)]
elif (len(entity.text) >=2 and entity.text == entity.text.upper()):
ref2mention[entity.text.lower()] = ref2mention.get(entity.text.lower(), []) + [(entity.text, entity.start, entity.end)]
#store away coref NOUNs for potential label and coref reference
#same rule as above for promoting a noun span into one considered for further processing.
for cl in list(doc._.coref_clusters):
mentions = [(entity.text, entity.start, entity.end) for entity in cl.mentions]
mentions.sort(key=lambda e: len(e[0]), reverse=True)
textArr = mentions[0][0].lower().split()
for key in mentions:
chunk2ner[key]= "NOUN"
for mention in mentions:
mention_lower = mention[0].lower()
textArr = mention_lower.split()
if mention_lower not in self.stopwords_en:
if len(textArr) > 1:
short_span = " ".join(textArr[-2:])
else:
short_span = textArr[0]
ref2mention[short_span] = ref2mention.get(short_span, []) + mentions
non_stopwords = [a for a in textArr if a not in self.stopwords_en]
if len(non_stopwords) > 2:
abrev = "".join([a[0] for a in non_stopwords])
ref2mention[abrev] = ref2mention.get(abrev, []) + mentions
#cleanup the mention2ref, favoring large clusters with coref labels that are longer
seen = {}
corefs = [(a, list(set(b))) for a, b in ref2mention.items()]
corefs.sort(key=lambda a: a[0].count(" ")+len(a[1]), reverse=True)
for coref, spans in corefs:
new_spans = []
spans = list(set(spans))
spans.sort(key=lambda a: a[1]+(1.0/(1.0+a[2]-a[1])))
spans2 = []
for span in spans:
if spans2 and spans2[-1][1] >= span[1]:
continue
spans2.append(span)
for span in spans2:
if span in seen: continue
seen[span] = 1
new_spans.append(span)
del ref2mention[coref]
if new_spans:
new_coref = [s[0] for s in new_spans]
new_coref.sort(key=lambda a: len(a), reverse=True)
ref2mention[new_coref[0].lower()] = list(set(list(ref2mention.get(new_coref[0].lower(), [])) + new_spans))
mention2ref.clear()
for a, b1 in ref2mention.items():
for b in b1:
mention2ref[b] = a
# expand coref information by using the most common coref label in a cluster
if True:
for cl in list(doc._.coref_clusters):
mentions = [(entity.text, entity.start, entity.end) for entity in cl.mentions]
all_mentions = list(set(itertools.chain(*[ref2mention[mention2ref[mention]] for mention in mentions if mention in mention2ref])))
corefs = [mention2ref[mention] for mention in mentions if mention in mention2ref]
if corefs:
coref = Counter(corefs).most_common()[0][0]
else:
coref = cl.main.text.lower()
for mention in all_mentions:
if mention not in chunk2ner:
chunk2ner[mention] = 'NOUN'
old_ref = mention2ref.get(mention)
if old_ref and mention in ref2mention[old_ref]:
ref2mention[old_ref].remove(mention)
if not ref2mention[old_ref]:
del ref2mention[old_ref]
mention2ref[mention] = coref
if mention not in ref2mention.get(coref,[]):
ref2mention[coref] = ref2mention.get(coref,[])
ref2mention[coref].append(mention)
#expand ner labels based on coref matches
for entity in list(doc.ents):
mention = (entity.text, entity.start, entity.end)
chunk2ner[mention]= entity.label_
if mention in mention2ref:
coref = mention2ref[mention]
for mention in ref2mention[coref]:
chunk2ner[mention] = entity.label_
# overwrite all ner labels in the coref cluster to PERSON if there is a person pronoun
if True:
for cl in list(doc._.coref_clusters):
cluster_text_list = set([m.text.lower() if m.text != 'US' else m.text for m in cl.mentions])
if "us" in cluster_text_list or "you" in cluster_text_list or "your" in cluster_text_list or "yours" in cluster_text_list or "we" in cluster_text_list or 'i' in cluster_text_list or 'my' in cluster_text_list or 'mine' in cluster_text_list or 'me' in cluster_text_list or 'he' in cluster_text_list or "she" in cluster_text_list or "his" in cluster_text_list or "her" in cluster_text_list or "him" in cluster_text_list or "hers" in cluster_text_list:
label = "PERSON"
for m in cl.mentions:
chunk2ner[(m.text, m.start, m.end)] = label
# propogate the ner label to everything in the same coref group
for coref, seq in ref2mention.items():
labels = [chunk2ner[mention] for mention in seq if mention in chunk2ner and chunk2ner[mention] != 'NOUN']
if labels:
label = Counter(labels).most_common()[0][0]
for mention in seq:
if mention in chunk2ner and not (label == 'PERSON' or chunk2ner[mention] == 'PUBLIC_FIGURE'): chunk2ner[mention] = label
#sort the chunks into order
chunks = list(chunk2ner.items())
chunks.sort(key=lambda a: a[0][1]+(1.0/(1.0+a[0][2]-a[0][1])))
chunks2 = []
#clear duplicates and subsumed mentions
for mention, label in chunks:
if not chunks2 or (chunks2[-1][2] <= mention[1]):
if not chunks2 or chunks2[-1][2] < mention[1]:
self.add_chunks_span(chunks2, (doc[0 if not chunks2 else chunks2[-1][2]: mention[1]].text, 0 if not chunks2 else chunks2[-1][2], mention[1]), \
None, None, None, chunk2ner, mention2ref, ref2mention)
self.add_chunks_span(chunks2, mention, None, label, mention2ref.get(mention), chunk2ner, mention2ref, ref2mention)
elif chunks2[-1][2] > mention[1] and chunks2[-1][1] <= mention[1]:
if chunk2ner.get(chunks2[-1]) not in (None, '', 'NOUN'):
self.del_ner_coref(mention, chunk2ner, mention2ref, ref2mention)
continue
elif label in (None, '', 'NOUN'):
self.del_ner_coref(mention, chunk2ner, mention2ref, ref2mention)
continue
old_mention = chunks2.pop()
oldSpan = old_mention[0]
oldLabel = chunk2ner.get(old_mention)
oldAnaphore = mention2ref.get(old_mention)
sArr = oldSpan.split(mention[0], 1)
self.del_ner_coref(old_mention, chunk2ner, mention2ref, ref2mention)
s0 = sArr[0].strip()
if s0:
self.add_chunks_span(chunks2, (s0, old_mention[1], mention[1]), None, \
oldLabel if s0 in pronouns or (len(s0) > 1 and s0 not in self.stopwords_en) else None, oldAnaphore if s0 in pronouns or (len(s0) > 1 and s0 not in self.stopwords_en) else None, \
chunk2ner, mention2ref, ref2mention)