-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext_cleaner.py
2178 lines (1910 loc) · 95.3 KB
/
text_cleaner.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
import argparse
import logging
import multiprocessing
import re
from ast import literal_eval
from functools import lru_cache, partial
from pathlib import Path
from typing import Callable
# check if splitted word is one single word in english
import enchant
import ftfy
import inflect
import pandas as pd
# TODO change for termcolor https://github.com/facebookresearch/mmf/blob/7fa7607d299a644158dc3104247e58a30e4b42ab/mmf/utils/_logger.py
from colorama import Back, Fore
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from tqdm import tqdm
from timer import Timer
from utils import parallelize_dataframe, setup_log
_logger = logging.getLogger(__name__)
_grammar = inflect.engine()
LINE_LIMIT = 5000
BG_HIGHLIGHT_COLOR = Back.GREEN
# TODO clean these
# national_natural_science_foundation_china
# advancement_artifcial_intelligence_www_aaai
# copyright_association_advancement_artifcial_intelligence
# association_advancement_artifcial_intelligence_www
# artifcial_intelligence_www_aaai_org
# intelligence_www_aaai_org
# introduction_deep_neural_network_dnn
# international_joint_artificial_intelligence
# introduction_deep_neural_network
# TODO: check for unknown words. if an unknown word is found, check for it as separated words
# if it exists, replace them by the correct words
class TextCleaner():
"""
Useful link to test regex
https://regex101.com/r/NfK7rz/9
https://www.loggly.com/blog/five-invaluable-techniques-to-improve-regex-performance/
"""
# TODO improve regexes, change for special chars like \b
# https://docs.python.org/3/library/re.html#regular-expression-syntax
def __init__(self, debug: bool = False):
super().__init__()
self._logger = logging.getLogger(__name__)
self._composite_words = [
'state-of-the-art[s]?',
]
self._stop_words = set(stopwords.words("english"))
new_stop_words = [
# 'application',
# 'applications',
# 'approach',
# 'approaches',
'also',
'conference',
'however',
'paper',
'propose',
'proposed',
'us',
'use',
'used',
'using',
'vs',
]
for w in new_stop_words:
self._stop_words.add(w)
# new terms not found in dictionary, used during agglutination step
self._new_words = {
'2_bit',
'3_bit',
'4_bit',
'5_bit',
'6_bit',
'7_bit',
'8_bit',
'16_bit',
'accuracy',
'achieve',
'approximability',
'autoregressive',
'avgpooling',
'backpropagation',
'bit_rate',
'bitrate',
'capsnet',
'centroid',
'cnn',
'codec',
'convolutional',
'crowdsourced',
'crowdsourcing',
'datapoint',
'dataset',
'deblurring',
'deepfake',
'demoireing',
'demosaicing',
'denoising',
'dnn',
'downsampling',
'downscaling',
'edit',
'extrinsic',
'gan',
'gnn',
'hyperparameter',
'interdependences',
'interdependency',
'interpretability',
'intrinsic',
'iterative',
'iteratively',
'judgement',
'maxpooling',
'mini-batch',
'minibatch',
'minpooling',
'misclassification',
'moire',
'orthogonalization',
'outperform',
'pre',
'pseudo_label',
'regularizer',
'resampling',
'rescaling',
'rnn',
'scalability',
'scalable',
'sigmoid',
'smartphone',
'state_of_the_art',
'thresholding',
'u_net',
'upsampling',
'upscaling',
'voxel',
}
non_singularizable_words = {
'address',
'analysis',
'basis',
'bias',
'class',
'cross',
'nas', # neural architecture search
'loss',
'stimulus',
'thus',
}
for w in non_singularizable_words:
_grammar.defnoun(w, w)
self._non_aglutinable_words = {
'anew',
'anews',
'calla',
'fora',
'fork',
'iall',
'lets',
'overall',
'pager',
'sand',
'seethe',
'sets',
'shave',
'thank',
'thebe',
'thew',
'thews',
'wheres',
}
# acl conferences regex
prefix_proceedings = '(in )?proceedings of [\d\w\s\(\)#&\-\−\–:,]+'
prefix_paper_type = '( \((short|long) papers\)|(-|−|–|: )(system demonstrations|tutorial abstracts)|(-|:|,) student research workshop)?(\s)*(,)? '
pages_and_location = 'page(s)? [\d]+((-|−|–)[\d]+)?(,)? ([\w]+( [\w]+)*, [\w]+( [\w]+)*(,|.)? )?'
dates_year = '([\d]+ )?[\w]+(,)? [\d]+(st|nd|rd|th)?(( )?(-|−|–)( )?([\w]+ )?[\d]+)?(,)?( [\d]+)?. '
suffix_acl = '[\d\w©]+ (association for computational linguistics|afnlp)'
# item citation regex
item_citation = '(appendix[es]?|equation[s]?|figure[s]?|table[s]?|fig[s]?.|theorem[s]?|(sub)?section[s]?|(sub)?sec[s]?.)'
"""
examples of conferences names that might appear and must be supported
ps: this happens due to the lack of being able to correctly remove all references
in conferences like ijcai 2017
in proceedings of the twenty-first annual acm-siam symposium on discrete algorithms, soda 2010, austin, texas, usa, january 17-19, 2010, pages 1065-1075,
in advances in neural information processing systems 27: annual conference on neural information processing systems 2014, december 8-13 2014, montreal, quebec, canada, pages 190-198, 2014.
journal of machine learning research,
in proceedings of the 27th international conference on machine learning (icml-10), june 21-24, 2010, haifa, israel, pages 911-918, 2010.
in proceedings of the joint european conference on machine learning and knowledge discovery in databases, ecml-pkdd 2011, athens, greece, september 5-9, 2011, pages 349-364, 2011.
university press, 2014.
in 10th international conference on machine learning. learning and applications and workshops, icmla 2011, honolulu, hawaii, usa, december 18-21, 2011. volume 2: special sessions and workshop, pages 84-89, 2011.
in proceedings of the 30th international conference on machine learning, icml 2013, atlanta, ga, usa, 16-21 june 2013, pages 504-512, 2013.
"""
num_or_hyphen = '[\d\-\−\–]+'
num_colon_hyphen_par = '[\d:\-\−\–\(\)]+'
ordinal_num = '[\d]+[\s]*(st|nd|rd|th)'
self._bib_info_to_remove = [
'acm transactions on graphics',
'(aaai|arxiv|cvpr|eccv|iccv|iclr|icml|ijcv|jmlr|neurips|wacv), [\d]+',
'arxiv preprint arxiv:[\d]+.[\d]+(, [\d]+.)?',
f'advances in neural information processing systems {num_colon_hyphen_par}',
'advances in neural information processing systems, (volume|vol- ume) [\d]+, [\d]+',
f'ai magazine, {num_colon_hyphen_par}, [\d]+',
f'artificial (intelligence|in- telligence), {num_colon_hyphen_par}, [\d]+',
f'biometrics, {num_colon_hyphen_par}, [\d]+',
'cambridge university press',
f'computational linguistics, {num_colon_hyphen_par}',
'cognitive science, [\d]+',
'conference on neural information processing systems (neurips|nips) [\w]+ ([\w]+ )*(canada|usa)',
'conference on neural information processing systems \((neurips|nips) [\d]+\), [\w\s]+, ([\w]+, )*[\w]+',
'conference on neural information processing systems \(neurips [\d]+\)',
'copyright [\S]+ [\d]+, association for the advancement of (artificial|artifcial|artifi- cial) ' \
'intelligence \(www.aaai.org\)',
f'experimental economics {num_colon_hyphen_par}',
'ijcv, [\w]+ [\d]+',
'in [\d]+ aaai [\w]+ symposium series, [\d]+',
f'in ({ordinal_num} )?annual meeting of the association for computational linguistics' \
f'( and the ({ordinal_num} )?international joint conference on natural language processing)?',
'(in proc |ieee )?international (conference on|journal of) computer vision (and (pattern|pat- tern) ' \
'recognition|workshops( iccv workshops)?)?',
'in (proceedings of |proc. )?international conference on learning representation(s)?(, [\d]+)?',
'in (proceedings of )?the ieee conference on computer vision and pattern recognition' \
'(, pp. [\d\s\-\−\–]+, [\d]+| \(cvpr\))?',
f'in computer vision and (pattern|pat- tern) recognition, [\d]+. cvpr [\d]+. ' \
f'ieee conference on, {num_or_hyphen}. ieee',
'in (proceedings of )?the ieee conference on computer vision and (pattern|pat- tern) recognition',
f'in proceedings of the {ordinal_num} international conference on machine learning \(icml-[\d]+\)',
f'in proceedings of the {ordinal_num} international conference on machine learning' \
f'[\s\-\−\–]volume [\d]+, pp. [\s\d\-\−\–]+. jmlr. org, [\d]+',
'in computer vision and (pattern|pat- tern) recognition \(cvpr\)',
'in computer vision and (pattern|pat- tern) recognition cvpr',
f'in advances in neural information processing systems(, pp. [\d\s\-\−\–]+, [\d]+|, {num_or_hyphen})?',
'in the ieee international conference on computer vision \(iccv\)',
'(in the [\d]+ )?conference of the north american chapter of the association for computational linguistics',
f'in www, {num_or_hyphen}. acm',
f'in proceedings of the {ordinal_num} international conference on (artificial|artifcial|artifi- cial) ' \
f'intelligence, {num_or_hyphen}. aaai press',
f'in proceedings of the [\w]+ international conference on artificial intelligence and statistics, ' \
f'pp. {num_or_hyphen}, [\d]+',
'in (proceedings of |proc. )?international conference on machine learning' \
'((, volume [\d]+, pp. [\d\s\-\−\–]+)?, [\d]+)?',
'in international joint conferences on (artificial|artifcial|artifi- cial) intelligence',
f'ieee transactions on [\w\s\-\−\–]*{num_colon_hyphen_par}',
'in proceedings alt, [\d]+',
f'journal of artificial intelligence research, {num_colon_hyphen_par}',
f'journal of machine learning research( {num_colon_hyphen_par})?',
f'journal of the [\w\s:]+ [\w\(\)\s]*{num_colon_hyphen_par}',
'journal of the [\w\s]+, [\d]+',
'(the )?mit press( cambridge)?, [\d]+',
f'nature, {num_colon_hyphen_par}, [\d]+',
'pattern analysis and machine intelligence',
'proc siggraph',
f'proceedings of the {ordinal_num} international conference on computational linguistics, page(s)? '
f'{num_or_hyphen} [\w\s,]+( \(online\),)? [\w]+ {num_or_hyphen}, [\d]+',
'(cam- bridge |cambridge )?university press(,)? [\d]+(.|,)',
'workshop track',
'(in|proceedings of the) [\w\d\s\-.]+, page(s)? [\d]+(-[\d]+)?([\w\s\-,]+)?',
'international conference [\w\s\-\−\–]+, pp. [\d\s\-\−\–]+. [\w]+, [\d]+',
# international conference on intelligent robots and systems, pp. 5026-5033. ieee, 2012.
# 'pages [\d]+-[\d]+',
f'proceedings of the {ordinal_num} workshop [\w\s\-\−\–\(\)]+, page(s)? {num_or_hyphen} [\w\s]+, [\w\s]+' \
f'( \(online\))?, [\w]+ [\d]+, [\d]+',
'(©)?[\d]+ association for computational linguistics( [\d]+)?',
f'proceedings of the {ordinal_num} international conference on [\w\s,\-\−\–]+ pmlr ([\d,\s]+.)? ' \
f'copyright ([\d]+ )?by the author\(s\)',
'proceedings of the (st|nd|rd|th) international conference on machine learning online pmlr ' \
'copyright by the author',
f'proceedings of the {ordinal_num} international conference on machine learning \(icml [\d]+\), [\d]+',
'(proceedings of the|in) [\w]+(-[\w]+)? aaai conference on (artificial|artifcial|artifi- cial) ' \
'intelligence(, [\d]+| \(aaai-[\d]+\))?',
f'{prefix_proceedings}{prefix_paper_type}{pages_and_location}{dates_year}{suffix_acl}',
'c[\d]+ association for computational linguistics',
f'findings of the association for computational linguistics: emnlp [\d]+, page(s)? {num_or_hyphen}(,|.)? ' \
f'[\w]+ [\d\-\−\–\s]+(,|.) [\d]+',
f'(in )?(advances in neural information processing|findings of|proceedings of|{ordinal_num}? ' \
f'(international )?conference (on|in)) [\d\w\s\(\)#&\-\−\–:,.]+ page(s)? {num_or_hyphen}(,|.)( [\d]+)?',
'[\w]+, [\w]+, [\w]+ [\d]+ - [\w]+ [\d]+, [\d]+. [\w\d]+ association for computational linguistics',
f'[\w]+, [\w]+( \(online\))?, [\w]+ {num_or_hyphen}, [\d]+. (©)?[\d]+ association for computational ' \
f'linguistics proceedings of the {ordinal_num}[\w\s]+, page(s)? {num_or_hyphen}',
'[\w]*proceedings of the [\w\-]+ international joint conference on (artificial|artifcial|artifi- cial) ' \
'intelligence \([\d\w\-]+\)',
'published as a conference paper at [\w]+( [\d]+)?',
f'proceedings of the {ordinal_num} international conference on machine learning, [\w]+( [\w]+)*, ' \
'([\w]+(, [\w]+)*)*[,.]? pmlr [\d]+, [\d]+. [\w\-]+( [\d]+)? by the author(\(s\))?',
'published as a conference paper at [\w]+( [\d]+)',
f'[\w]+ state university {num_colon_hyphen_par}',
'springer science & business media(, [\d]+)?',
'statistical learning theory(, volume [\d]+)?',
f'statistical science, {num_colon_hyphen_par}, [\d]+',
f'the [\w\s,\-\−\–]+ aaai conference on artificial intelligence \(aaai{num_or_hyphen}\)',
'university of [\w\s]+, (dept.|department of) [\w\s\-\−\–]+, [\w\s\-\−\–.]+, [\d]+(, [\d]+)?',
# '(in|proceedings of the) [\w\d\s\-.]+, page(s)? [\d]+(-[\d]+)?(,|.) [\w\s]+, [\d]+',
]
self._phrases_to_remove = [
'(ablation stud(y|ies) )?we (also )?conduct(ed)? ablation stud(y|ies)( to)( demonstrate the (\w)+ of ' \
'(our|the)( proposed)?( implementation| method| solution)?)?',
'ablation stud(y|ies)',
'(ap(\w|[\d]+)? )+',
'(these |both the |all the |the first [\w]+ |first [\w]+ |the )?(authors )?contribute(d)? equally' \
'( to this work)?',
'in fact',
'corresponding author',
f'(in {item_citation} [\d]+ )?((we )|(it ))?(also |now )?show(s|n)? (in {item_citation} [\d]+ )?'
f'(that|(the )?result(s)?)',
'(we have |has )?show(n)? that',
f'(it is )?(show(n)? )?(in )?this {item_citation}( that)?',
'even though',
'experimental result[s]?( show(n|s)?| prove(s)?)?',
'let denote',
'achieve(d)? better performance',
'proposed method',
'(our )?contributions are summarized as follows',
'state of the art[s]?',
'(a number of |most |in )?(recent|related|previous|prior) (work|year)[s]?( have)?( also)?',
'(to the )?best of our knowledge',
'(we )?would like( to)?',
'(we )?conduct(ed)? (extensive |numerous |several )?experiment(s)?',
'supplementary material[s]?',
'all rights reserved(.|,)?',
'best viewed in color',
'this work is (licensed|licenced) under a creative commons attribution [\d.]+ international ' \
'(license|licence). (license|licence) details',
'(part of the )?(work|research) done during (an )?internship at',
'(the |this |these )?(experiment|result)[s]? (show(n|s|ing)?|prove(s)?)( that)?',
'(in )?the [\w]+ (row|column)(s)?( we)?( show(s)?)?( that| the)?',
'(in )?each (row|column)(s)?(we show( that| the)?)?',
# '(in )?(the )?([\w]+|each) ([\w]+ )?(row|column)(s)?( show(s)?)?( that| the)?',
'(the |this )?(work|research|paper) (is|was) (partially )?(done|funded by|supported( in part(s)?)? by) ' \
'([\w\s\d\-\_,]+ \(((, | and )?no. [\d\w\-\s]+)+\))+.',
'(the |this )?(work|research|paper) (is|was) (partially )?(done|funded by|supported( in part(s)?)? by) ' \
'[\w\s\d\-\_]+(no|and no)+ ([\w\d\-\_]+)*',
'(the |this )?(work|research|paper) (is|was) (partially )?(done|funded by|supported( in part(s)?)? by) ' \
'[\w\s\d\-\_]+\((grant no(.)? [\d]+| and |, and |no(.)? [\d]+)+\)',
'(the |this )?(work|research|paper) (is|was) (partially )?(done|funded by|supported( in part(s)?)? by) ' \
'[\d\s\w\-\_]+ of china',
'(the |this )?(work|research|paper) (is|was) (partially )?(done|funded by|supported( in part(s)?)? by)',
'joint research project with youtu lab of tencent',
'((the )?code )?(is |will be )?available at',
'this [\w\d]+ paper is the open access version provided by [\w\s\d\-_]+ except for this watermark it is ' \
'identical to the accepted version the final published version of the proceedings is available on ' \
'ieee xplore',
]
self._remaining_two_chars = [
'\\b[xyzwhijklt](_)?[\d]\\b',
'\\b[\d](_)?[xyzwhijklt]\\b',
'\\b[xyzwhijklt](_)?[aeiouxyzwhijklt]\\b',
'\\bth\\b',
'\\b_[\d\w]\\b',
'\\b[\d\w]_\\b',
'\\b_\\b',
]
self._symbols_dict = {
'∼' : '~',
'–': '-',
'−': '-',
'ꟻ': 'F',
}
self._words_with_footnotes = [
'available',
'code[s]?',
'dataset[s]?',
'github',
'image[s]?',
'model[s]?',
'video[s]?',
]
self._metrics = [
'db',
'px'
]
self._create_regexes_dict()
self._debug = debug
if self._debug:
self._logger.debug(
f'\nComposite words to remove: {sorted(self._composite_words)}')
self._logger.debug(
f'\nAdditional words to agglutinate: {sorted(self._new_words)}')
self._logger.debug(f'\nStop words: {sorted(self._stop_words)}')
self._logger.debug(
f'\nCommon words with footnotes: {self._words_with_footnotes}')
def _create_regexes_dict(self):
self._regexes = {}
# aglutinate_urls
regex = '\\b[0-9]?(ht|f)tp[s]?:[\\s/]+[\w.\-\−\–]+(-[\\s]+)?(.[\\s]+)?(?![0-9]?((ht|f)tp[s]?|. ))' \
'[\w:/?.&=#\-\−\–\~\˜\+]+([\-\−\–_:/][\\s]+(?![0-9]?((ht|f)tp[s]?|. ))' \
'[\w:/?.&=#\-\−\–\~\˜\+]+)*[\\s]*[,.\)/]'
regex += '((htm|html|mp4|py|zip|php)\\b)?' # possible extensions
self._regexes['aglutinate_urls'] = re.compile(regex)
# aglutinate_words
regex = '([\w]+)[\s]*-[\s]*([\w]+)'
self._regexes['aglutinate_words'] = re.compile(regex)
# remove_cid
regex = '\(cid:[\s0-9]+\)'
self._regexes['remove_cid'] = re.compile(regex)
# remove_composite_words
regex = '|'.join(self._composite_words)
regex = '[\s]*[\-\−\–_]?[\s]*'.join(regex.split('-'))
self._regexes['remove_composite_words'] = re.compile(regex)
# remove_eg_ie_etal
regexes = [
'e\.g\.', # e.g.
'i\.e\.', # i.e.
'w\.r\.t\.', # w.r.t.
# someone et.al.
'(\(|\\b)[\w\-\−\–´\'&]+[\s]+et[.]?[\s]+al[ .\b]([\s]*(,[\s]+|\()[\d]+)?(\)|;|\\b)?',
'(\\b|\()[\w]+[\s]+&[\s]+[\w]+([\s]+\(|,[\s]+)[\d]+(\)|\\b)', # someone & something
]
regex = '|'.join(regexes)
self._regexes['remove_eg_ie_etal'] = re.compile(regex)
# remove_equations
regex = '^[^ ]+[\s]?[=≡→←⊗][\s]?[^ \n]+[\s]*$'
self._regexes['remove_equations'] = re.compile(regex, re.MULTILINE)
# remove_emails
regex = '[\w.\-\−\–]+@[\w\-\−\–]+\.[\w.\-\−\–]+'
self._regexes['remove_emails'] = re.compile(regex)
# remove_footnotes_numbers
regex = '|'.join(self._words_with_footnotes)
regex = f'\\b({regex})[0-9]\\b'
self._regexes['remove_footnotes_numbers'] = re.compile(regex)
# remove_html_tags
regex = '[\s]*<(/)?[\w\s_\-\−\–=\"]+(/)?>[\s]*'
self._regexes['remove_html_tags'] = re.compile(regex)
# remove_hyphens_slashes
regex = '[\s]+[\-\−\–]|[\-\−\–][\s]+|/'
self._regexes['remove_hyphens_slashes'] = re.compile(regex)
# remove_item_citation
regexes = []
# item citation
prefix = '(\()?(((as|are)?[\s]*shown|see([\s]+next)?|summarized)?([\s+]in)?|please[\s]+refer[\s]+to)?'
item = '[\s]+(appendix[es]?|equation[s]?|figure[s]?|table[s]?|fig[s]?.|theorem[s]?|(sub)?section[s]?|(sub)?sec[s]?.)'
first_number_letter = '[\s.]+[0-9]*([\-\−\–\(.]?[\w]{1}[\)]?)?'
next_number_letters = '((,[\s]+|[\s]+and[\s]+|\-)[0-9]*([\-\−\–\(.]?[\w]{1}[\)]?)?)*'
suffix = '([\s]+(show[s]?|above|below))?([\s,.:\)]|\\b)'
regexes.append(f'{prefix}{item}{first_number_letter}{next_number_letters}{suffix}')
# references citation
regexes.append('\[[0-9][,\s\-\−\–0-9]*\]')
regex = '|'.join(regexes)
self._regexes['remove_item_citation'] = re.compile(regex)
# remove_latex_commands
regex = '[\s]*\\\[^ ]+[\s]*'
self._regexes['remove_latex_commands'] = re.compile(regex)
# remove_latex_inline_equations
regex = '[\s]*\$[^\$]+\$[\s]*'
self._regexes['remove_latex_inline_equations'] = re.compile(regex)
# remove_latexit_tags
regex = '<latexit[\d\s\w/=\"+_()]*>[\s\w\d=/+()]*</latexit>'
self._regexes['remove_latexit_tags'] = re.compile(regex)
# remove_metrics
metrics_regex_str = '|'.join(f'[\s]?{w}' for w in self._metrics)
regex = f'[\s\(\[\{{\∼\~][0-9]+([.,][0-9]+)?([\s]?[%kmb]+|{metrics_regex_str})?[.,:\s\)\]\}}]'
self._regexes['remove_metrics'] = re.compile(regex)
# remove_numbers
regexes = []
# numbers
regexes.append('[\s\(\[\{\∼\~][-]?[0-9]+([.,][0-9]+)?([\s]+[-]?[0-9]+([.,][0-9]+)?)*[.,:\s\)\]\}]')
# roman numbers
regexes.append('[\(\s][ivx]+\)')
# enumerates
regexes.append('\([\s]*[a-zA-Z][\s]*\)')
regex = '|'.join(regexes)
self._regexes['remove_numbers'] = re.compile(regex)
# remove_numbers_only_lines
regexes = []
# numbers
regexes.append('^[\(]?[-−]?[0-9]+([.,][0-9]+)?([\s\+\-\−\–\±]+[\-\−\–]?[0-9]+([.,][0-9]+)?)*[\)]?[\s]*$')
# headers
regexes.append('^[0-9]+.([0-9]+[.]?){0,2}$')
regex = '|'.join(regexes)
self._regexes['remove_numbers_only_lines'] = re.compile(regex, re.MULTILINE)
# remove_ordinal_numbers
regex = '[0-9]*1st|[0-9]*2nd|[0-9]*3rd|[0-9]+th'
self._regexes['remove_ordinal_numbers'] = re.compile(regex)
# remove_bib_info
bib_info_to_remove = (fr'\b{p}' for p in self._bib_info_to_remove)
bib_info_to_remove = (fr'{p}\b' if not p.endswith('\)') else p for p in bib_info_to_remove)
regex = '|'.join(bib_info_to_remove)
regex = '[\s]+'.join(regex.split())
self._regexes['remove_bib_info'] = re.compile(regex)
# remove_phrases
phrases_to_remove = (fr'\b{p}' for p in self._phrases_to_remove)
phrases_to_remove = (fr'{p}\b' if not p.endswith('\)') and not p.endswith('.') else p for p in phrases_to_remove)
regex = '|'.join(phrases_to_remove)
regex = '[\s]+'.join(regex.split())
self._regexes['remove_phrases'] = re.compile(regex)
# remove_remaining_two_chars
regex = '|'.join(self._remaining_two_chars)
regex = '[\s]+'.join(regex.split())
self._regexes['remove_remaining_two_chars'] = re.compile(regex)
# remove_shapes
regex = '[hwck0-9]+[x×][hwck0-9]+[x×]?[hwck0-9]*'
self._regexes['remove_shapes'] = re.compile(regex)
# remove_specific_expressions
regexes = []
# arxiv:1701.08893, 2016.
regexes.append('\\barxiv:[0-9]+.[0-9]+(, [\d]+[a-z]?)\\b')
# pages 234– 241
regexes.append('\\bpages[\s]+[0-9]+[\s]*[\-\−\–][\s]*[0-9]+\\b')
regex = '|'.join(regexes)
self._regexes['remove_specific_expressions'] = re.compile(regex)
# remove_symbols
regex = '[^ a-zA-Z0-9\-_/]'
self._regexes['remove_symbols'] = re.compile(regex)
# remove_tabular_data
regexes = [
# '^[\w\-\−\–]+[\t ]*[:=,.]?[\t ]*$',
'\n\n[\w\-\−\–]+[\t ]*[:=,.]?[\t ]*\n',
'^[^\s.,]+$',
]
regex = '|'.join(regexes)
self._regexes['remove_tabular_data'] = re.compile(regex, re.MULTILINE)
# remove_urls
regex = '\\b(ht|f)tp[s]?://[\w:/?.&=#\-\−\–\~\˜]+[/.,\\d\)]?'
self._regexes['remove_urls'] = re.compile(regex)
# replace_hyphens_by_underline
regex = '([\w]+)-([\w]+)'
self._regexes['replace_hyphens_by_underline'] = re.compile(regex)
def _pretty_print(
self,
regex: str | re.Pattern,
text: str,
color: str = BG_HIGHLIGHT_COLOR,
border_line_limit: int = LINE_LIMIT,
flags: re.RegexFlag=re.RegexFlag.NOFLAG,
) -> None:
new_text = ''
previous_start = 0
if isinstance(regex, re.Pattern):
gen = enumerate(regex.finditer(text))
else:
gen = enumerate(re.finditer(regex, text, flags=flags))
for i, match in gen:
start, end = match.span()
if i == 0 and len(text[previous_start:start]) > border_line_limit:
new_text += f'...\n{text[start-border_line_limit:start]}'
else:
new_text += text[previous_start:start]
new_text += color + text[start:end] + Back.RESET
previous_start = end
if previous_start != 0:
if len(text[previous_start:]) > border_line_limit:
new_text += f'{text[previous_start:previous_start+border_line_limit]}\n...'
else:
new_text += text[previous_start:]
self._logger.debug(new_text)
else:
self._logger.debug('Text kept the same')
def _highlight_not_recognized_words(self, text: str, spell_checker: enchant.Dict = enchant.Dict("en_US"),
extra_lemmas_dict: dict[str, str] = {}, color: int = Back.BLUE) -> str:
def _recognized(word: str) -> bool:
if len(word) > 0 and spell_checker.check(word) or word in self._new_words or word in extra_lemmas_dict.values():
return True
else:
return False
new_words = []
text_split = text.strip().split()
words_with_underline = (w for w in text_split if '_' in w)
for word in words_with_underline:
splitted = word.split('_')
recognized_words = [w for w in splitted if _recognized(w)]
if len(splitted) == len(recognized_words):
new_words.append(word)
new_words += self._new_words
return ' '.join(w if spell_checker.check(w) or w in new_words else f'{color}{w}{Back.RESET}' for w in text_split)
def _run_regex(self, text: str, regexes: str | list[str] | re.Pattern, replacement: str = ' ', flags: re.RegexFlag=re.RegexFlag.NOFLAG) -> str:
if isinstance(regexes, list):
regexes = '|'.join(regexes)
regexes = re.compile(regexes, flags)
elif isinstance(regexes, str):
regexes = re.compile(regexes, flags)
if self._debug:
self._pretty_print(regexes, text)
return regexes.sub(replacement, text)
def aglutinate_urls(self, text: str, spell_checker: enchant.Dict = enchant.Dict("en_US")) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nAglutinating urls:')
regex = self._regexes['aglutinate_urls']
if self._debug:
self._pretty_print(regex, text)
self._logger.debug('')
match = regex.search(text)
previous_index = 0
while match is not None:
start, end = match.span()
word = text[previous_index +
start:previous_index+end]
if word[0].isnumeric():
word = text[previous_index + 1 +
start:previous_index+end]
text = text.replace(
text[previous_index+start:previous_index+end], word)
end -= 1
if word.find(' ') > 0:
if self._debug:
self._logger.debug(f'Aglutinating {word}')
last_word = word.split()[-1]
if last_word.endswith('.') or last_word.endswith(',') or last_word.endswith(')'):
last_word = last_word[:-1]
if len(last_word) > 0 and last_word[0].isupper() and spell_checker.check(last_word):
end = end - len(word.split()[-1]) - 1
word = text[previous_index +
start:previous_index+end].strip()
word = word.replace(' ', '')
text = text.replace(
text[previous_index+start:previous_index+end], word)
previous_index += end-1
match = regex.search(text[previous_index:])
return text
def aglutinate_words(
self,
text: str,
spell_checker: enchant.Dict = enchant.Dict("en_US"),
min_occurrences: int = 5,
) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nAglutinating words separated by "-":')
regex = self._regexes['aglutinate_words']
not_existing_words_found = set()
if self._debug:
self._pretty_print(regex, text)
self._logger.debug('')
match = regex.search(text)
previous_index = 0
while match is not None:
original_word = text[previous_index + match.start():previous_index + match.end()]
word = re.sub(regex, '\\1\\2', original_word)
if word not in not_existing_words_found:
if word in self._new_words or spell_checker.check(word):
self._logger.debug(f'{Fore.RED}{original_word}{Fore.RESET} -> {Fore.GREEN}{word}{Fore.RESET}')
text = re.sub(original_word, word, text)
elif re.search(word, text) is not None and len(re.findall(word, text)) > min_occurrences:
self._logger.debug(f'{Fore.RED}{original_word}{Fore.RESET} -> {Fore.GREEN}{word}{Fore.RESET}'
f' (happens more than {min_occurrences}x)')
self._new_words.add(word)
text = re.sub(original_word, word, text)
else:
hyphen_word = re.sub(regex, '\\1_\\2', original_word)
self._logger.debug(f'Keep {Fore.GREEN}{hyphen_word}{Fore.RESET}')
if hyphen_word != original_word:
text = re.sub(original_word, hyphen_word, text)
not_existing_words_found.add(word)
else:
hyphen_word = re.sub(regex, '\\1_\\2', original_word)
self._logger.debug(f'Keep {Fore.GREEN}{hyphen_word}{Fore.RESET}')
if hyphen_word != original_word:
text = re.sub(original_word, hyphen_word, text)
previous_index += match.start()
match = regex.search(text[previous_index:])
return text
def aglutinate_word_sequences(
self,
text: str,
spell_checker: enchant.Dict = enchant.Dict("en_US"),
max_ngram: int = 2,
min_occurrences: int = 5,
) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nAglutinating words separated by " ":')
def _recognized(word: str) -> bool:
if len(word) > 0 and spell_checker.check(word) or word in self._new_words:
return True
else:
return False
words = text.strip().split()
for n in reversed(range(2, max_ngram + 1)):
self._logger.debug(f'Replacing {n}-grams')
i = n
while i < len(words):
# only agglutinate if at least one of the words has more than 2 chars, none starts or
# ends with - and the first one is not in since it could alter the meaning of the sentence
# (e.g.: in different - indifferent)
if any((len(w) > 2 for w in words[i-n:i])) and \
not any((w.startswith('-') or w.endswith('-') for w in words[i-n:i])) and \
words[i-n] != 'in':
ngram = ''.join(words[i-n:i])
if ngram not in self._non_aglutinable_words and ngram[:5] != 'anon-':
if _recognized(ngram):
if self._debug:
ngram_orig = ' '.join(words[i-n:i])
self._logger.debug(f'{Fore.RED}{ngram_orig}{Fore.RESET} -> {Fore.GREEN}{ngram}{Fore.RESET}')
words[i-n] = ngram
i -= n-1
j = n-1
while j > 0:
words.pop(i)
j -= 1
# only consider if the ngram happens at least X times
elif re.search(ngram, text) is not None and len(re.findall(ngram, text)) > min_occurrences:
if self._debug:
ngram_orig = ' '.join(words[i-n:i])
self._logger.debug(f'{Fore.RED}{ngram_orig}{Fore.RESET} -> {Fore.GREEN}{ngram}{Fore.RESET}'
f' (happens more than {min_occurrences}x)')
self._new_words.add(ngram)
words[i-n] = ngram
i -= n-1
j = n-1
while j > 0:
words.pop(i)
j -= 1
else:
i += 1
else:
i += 1
else:
i += 1
return ' '.join(words)
def plural_to_singular(self, text: str,
lemmatizer: Callable[[str], str] = _grammar.singular_noun,
extra_lemmas_dict: dict[str, str] = {}) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nConverting from plural to singular:')
tokens = word_tokenize(text)
# multibias, multiclass, across, address, helpless, multiloss, fairness, dangerous, heterogeneous, various, decompress
# stimulus, analysis
suffixes = ('agenda', 'bacteria', 'bias', 'data', 'lus', 'nas', 'ous', 'sis', 'ss')
def _lemmatize_fn(word: str) -> str:
if word.endswith(suffixes):
return word
return lemmatizer(word)
words_in_singular = (_lemmatize_fn(w) if w not in extra_lemmas_dict else extra_lemmas_dict[w] for w in tokens)
# do this because how inflect library works (returns singular of the word or False)
words_in_singular = (w if not isinstance(w, bool) else tokens[i] for i, w in enumerate(words_in_singular))
if self._debug:
coloured_tokens = (w if (w not in extra_lemmas_dict) and (w.endswith(suffixes) or lemmatizer(w) == False) \
else BG_HIGHLIGHT_COLOR + w + Back.RESET for w in tokens)
self._logger.debug(' '.join(coloured_tokens))
return ' '.join(words_in_singular)
def remove_accents(self, text: str) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving accents:')
accents = {
'[áàãâä]|´a|`a|\~a|\^a': 'a',
'ç': 'c',
'[éèêë]|´e|`e|\^e': 'e',
'[íïì]|´i|`i': 'i',
'ñ': 'n',
'[óòôö]|´o|`o|\~o|\^o': 'o',
'[úùü]|´u|`u': 'u',
'ß': 'ss',
}
if self._debug:
regex = '|'.join(accents.keys())
self._pretty_print(re.compile(regex), text)
for k, v in accents.items():
text = re.sub(k, v, text)
return text
def remove_before_title(self, text: str, title: str, ignore_case=False) -> str:
title_split = title.strip().split()
# use first 3 words if it has
if len(title_split) >= 3:
first_words_of_title = ' '.join(title_split[:3])
elif len(title_split) >= 2:
first_words_of_title = ' '.join(title_split[:2])
else:
first_words_of_title = title_split[0]
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving text before title:')
if ignore_case:
end = text.lower().find(first_words_of_title.lower())
else:
end = text.find(first_words_of_title)
if end > 0:
return self.remove_text_between_positions(text, to_position=end)
else:
return text
def remove_between_title_abstract(self, text: str, title: str, end_word: str = 'abstract', ignore_case=False) -> str:
title_split = title.strip().split()
# use last 3 words if it has
if len(title_split) >= 3:
last_words_of_title = ' '.join(title_split[-3:])
elif len(title_split) >= 2:
last_words_of_title = ' '.join(title_split[-2:])
else:
last_words_of_title = title_split[0]
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving text between title and abstract, '
f'delimited by "{last_words_of_title}" and "{end_word}":')
if ignore_case:
lower_text = text.lower()
last_words_of_title = last_words_of_title.lower()
start = lower_text.find(last_words_of_title) + len(last_words_of_title)
end = lower_text[start:].find(end_word) + start + len(end_word)
else:
start = text.find(last_words_of_title) + len(last_words_of_title)
end = text[start:].find(end_word) + start + len(end_word)
return self.remove_text_between_positions(text, start, end)
def remove_bib_info(self, text: str, phrases: None | list[str] = None) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving bib info:')
if phrases and len(phrases) > 0:
phrases += self._bib_info_to_remove
phrases_gen = (fr'\b{p}' for p in phrases)
phrases_gen = (fr'{p}\b' if not p.endswith('\)') else p for p in phrases_gen)
regex_str = '|'.join(phrases)
regex_str = '[\s]+'.join(regex_str.split())
regex = re.compile(regex_str)
else:
regex = self._regexes['remove_bib_info']
return self._run_regex(text, regex, ' ')
def remove_cid(self, text: str) -> str:
# a PDF contains CMAPs which map character codes to glyph indices
# so, a CID is a character id for the glyph it maps to, inside the CMAP table
self._logger.debug(f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving cids:')
regex = self._regexes['remove_cid']
return self._run_regex(text, regex, '')
def remove_composite_words(self, text: str, composite_words: None | list[str] = None) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving composite words:')
if composite_words and len(composite_words) > 0:
composite_words += self._composite_words
regex_str = '|'.join(composite_words)
regex_str = '[\s]*[-_][\s]*'.join(regex_str.split('-'))
regex = re.compile(regex_str)
else:
regex = self._regexes['remove_composite_words']
return self._run_regex(text, regex, ' ')
def remove_eg_ie_etal(self, text: str) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving e.g., i.e. and et al:')
regex = self._regexes['remove_eg_ie_etal']
return self._run_regex(text, regex, ' ')
def remove_equations(self, text: str) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving equations:')
regex = self._regexes['remove_equations']
return self._run_regex(text, regex, '\n')
def remove_emails(self, text: str) -> str:
self._logger.debug(f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving emails:')
regex = self._regexes['remove_emails']
return self._run_regex(text, regex, ' ')
def remove_first_word_occurrence(self, text: str, word: str, ignore_case=False) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving first occurrence of "{word}":')
if ignore_case:
index = text.lower().find(word.lower())
else:
index = text.find(word)
if index >= 0:
if self._logger.isEnabledFor(logging.DEBUG):
tmp_text = text[:index] + BG_HIGHLIGHT_COLOR + word + Back.RESET + text[index + len(word):]
self._logger.debug(tmp_text)
return text[:index] + text[index + len(word):]
else:
self._logger.debug('Text kept the same')
return text
def remove_footnotes_numbers(self, text: str, words_with_footnotes: None | list[str] = None) -> str:
self._logger.debug(
f'\n{Fore.GREEN}###########################{Fore.RESET}\n\nRemoving footnotes from words:')
if words_with_footnotes and len(words_with_footnotes) > 0:
words_with_footnotes += self._words_with_footnotes
regex_str = '|'.join(words_with_footnotes)
regex_str = f'\\b({regex_str})[0-9]\\b'
regex = re.compile(regex_str)
else:
regex = self._regexes['remove_footnotes_numbers']
return self._run_regex(text, regex, '\\1')
def remove_from_word_to_end(self, text: str, from_word: str, ignore_case=False) -> str:
self._logger.debug(