This repository has been archived by the owner on Apr 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathannotations.py
1683 lines (1271 loc) · 74.7 KB
/
annotations.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 numpy as np
import uuid, re, subprocess, os, shutil, math, re, logging, pickle, json, itertools, functools, psutil, time
import multiprocessing, gc
import pandas
import spacy_wrapper, spacy
import snips_nlu_parsers
import utils
# Data files for gazetteers
WIKIDATA = "./data/wikidata.json"
WIKIDATA_SMALL = "./data/wikidata_small.json"
#COMPANY_NAMES = "./data/company_names.json"
GEONAMES = "./data/geonames.json"
CRUNCHBASE = "./data/crunchbase.json"
PRODUCTS = "./data/products.json"
FIRST_NAMES = "./data/first_names.json"
# sets of tokens used for the shallow patterns
MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
MONTHS_ABBRV = {"Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sep.", "Sept.", "Oct.", "Nov.", "Dec."}
DAYS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
DAYS_ABBRV = {"Mon.", "Tu.", "Tue.", "Tues.", "Wed.", "Th.", "Thu.", "Thur.", "Thurs.", "Fri.", "Sat.", "Sun."}
MAGNITUDES = {"million", "billion", "mln", "bln", "bn", "thousand", "m", "k", "b", "m.", "k.", "b.", "mln.", "bln.", "bn."}
UNITS = {"tons", "tonnes", "barrels", "m", "km", "miles", "kph", "mph", "kg", "°C", "dB", "ft", "gal", "gallons", "g", "kW", "s", "oz",
"m2", "km2", "yards", "W", "kW", "kWh", "kWh/yr", "Gb", "MW", "kilometers", "meters", "liters", "litres", "g", "grams", "tons/yr",
'pounds', 'cubits', 'degrees', 'ton', 'kilograms', 'inches', 'inch', 'megawatts', 'metres', 'feet', 'ounces', 'watts', 'megabytes',
'gigabytes', 'terabytes', 'hectares', 'centimeters', 'millimeters'}
ORDINALS = ({"first, second, third", "fourth", "fifth", "sixth", "seventh"} |
{"%i1st"%i for i in range(100)} | {"%i2nd"%i for i in range(100)} | {"%ith"%i for i in range(1000)})
ROMAN_NUMERALS = {'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX','X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII',
'XVIII', 'XIX', 'XX', 'XXI', 'XXII', 'XXIII', 'XXIV', 'XXV', 'XXVI', 'XXVII', 'XXVIII', 'XXIX', 'XXX'}
# Full list of country names
COUNTRIES = {'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua', 'Argentina', 'Armenia', 'Australia', 'Austria',
'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan',
'Bolivia', 'Bosnia Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina', 'Burundi', 'Cambodia', 'Cameroon',
'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Costa Rica',
'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor',
'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Fiji', 'Finland', 'France',
'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana',
'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Ivory Coast',
'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea North', 'Korea South', 'Kosovo', 'Kuwait', 'Kyrgyzstan',
'Laos','Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia', 'Madagascar',
'Malawi', 'Malaysia', 'Maldives','Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia',
'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique','Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands',
'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea',
'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russian Federation', 'Rwanda', 'St Kitts & Nevis',
'St Lucia', 'Saint Vincent & the Grenadines','Samoa', 'San Marino', 'Sao Tome & Principe', 'Saudi Arabia', 'Senegal', 'Serbia',
'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Sudan',
'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania',
'Thailand', 'Togo', 'Tonga', 'Trinidad & Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine',
'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela',
'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe', "USA", "UK", "Russia", "South Korea"}
# Natialities, religious and political groups
NORPS = {'Afghan', 'African', 'Albanian', 'Algerian', 'American', 'Andorran', 'Anglican', 'Angolan', 'Arab', 'Aramean','Argentine', 'Armenian',
'Asian', 'Australian', 'Austrian', 'Azerbaijani', 'Bahamian', 'Bahraini', 'Baklan', 'Bangladeshi', 'Batswana', 'Belarusian', 'Belgian',
'Belizean', 'Beninese', 'Bermudian', 'Bhutanese', 'Bolivian', 'Bosnian', 'Brazilian', 'British', 'Bruneian', 'Buddhist',
'Bulgarian', 'Burkinabe', 'Burmese', 'Burundian', 'Californian', 'Cambodian', 'Cameroonian', 'Canadian', 'Cape Verdian', 'Catholic', 'Caymanian',
'Central African', 'Central American', 'Chadian', 'Chilean', 'Chinese', 'Christian', 'Christian-Democrat', 'Christian-Democratic',
'Colombian', 'Communist', 'Comoran', 'Congolese', 'Conservative', 'Costa Rican', 'Croat', 'Cuban', 'Cypriot', 'Czech', 'Dane', 'Danish',
'Democrat', 'Democratic', 'Djibouti', 'Dominican', 'Dutch', 'East European', 'Ecuadorean', 'Egyptian', 'Emirati', 'English', 'Equatoguinean',
'Equatorial Guinean', 'Eritrean', 'Estonian', 'Ethiopian', 'Eurasian', 'European', 'Fijian', 'Filipino', 'Finn', 'Finnish', 'French',
'Gabonese', 'Gambian', 'Georgian', 'German', 'Germanic', 'Ghanaian', 'Greek', 'Greenlander', 'Grenadan', 'Grenadian', 'Guadeloupean', 'Guatemalan',
'Guinea-Bissauan', 'Guinean', 'Guyanese', 'Haitian', 'Hawaiian', 'Hindu', 'Hinduist', 'Hispanic', 'Honduran', 'Hungarian', 'Icelander', 'Indian',
'Indonesian', 'Iranian', 'Iraqi', 'Irish', 'Islamic','Islamist', 'Israeli', 'Israelite', 'Italian', 'Ivorian', 'Jain', 'Jamaican', 'Japanese',
'Jew', 'Jewish', 'Jordanian', 'Kazakhstani', 'Kenyan', 'Kirghiz', 'Korean', 'Kurd', 'Kurdish', 'Kuwaiti', 'Kyrgyz', 'Labour', 'Latin',
'Latin American', 'Latvian', 'Lebanese', 'Liberal', 'Liberian', 'Libyan', 'Liechtensteiner', 'Lithuanian', 'Londoner', 'Luxembourger',
'Macedonian', 'Malagasy', 'Malawian','Malaysian', 'Maldivan', 'Malian', 'Maltese', 'Manxman', 'Marshallese', 'Martinican', 'Martiniquais',
'Marxist', 'Mauritanian', 'Mauritian', 'Mexican', 'Micronesian', 'Moldovan', 'Mongolian', 'Montenegrin', 'Montserratian', 'Moroccan',
'Motswana', 'Mozambican', 'Muslim', 'Myanmarese', 'Namibian', 'Nationalist', 'Nazi', 'Nauruan', 'Nepalese', 'Netherlander', 'New Yorker',
'New Zealander', 'Nicaraguan', 'Nigerian', 'Nordic', 'North American', 'North Korean','Norwegian','Orthodox', 'Pakistani', 'Palauan',
'Palestinian', 'Panamanian', 'Papua New Guinean', 'Paraguayan', 'Parisian', 'Peruvian', 'Philistine', 'Pole', 'Polish', 'Portuguese',
'Protestant', 'Puerto Rican', 'Qatari', 'Republican', 'Roman', 'Romanian', 'Russian', 'Rwandan', 'Saint Helenian', 'Saint Lucian',
'Saint Vincentian', 'Salvadoran', 'Sammarinese', 'Samoan', 'San Marinese', 'Sao Tomean', 'Saudi', 'Saudi Arabian', 'Scandinavian', 'Scottish',
'Senegalese', 'Serb', 'Serbian', 'Shia', 'Shiite', 'Sierra Leonean', 'Sikh', 'Singaporean', 'Slovak', 'Slovene', 'Social-Democrat', 'Socialist',
'Somali', 'South African', 'South American', 'South Korean', 'Soviet', 'Spaniard', 'Spanish', 'Sri Lankan', 'Sudanese', 'Sunni',
'Surinamer', 'Swazi', 'Swede', 'Swedish', 'Swiss', 'Syrian', 'Taiwanese', 'Tajik', 'Tanzanian', 'Taoist', 'Texan', 'Thai', 'Tibetan',
'Tobagonian', 'Togolese', 'Tongan', 'Tunisian', 'Turk', 'Turkish', 'Turkmen(s)', 'Tuvaluan', 'Ugandan', 'Ukrainian', 'Uruguayan', 'Uzbek',
'Uzbekistani', 'Venezuelan', 'Vietnamese', 'Vincentian', 'Virgin Islander', 'Welsh', 'West European', 'Western', 'Yemeni', 'Yemenite',
'Yugoslav', 'Zambian', 'Zimbabwean', 'Zionist'}
# Facilities
FACILITIES = {"Palace", "Temple", "Gate", "Museum", "Bridge", "Road", "Airport", "Hospital", "School", "Tower", "Station", "Avenue",
"Prison", "Building", "Plant", "Shopping Center", "Shopping Centre", "Mall", "Church", "Synagogue", "Mosque", "Harbor", "Harbour",
"Rail", "Railway", "Metro", "Tram", "Highway", "Tunnel", 'House', 'Field', 'Hall', 'Place', 'Freeway', 'Wall', 'Square', 'Park',
'Hotel'}
# Legal documents
LEGAL = {"Law", "Agreement", "Act", 'Bill', "Constitution", "Directive", "Treaty", "Code", "Reform", "Convention", "Resolution", "Regulation",
"Amendment", "Customs", "Protocol", "Charter"}
# event names
EVENTS = {"War", "Festival", "Show", "Massacre", "Battle", "Revolution", "Olympics", "Games", "Cup", "Week", "Day", "Year", "Series"}
# Names of languages
LANGUAGES = {'Afar', 'Abkhazian', 'Avestan', 'Afrikaans', 'Akan', 'Amharic', 'Aragonese', 'Arabic', 'Aramaic', 'Assamese', 'Avaric', 'Aymara',
'Azerbaijani', 'Bashkir', 'Belarusian', 'Bulgarian', 'Bambara', 'Bislama', 'Bengali', 'Tibetan', 'Breton', 'Bosnian', 'Cantonese',
'Catalan', 'Chechen', 'Chamorro', 'Corsican', 'Cree', 'Czech', 'Chuvash', 'Welsh', 'Danish', 'German', 'Divehi', 'Dzongkha', 'Ewe',
'Greek', 'English', 'Esperanto', 'Spanish', 'Castilian', 'Estonian', 'Basque', 'Persian', 'Fulah', 'Filipino', 'Finnish', 'Fijian', 'Faroese',
'French', 'Western Frisian', 'Irish', 'Gaelic', 'Galician', 'Guarani', 'Gujarati', 'Manx', 'Hausa', 'Hebrew', 'Hindi', 'Hiri Motu',
'Croatian', 'Haitian', 'Hungarian', 'Armenian', 'Herero', 'Indonesian', 'Igbo', 'Inupiaq', 'Ido', 'Icelandic', 'Italian', 'Inuktitut',
'Japanese', 'Javanese', 'Georgian', 'Kongo', 'Kikuyu', 'Kuanyama', 'Kazakh', 'Kalaallisut', 'Greenlandic', 'Central Khmer', 'Kannada',
'Korean', 'Kanuri', 'Kashmiri', 'Kurdish','Komi', 'Cornish', 'Kirghiz', 'Latin', 'Luxembourgish', 'Ganda', 'Limburgish', 'Lingala', 'Lao',
'Lithuanian', 'Luba-Katanga', 'Latvian', 'Malagasy', 'Marshallese', 'Maori', 'Macedonian', 'Malayalam', 'Mongolian', 'Marathi', 'Malay',
'Maltese', 'Burmese', 'Nauru', 'Bokmål', 'Norwegian', 'Ndebele', 'Nepali', 'Ndonga', 'Dutch', 'Flemish', 'Nynorsk', 'Navajo', 'Chichewa',
'Occitan', 'Ojibwa', 'Oromo', 'Oriya', 'Ossetian', 'Punjabi', 'Pali', 'Polish', 'Pashto', 'Portuguese', 'Quechua', 'Romansh', 'Rundi',
'Romanian', 'Russian', 'Kinyarwanda', 'Sanskrit', 'Sardinian', 'Sindhi', 'Sami', 'Sango', 'Sinhalese', 'Slovak', 'Slovenian', 'Samoan',
'Shona', 'Somali', 'Albanian', 'Serbian', 'Swati', 'Sotho', 'Sundanese', 'Swedish', 'Swahili', 'Tamil', 'Telugu', 'Tajik', 'Thai',
'Tigrinya', 'Turkmen', 'Taiwanese', 'Tagalog', 'Tswana', 'Tonga', 'Turkish', 'Tsonga', 'Tatar', 'Twi', 'Tahitian', 'Uighur', 'Ukrainian',
'Urdu', 'Uzbek', 'Venda', 'Vietnamese', 'Volapük', 'Walloon', 'Wolof', 'Xhosa', 'Yiddish', 'Yoruba', 'Zhuang', 'Mandarin',
'Mandarin Chinese', 'Chinese', 'Zulu'}
# Generic words that may appear in official company names but are sometimes skipped when mentioned in news articles (e.g. Nordea Bank -> Nordea)
GENERIC_TOKENS = {"International", "Group", "Solutions", "Technologies", "Management", "Association", "Associates", "Partners",
"Systems", "Holdings", "Services", "Bank", "Fund", "Stiftung", "Company"}
# List of tokens that are typically lowercase even when they occur in capitalised segments (e.g. International Council of Shopping Centers)
LOWERCASED_TOKENS = {"'s", "-", "a", "an", "the", "at", "by", "for", "in", "of", "on", "to", "up", "and"}
# Prefixes to family names that are often in lowercase
NAME_PREFIXES = {"-", "von", "van", "de", "di", "le", "la", "het", "'t'", "dem", "der", "den", "d'", "ter"}
############################################
# ANNOTATOR
############################################
class BaseAnnotator:
"""Base class for the annotations. """
def __init__(self, to_exclude=None):
self.to_exclude = list(to_exclude) if to_exclude is not None else []
def pipe(self, docs):
"""Goes through the stream of documents and annotate them"""
for doc in docs:
yield self.annotate(doc)
def annotate(self, doc):
"""Annotates one single document"""
raise NotImplementedError()
def clear_source(self, doc, source):
"""Clears the annotation associated with a given source name"""
if "annotations" not in doc.user_data:
doc.user_data["annotations"] = {}
doc.user_data["annotations"][source] = {}
def add(self, doc, start, end, label, source, conf=1.0):
""" Adds a labelled span to the annotation"""
if not self._is_allowed_span(doc, start, end):
return
elif (start,end) not in doc.user_data["annotations"][source]:
doc.user_data["annotations"][source][(start, end)] = ((label, conf),)
# If the span is already present, we need to check that the total confidence does not exceed 1.0
else:
current_vals = doc.user_data["annotations"][source][(start, end)]
if label in {label2 for label2, _ in current_vals}:
return
total_conf = sum([conf2 for _, conf2 in current_vals]) + conf
if total_conf > 1.0:
current_vals = [(label2, conf2/total_conf) for label2, conf2 in current_vals]
conf = conf/total_conf
doc.user_data["annotations"][source][(start, end)] = (*current_vals, (label, conf))
def _is_allowed_span(self, doc, start, end):
"""Checks whether the span is allowed (given exclusivity relations with other sources)"""
for source in self.to_exclude:
intervals = list(doc.user_data["annotations"][source].keys())
start_search, end_search = _binary_search(start, end, intervals)
for interval_start, interval_end in intervals[start_search:end_search]:
if start < interval_end and end > interval_start:
return False
return True
def annotate_docbin(self, docbin_input_file, docbin_output_file=None, return_raw=False,
cutoff=None, nb_to_skip=0):
"""Runs the annotator on the documents of a DocBin file, and write the output
to the same file (or returns the raw data is return_raw is True)"""
attrs = [spacy.attrs.LEMMA, spacy.attrs.TAG, spacy.attrs.DEP, spacy.attrs.HEAD,
spacy.attrs.ENT_IOB, spacy.attrs.ENT_TYPE]
docbin = spacy.tokens.DocBin(attrs=attrs, store_user_data=True)
print("Reading", docbin_input_file, end="...", flush=True)
for doc in self.pipe(docbin_reader(docbin_input_file, cutoff=cutoff, nb_to_skip=nb_to_skip)):
docbin.add(doc)
if len(docbin)%1000 ==0:
print("Number of processed documents:", len(docbin))
print("Finished annotating", docbin_input_file)
data = docbin.to_bytes()
if return_raw:
return data
else:
if docbin_output_file is None:
docbin_output_file = docbin_input_file
print("Write to", docbin_output_file, end="...", flush=True)
fd = open(docbin_output_file, "wb")
fd.write(data)
fd.close()
print("done")
class FullAnnotator(BaseAnnotator):
"""Annotator of entities in documents, combining several sub-annotators (such as gazetteers,
spacy models etc.). To add all annotators currently implemented, call add_all(). """
def __init__(self):
super(FullAnnotator,self).__init__()
self.annotators = []
def pipe(self, docs):
"""Annotates the stream of documents using the sub-annotators."""
streams = itertools.tee(docs, len(self.annotators)+1)
pipes = [annotator.pipe(stream) for annotator,stream in zip(self.annotators, streams[1:])]
for doc in streams[0]:
for pipe in pipes:
try:
next(pipe)
except:
print("ignoring document:", doc)
yield doc
def annotate(self, doc):
"""Annotates a single document with the sub-annotators
NB: do not use this method for large collections of documents (as it is quite inefficient), and
prefer the method pipe that runs the Spacy models on batches of documents"""
for annotator in self.annotators:
doc = annotator.annotate(doc)
return doc
def add_annotator(self, annotator):
self.annotators.append(annotator)
return self
def add_all(self):
"""Adds all implemented annotation functions, models and filters"""
print("Loading shallow functions")
self.add_shallow()
print("Loading Spacy NER models")
self.add_models()
print("Loading gazetteer supervision modules")
self.add_gazetteers()
print("Loading document-level supervision sources")
self.add_doc_level()
return self
def add_shallow(self):
"""Adds shallow annotation functions"""
# Detection of dates, time, money, and numbers
self.add_annotator(FunctionAnnotator(date_generator, "date_detector"))
self.add_annotator(FunctionAnnotator(time_generator, "time_detector"))
self.add_annotator(FunctionAnnotator(money_generator, "money_detector"))
exclusives = ["date_detector", "time_detector", "money_detector"]
# Detection based on casing
proper_detector = SpanGenerator(is_likely_proper)
self.add_annotator(FunctionAnnotator(proper_detector, "proper_detector",
to_exclude=exclusives))
# Detection based on casing, but allowing some lowercased tokens
proper2_detector = SpanGenerator(is_likely_proper, exceptions=LOWERCASED_TOKENS)
self.add_annotator(FunctionAnnotator(proper2_detector, "proper2_detector",
to_exclude=exclusives))
# Detection based on part-of-speech tags
nnp_detector = SpanGenerator(lambda tok: tok.tag_=="NNP")
self.add_annotator(FunctionAnnotator(nnp_detector, "nnp_detector",
to_exclude=exclusives))
# Detection based on dependency relations (compound phrases)
compound_detector = SpanGenerator(lambda x: is_likely_proper(x) and in_compound(x))
self.add_annotator(FunctionAnnotator(compound_detector, "compound_detector",
to_exclude=exclusives))
# We add one variants for each NE detector, looking at infrequent tokens
for source_name in ["proper_detector", "proper2_detector", "nnp_detector","compound_detector"]:
self.add_annotator(SpanConstraintAnnotator(is_infrequent, source_name, "infrequent_"))
self.add_annotator(FunctionAnnotator(legal_generator, "legal_detector", exclusives))
exclusives += ["legal_detector"]
self.add_annotator(FunctionAnnotator(number_generator, "number_detector", exclusives))
# Detection of companies with a legal type
self.add_annotator(FunctionAnnotator(CompanyTypeGenerator(), "company_type_detector",
to_exclude=exclusives))
# Detection of full person names
self.add_annotator(FunctionAnnotator(FullNameGenerator(), "full_name_detector",
to_exclude=exclusives+["company_type_detector"]))
# Detection based on a probabilistic parser
self.add_annotator(FunctionAnnotator(SnipsGenerator(), "snips"))
return self
def add_models(self):
"""Adds Spacy NER models to the annotator"""
self.add_annotator(ModelAnnotator("en_core_web_md", "core_web_md"))
self.add_annotator(ModelAnnotator("data/conll2003", "conll2003"))
self.add_annotator(ModelAnnotator("data/BTC", "BTC"))
self.add_annotator(ModelAnnotator("data/SEC-filings", "SEC"))
return self
def add_gazetteers(self):
"""Adds gazetteer supervision models (company names and wikidata)."""
exclusives = ["date_detector", "time_detector", "money_detector", "number_detector"]
# Annotation of company, person and location names based on wikidata
self.add_annotator(GazetteerAnnotator(WIKIDATA, "wiki", to_exclude=exclusives))
# Annotation of company, person and location names based on wikidata (only entries with descriptions)
self.add_annotator(GazetteerAnnotator(WIKIDATA_SMALL, "wiki_small", to_exclude=exclusives))
# Annotation of location names based on geonames
self.add_annotator(GazetteerAnnotator(GEONAMES, "geo", to_exclude=exclusives))
# Annotation of organisation and person names based on crunchbase open data
self.add_annotator(GazetteerAnnotator(CRUNCHBASE, "crunchbase", to_exclude=exclusives))
# Annotation of product names
self.add_annotator(GazetteerAnnotator(PRODUCTS, "product", to_exclude=exclusives[:-1]))
# We also add new sources for multitoken entities (which have higher confidence)
for source_name in ["wiki", "wiki_small", "geo", "crunchbase", "product"]:
for cased in ["cased", "uncased"]:
self.add_annotator(SpanConstraintAnnotator(lambda s: len(s) > 1, "%s_%s"%(source_name, cased), "multitoken_"))
self.add_annotator(FunctionAnnotator(misc_generator, "misc_detector", exclusives))
return self
def add_doc_level(self):
"""Adds document-level supervision sources"""
self.add_annotator(StandardiseAnnotator())
self.add_annotator(DocumentHistoryAnnotator())
self.add_annotator(DocumentMajorityAnnotator())
return self
############################################
# I/O FUNCTIONS
############################################
def docbin_reader(docbin_input_file, vocab=None, cutoff=None, nb_to_skip=0):
"""Generate Spacy documents from the input file"""
if vocab is None:
if not hasattr(docbin_reader, "vocab"):
print("Loading vocabulary", end="...", flush=True)
docbin_reader.vocab = spacy.load("en_core_web_md").vocab
print("done")
vocab = docbin_reader.vocab
vocab.strings.add("subtok")
fd = open(docbin_input_file, "rb")
data = fd.read()
fd.close()
docbin = spacy.tokens.DocBin(store_user_data=True)
docbin.from_bytes(data)
del data
# print("Total number of documents in docbin:", len(docbin))
# Hack to easily skip a number of documents
if nb_to_skip:
docbin.tokens = docbin.tokens[nb_to_skip:]
docbin.spaces = docbin.spaces[nb_to_skip:]
docbin.user_data = docbin.user_data[nb_to_skip:]
reader = docbin.get_docs(vocab)
for i, doc in enumerate(reader):
yield doc
if cutoff is not None and (i+1) >= cutoff:
return
def convert_to_json(docbin_file, json_file, source="HMM", cutoff=None, nb_to_skip=0):
corpus_gen = docbin_reader(docbin_file)
for i in range(nb_to_skip):
next(corpus_gen)
print("Writing JSON file to", json_file)
out_fd = open(json_file, "wt")
out_fd.write("[{\"id\": 0, \"paragraphs\": [\n")
for i, doc in enumerate(corpus_gen):
doc.ents = tuple(spacy.tokens.Span(doc, start, end, doc.vocab.strings[label])
for (start, end), ((label,conf),) in doc.user_data["annotations"][source].items() if end <= len(doc))
doc.user_data = {}
d = spacy.gold.docs_to_json([doc])
s = json.dumps(d["paragraphs"]).strip("[]")
if i==0:
out_fd.write(s)
else:
out_fd.write(",\n"+s)
if cutoff is not None and i >= cutoff:
out_fd.flush()
break
if i>0 and i % 1000 == 0:
print("Converted documents:", i)
out_fd.flush()
out_fd.write("]}]\n")
out_fd.flush()
out_fd.close()
def _annotate_docbin_parallel(cmd, docbin_input_file, docbin_output_file, nb_cores=8, nb_docs=160000):
"""Utility function to easily distribute the annotation of large docbin files on
several cores. The command must be a string whose evaluation returns the annotator"""
p = multiprocessing.Pool(nb_cores)
args = [(cmd, docbin_input_file, (nb_docs//nb_cores) if i<nb_cores-1 else None,
i*(nb_docs//nb_cores)) for i in range(nb_cores)]
datas = p.starmap(_annotate_fun, args)
p.close()
attrs = [spacy.attrs.LEMMA, spacy.attrs.TAG, spacy.attrs.DEP, spacy.attrs.HEAD,
spacy.attrs.ENT_IOB, spacy.attrs.ENT_TYPE]
docbin = spacy.tokens.DocBin(attrs, store_user_data=True)
for data in datas:
docbin.merge(spacy.tokens.DocBin(store_user_data=True).from_bytes(data))
data = docbin.to_bytes()
print("Write to", docbin_output_file, end="...", flush=True)
fd = open(docbin_output_file, "wb")
fd.write(data)
fd.close()
print("done")
def _annotate_fun(cmd, docbin_input_file, cutoff, nb_to_skip):
return eval(cmd).annotate_docbin(docbin_input_file, cutoff=cutoff, nb_to_skip=nb_to_skip)
############################################
# CORE ANNOTATORS
############################################
class ModelAnnotator(BaseAnnotator):
"""Annotation based on a spacy NER model"""
def __init__(self, model_path, source_name):
super(ModelAnnotator, self).__init__()
print("loading", model_path, end="...", flush=True)
model = spacy.load(model_path)
self.ner = model.get_pipe("ner")
self.source_name = source_name
print("done")
def pipe(self, docs):
"""Annotates the stream of documents based on the Spacy NER model"""
stream1, stream2 = itertools.tee(docs, 2)
# Apply the NER models through the pipe
# (we need to work on copies to strange deadlock conditions)
stream2 = (spacy.tokens.Doc(d.vocab).from_bytes(d.to_bytes(exclude="user_data"))
for d in stream2)
def remove_ents(doc): doc.ents = tuple() ; return doc
stream2 = (remove_ents(d) for d in stream2)
stream2 = self.ner.pipe(stream2)
for doc, doc_copy in zip(stream1, stream2):
self.clear_source(doc, self.source_name)
self.clear_source(doc, self.source_name+"+c")
# Add the annotation
for ent in doc_copy.ents:
self.add(doc, ent.start, ent.end, ent.label_, self.source_name)
# Correct some entities
doc_copy = spacy_wrapper._correct_entities(doc_copy)
for ent in doc_copy.ents:
self.add(doc, ent.start, ent.end, ent.label_, self.source_name+"+c")
yield doc
def annotate(self, doc):
"""Annotates one single document using the Spacy NER model
NB: do not use this method for large collections of documents (as it is quite inefficient), and
prefer the method pipe that runs the Spacy model on batches of documents"""
ents = list(doc.ents)
doc.ents = tuple()
doc = self.ner(doc)
self.clear_source(doc, self.source_name)
self.clear_source(doc, self.source_name+"+c")
# Add the annotation
for ent in doc.ents:
self.add(doc, ent.start, ent.end, ent.label_, self.source_name)
# Correct some entities
doc = spacy_wrapper._correct_entities(doc)
for ent in doc.ents:
self.add(doc, ent.start, ent.end, ent.label_, self.source_name+"+c")
doc.ents = ents
return doc
class FunctionAnnotator(BaseAnnotator):
"""Annotation based on a heuristic function that generates (start,end,label) given a spacy document"""
def __init__(self, function, source_name, to_exclude=()):
"""Create an annotator based on a function generating labelled spans given a Spacy Doc object. Spans that
overlap with existing spans from sources listed in 'to_exclude' are ignored. """
super(FunctionAnnotator, self).__init__(to_exclude=to_exclude)
self.function = function
self.source_name = source_name
def annotate(self, doc):
"""Annotates one single document"""
self.clear_source(doc, self.source_name)
for start, end, label in self.function(doc):
self.add(doc, start, end, label, self.source_name)
return doc
class SpanConstraintAnnotator(BaseAnnotator):
"""Annotation by looking at text spans (from another source) that satisfy a span-level constratint"""
def __init__(self, constraint, initial_source_name, prefix):
super(SpanConstraintAnnotator, self).__init__()
self.constraint = constraint
self.initial_source_name = initial_source_name
self.prefix = prefix
def annotate(self, doc):
"""Annotates one single document"""
self.clear_source(doc, self.prefix+self.initial_source_name)
for (start, end), vals in doc.user_data["annotations"][self.initial_source_name].items():
if self.constraint(doc[start:end]):
for label, conf in vals:
self.add(doc, start, end, label, self.prefix+self.initial_source_name, conf)
return doc
############################################
# ANNOTATION WITH DISTANT SUPERVISION
############################################
class GazetteerAnnotator(BaseAnnotator):
"""Annotation using a gazetteer, i.e. a large list of entity terms. The annotation looks
both at case-sensitive and case-insensitive occurrences. The annotator relies on a token-level
trie for efficient search. """
def __init__(self, json_file, source_name, to_exclude=()):
super(GazetteerAnnotator, self).__init__(to_exclude=to_exclude)
self.trie = extract_json_data(json_file)
self.source_name = source_name
def annotate(self, doc):
"""Annotates one single document"""
self.clear_source(doc, "%s_%s"%(self.source_name, "cased"))
self.clear_source(doc, "%s_%s"%(self.source_name, "uncased"))
for start, end, label, conf in self.get_hits(doc, case_sensitive=True, full_compound=True):
self.add(doc, start, end, label, "%s_%s"%(self.source_name, "cased"), conf)
for start, end, label, conf in self.get_hits(doc, case_sensitive=False, full_compound=True):
self.add(doc, start, end, label, "%s_%s"%(self.source_name, "uncased"), conf)
return doc
def get_hits(self, spacy_doc, case_sensitive=True, lookahead=10, full_compound=True):
"""Search for occurrences of entity terms in the spacy document"""
tokens = tuple(tok.text for tok in spacy_doc)
i = 0
while i < len(tokens):
tok = spacy_doc[i]
# Skip punctuation
if tok.is_punct:
i += 1
continue
# We skip if we are inside a compound phrase
elif full_compound and i > 0 and is_likely_proper(spacy_doc[i-1]) and spacy_doc[i-1].dep_=="compound":
i += 1
continue
span = tokens[i:i+lookahead]
prefix_length, prefix_value = self.trie.longest_prefix(span, case_sensitive)
if prefix_length:
# We further require at least one proper noun token (to avoid too many FPs)
if not any(is_likely_proper(tok) for tok in spacy_doc[i:i+prefix_length]):
i += 1
continue
# If we found a company and the next token is a legal suffix, include it
if ((i+prefix_length) < len(spacy_doc) and {"ORG", "COMPANY"}.intersection(prefix_value)
and spacy_doc[i+prefix_length].lower_.rstrip(".") in spacy_wrapper.LEGAL_SUFFIXES):
prefix_length += 1
# If the following tokens are part of the same compound phrase, skip
if full_compound and spacy_doc[i+prefix_length-1].dep_=="compound" and spacy_doc[i+prefix_length].text not in {"'s"}:
i += 1
continue
# Must account for spans with multiple possible entities
for neClass in prefix_value:
yield i, i+prefix_length, neClass, 1/len(prefix_value)
# We skip the text until the end of the occurences + 1 token (we assume two entities do not
# follow one another without at least one token such as a comma)
i += (prefix_length + 1)
else:
i += 1
def extract_json_data(json_file):
"""Extract entities from a Json file """
print("Extracting data from", json_file)
fd = open(json_file)
data = json.load(fd)
fd.close()
trie = utils.Trie()
for neClass, names in data.items():
print("Populating trie for entity class %s (number: %i)"%(neClass, len(names)))
for name in names:
# Removes parentheses and appositions
name = name.split("(")[0].split(",")[0].rstrip()
name = tuple(utils.tokenise_fast(name))
# Add the entity into the trie (values are tuples since each entity may have several possible types)
if name in trie and neClass not in trie[name]:
trie[name] = (*trie[name], neClass)
else:
trie[name] = (neClass,)
return trie
############################################
# ANNOTATION WITH SHALLOW PATTERNS
############################################
def date_generator(spacy_doc):
"""Searches for occurrences of date patterns in text"""
spans = {}
i = 0
while i < len(spacy_doc):
tok = spacy_doc[i]
if tok.lemma_ in DAYS | DAYS_ABBRV:
spans[(i,i+1)] = "DATE"
elif tok.is_digit and re.match("\d+$", tok.text) and int(tok.text) > 1920 and int(tok.text) < 2040:
spans[(i,i+1)] = "DATE"
elif tok.lemma_ in MONTHS | MONTHS_ABBRV:
if tok.tag_=="MD": # Skipping "May" used as auxiliary
pass
elif i > 0 and re.match("\d+$", spacy_doc[i-1].text) and int(spacy_doc[i-1].text) < 32:
spans[(i-1,i+1)] = "DATE"
elif i > 1 and re.match("\d+(?:st|nd|rd|th)$", spacy_doc[i-2].text) and spacy_doc[i-1].lower_=="of":
spans[(i-2,i+1)] = "DATE"
elif i < len(spacy_doc)-1 and re.match("\d+$", spacy_doc[i+1].text) and int(spacy_doc[i+1].text) < 32:
spans[(i,i+2)] = "DATE"
i += 1
else:
spans[(i,i+1)] = "DATE"
i += 1
# Concatenating contiguous spans
spans = merge_contiguous_spans(spans, spacy_doc)
for i, ((start,end), content) in enumerate(spans.items()):
yield start, end, content
def time_generator(spacy_doc):
"""Searches for occurrences of time patterns in text"""
i = 0
while i < len(spacy_doc):
tok = spacy_doc[i]
if (i < len(spacy_doc)-1 and tok.text[0].isdigit() and
spacy_doc[i+1].lower_ in {"am", "pm", "a.m.", "p.m.", "am.", "pm."}):
yield i, i+2, "TIME"
i += 1
elif tok.text[0].isdigit() and re.match("\d{1,2}\:\d{1,2}", tok.text):
yield i, i+1, "TIME"
i += 1
i += 1
def money_generator(spacy_doc):
"""Searches for occurrences of money patterns in text"""
i = 0
while i < len(spacy_doc):
tok = spacy_doc[i]
if tok.text[0].isdigit():
j = i+1
while (j < len(spacy_doc) and (spacy_doc[j].text[0].isdigit() or spacy_doc[j].norm_ in MAGNITUDES)):
j += 1
found_symbol = False
if i > 0 and spacy_doc[i-1].text in (spacy_wrapper.CURRENCY_CODES |
spacy_wrapper.CURRENCY_SYMBOLS):
i = i-1
found_symbol = True
if j < len(spacy_doc) and spacy_doc[j].text in (spacy_wrapper.CURRENCY_CODES |
spacy_wrapper.CURRENCY_SYMBOLS |
{"euros", "cents", "rubles"}):
j += 1
found_symbol = True
if found_symbol:
yield i,j, "MONEY"
i = j
else:
i += 1
def number_generator(spacy_doc):
"""Searches for occurrences of number patterns (cardinal, ordinal, quantity or percent) in text"""
i = 0
while i < len(spacy_doc):
tok = spacy_doc[i]
if tok.lower_ in ORDINALS:
yield i, i+1, "ORDINAL"
elif re.search("\d", tok.text):
j = i+1
while (j < len(spacy_doc) and (spacy_doc[j].norm_ in MAGNITUDES)):
j += 1
if j < len(spacy_doc) and spacy_doc[j].lower_.rstrip(".") in UNITS:
j += 1
yield i, j, "QUANTITY"
elif j < len(spacy_doc) and spacy_doc[j].lower_ in ["%", "percent", "pc.", "pc", "pct", "pct.", "percents", "percentage"]:
j += 1
yield i, j, "PERCENT"
else:
yield i, j, "CARDINAL"
i = j-1
i += 1
class SpanGenerator:
"""Generate spans that satisfy a token-level constratint"""
def __init__(self, constraint, label="ENT", exceptions=("'s", "-")):
"""annotation with a constraint (on spacy tokens). Exceptions are sets of tokens that are allowed
to violate the constraint inside the span"""
self.constraint = constraint
self.label = label
self.exceptions = set(exceptions)
def __call__(self, spacy_doc):
i = 0
while i < len(spacy_doc):
tok = spacy_doc[i]
# We search for the longest span that satisfy the constraint
if self.constraint(tok):
j = i+1
while True:
if j < len(spacy_doc) and self.constraint(spacy_doc[j]):
j += 1
# We relax the constraint a bit to allow genitive and dashes
elif j < (len(spacy_doc)-1) and spacy_doc[j].text in self.exceptions and self.constraint(spacy_doc[j+1]):
j += 2
else:
break
# To avoid too many FPs, we only keep entities with at least 3 characters (excluding punctuation)
if len(spacy_doc[i:j].text.rstrip(".")) > 2:
yield i, j, self.label
i = j
else:
i += 1
class CompanyTypeGenerator:
"""Search for compound spans that end with a legal suffix"""
def __init__(self):
self.suggest_generator = SpanGenerator(lambda x: is_likely_proper(x) and in_compound(x))
def __call__(self, spacy_doc):
for start, end, _ in self.suggest_generator(spacy_doc):
if spacy_doc[end-1].lower_.rstrip(".") in spacy_wrapper.LEGAL_SUFFIXES:
yield start, end, "COMPANY"
elif end < len(spacy_doc) and spacy_doc[end].lower_.rstrip(".") in spacy_wrapper.LEGAL_SUFFIXES:
yield start, end+1, "COMPANY"
class FullNameGenerator:
"""Search for occurrences of full person names (first name followed by at least one title token)"""
def __init__(self):
fd = open(FIRST_NAMES)
self.first_names = set(json.load(fd))
fd.close()
self.suggest_generator = SpanGenerator(lambda x: is_likely_proper(x) and in_compound(x),
exceptions=NAME_PREFIXES)
def __call__(self, spacy_doc):
for start, end, _ in self.suggest_generator(spacy_doc):
# We assume full names are between 2 and 4 tokens
if (end-start) < 2 or (end-start) > 5:
continue
elif (spacy_doc[start].text in self.first_names and spacy_doc[end-1].is_alpha
and spacy_doc[end-1].is_title):
yield start, end, "PERSON"
class SnipsGenerator:
"""Annotation using the Snips NLU entity parser. """
def __init__(self):
"""Initialise the annotation tool."""
self.parser = snips_nlu_parsers.BuiltinEntityParser.build(language="en")
def __call__(self, spacy_doc):
"""Runs the parser on the spacy document, and convert the result to labels."""
text = spacy_doc.text
# The current version of Snips has a bug that makes it crash with some rare Turkish characters, or mentions of "billion years"
text = text.replace("’", "'").replace("”", "\"").replace("“", "\"").replace("—", "-").encode("iso-8859-15", "ignore").decode("iso-8859-15")
text = re.sub("(\d+) ([bm]illion(?: (?:\d+|one|two|three|four|five|six|seven|eight|nine|ten))? years?)", "\g<1>.0 \g<2>", text)
results = self.parser.parse(text)
for result in results:
span = spacy_doc.char_span(result["range"]["start"], result["range"]["end"])
if span is None or span.lower_ in {"now"} or span.text in {"may"}:
continue
label = None
if result["entity_kind"]=="snips/number" and span.lower_ not in {"one", "some", "few", "many", "several"}:
label = "CARDINAL"
elif result["entity_kind"]=="snips/ordinal" and span.lower_ not in {"first", "second", "the first", "the second"}:
label = "ORDINAL"
elif result["entity_kind"]=="snips/amountOfMoney":
label = "MONEY"
elif result["entity_kind"]=="snips/percentage":
label = "PERCENT"
elif result["entity_kind"] in {"snips/date", "snips/datePeriod"}:
label = "DATE"
elif result["entity_kind"] in {"snips/time", "snips/timePeriod"}:
label = "TIME"
if label:
yield span.start, span.end, label
def legal_generator(spacy_doc):
legal_spans = {}
for (start,end) in get_spans(spacy_doc, ["proper2_detector", "nnp_detector"]):
if not is_likely_proper(spacy_doc[end-1]):
continue
span = spacy_doc[start:end].text
last_token = spacy_doc[end-1].text.title().rstrip("s")
if last_token in LEGAL:
legal_spans[(start,end)] = "LAW"
# Handling legal references such as Article 5
for i in range(len(spacy_doc)-1):
if spacy_doc[i].text.rstrip("s") in {"Article", "Paragraph", "Section", "Chapter", "§"}:
if spacy_doc[i+1].text[0].isdigit() or spacy_doc[i+1].text in ROMAN_NUMERALS:
start, end = i, i+2
if (i < len(spacy_doc)-3 and spacy_doc[i+2].text in {"-", "to", "and"}
and (spacy_doc[i+3].text[0].isdigit() or spacy_doc[i+3].text in ROMAN_NUMERALS)):
end = i+4
legal_spans[start, end] = "LAW"
# Merge contiguous spans of legal references ("Article 5, Paragraph 3")
legal_spans = merge_contiguous_spans(legal_spans, spacy_doc)
for start, end in legal_spans:
yield start, end, "LAW"
def misc_generator(spacy_doc):
"""Detects occurrences of countries and various less-common entities (NORP, FAC, EVENT, LANG)"""
spans = set(spacy_doc.user_data["annotations"]["proper_detector"].keys())
spans.update((i,i+1) for i in range(len(spacy_doc)))
spans = sorted(spans, key=lambda x:x[0])
for (start,end) in spans:
span = spacy_doc[start:end].text
span = span.title() if span.isupper() else span
last_token = spacy_doc[end-1].text
if span in COUNTRIES:
yield start, end, "GPE"
if end <= (start+3) and (span in NORPS or last_token in NORPS or last_token.rstrip("s") in NORPS):
yield start, end, "NORP"
if span in LANGUAGES and spacy_doc[start].tag_=="NNP":
yield start, end, "LANGUAGE"
if last_token in FACILITIES and end > start+1:
yield start, end, "FAC"
if last_token in EVENTS and end > start+1:
yield start, end, "EVENT"
############################################
# STANDARDISATION OF ANNOTATIONS
############################################
class StandardiseAnnotator(BaseAnnotator):