-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluator.py
2230 lines (2077 loc) · 126 KB
/
Evaluator.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
# from keras_models.utils.nlp import tokenize
import nltk
import spacy
from seqeval.metrics import f1_score, accuracy_score, classification_report
from rdflib import Graph
from rdflib.util import guess_format
# import pprint
import json
import io
import os
nlp = spacy.load('en_core_web_sm')
def writeNERoutputFileConll():#this writes the named entities of Conll03 dataset files in format required for ner evaluation i.e. like this [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
# inputFile = 'inputConll\conllpp\conllpp_test.txt' # Corrected CONLL EVALUATION DATASET
inputFile = 'inputConll\conll2003.eng.testb.txt' # CONLL EVALUATION DATASET #'inputConll\conll2003.eng.train.txt' # CONLL Training DATASET
# outputFile = 'outputConll\\eval\conllEntities\\conllppAllEntitiesWithMisc.txt' # Corrected CoNLL Entities output file
outputFile = 'outputConll\\eval\conllEntities\\allEntitiesWithMisc.txt' # CoNLL Entities output file
allEntities = []
entities = []
with open(inputFile, 'r', encoding='utf-8', errors='ignore') as inF:
# inputData = inF.read()
docNo = -1
for line in inF:
if (line.find('-DOCSTART-') == -1 and line.find('-DOCEND-') == -1): # within a doc
if line != '\n':
line = line.split('\n')[0]
x = line.split(' ')
lineFirstTok = x[0] # the token
lineLastTok = x[len(x) - 1] # the ner type
entities.append(lineLastTok)
elif (line.find('-DOCSTART-') != -1 or line.find('-DOCEND-') != -1): # start of next doc
if docNo >= 0:
allEntities.append(entities)
docNo += 1
entities = []
with open(outputFile, 'w', encoding='utf-8') as outF:
json.dump(allEntities, outF, sort_keys=True, ensure_ascii=False)
def writeNERoutputFileOke():#this writes the named entities of OKE dataset files in format required for ner evaluation script i.e. like this [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
inputFile = 'inputOKE\okeEvalInputTexts.txt' # OKE DATASET sentences
inputFile2Dir = 'outputOKE\\eval\\hmariEntities\\allEntities\\output' #'outputOKE\\eval\okeEntitiesOriginal\\doc' # oke Entities files directory #
outputFile = 'outputOKE\\eval\\hmariEntities\\allEntities\\allEntities2.txt' #'outputOKE\\eval\okeEntitiesOriginal\\allEntities.txt' # oke Entities output file #
allEntities = []
entities = []
with open(inputFile, 'r', encoding='utf-8', errors='ignore') as inF:
for docNo,line in enumerate(inF):#one line of inF is one doc
if docNo==50:
print()
# tokens = tokenize(line)
# tokens = nltk.word_tokenize(line)
doc = nlp(line)
tokens = [token.text for token in doc]
inputFile2 = inputFile2Dir + str(docNo) + '.txt'
inF2 = io.open(inputFile2, 'r', encoding='utf-8', errors='ignore')
okeEntities = json.load(inF2)
inF2.close()
entityNo = 0
charNoOkeFile = charEndNoOkeFile = 0 # this keeps track of the token being read (its stard and end character no) in the oke input sentences file
if len(okeEntities)>0:
entity = okeEntities[entityNo][0] #[0] is added for hmariEntities only
entityStart = int(entity['characterOffsetBegin'])
entityEnd = int(entity['characterOffsetEnd'])
else: entityStart = entityEnd = 0
consecutiveSameTypeEntities = False
for token in tokens:
ner = "O"
# if token=="``":
# token = "\""
# if token=="\'\'":
# # print(token)
# token = "\""
# # print(token)
# if docNo==31 and token=="Jr.":
# print(len(token))
temp = str.find(line,token,charEndNoOkeFile-1)
if temp!= -1:
charNoOkeFile = temp
charEndNoOkeFile = charNoOkeFile + len(token)
else:
charNoOkeFile = charEndNoOkeFile + 1
charEndNoOkeFile = charNoOkeFile + len(token)
if charNoOkeFile > entityEnd:
entityNo += 1
if entityNo < len(okeEntities):
entity = okeEntities[entityNo][0] #[0] is added for hmariEntities only
entityStart = int(entity['characterOffsetBegin'])
entityEnd = int(entity['characterOffsetEnd'])
offsetRangeEntity = range(entityStart, entityEnd) # offset range of current entity
offsetRangeTokenRead = range(charNoOkeFile, charEndNoOkeFile) # offset range of current token being read
offsetRangesOverlap = [i for i in offsetRangeEntity if i in offsetRangeTokenRead]
if len(offsetRangesOverlap) > 0:# if entityStart <= charNoOkeFile and charNoOkeFile < entityEnd:
ner = entity['ner']
text = entity['text']
if entityNo > 0 and entityNo < len(okeEntities):
prevEntity = okeEntities[entityNo - 1][0] #[0] is added for hmariEntities only
prevNer = prevEntity['ner']
if prevNer == ner:
if entityStart == int(prevEntity['characterOffsetEnd']) + 1:
if text.split(' ')[0] == token: # if its the first token of this entity, because B- tag is only for beginning of entity (which is consecutive and having same type)
consecutiveSameTypeEntities = True
ner = ner[0] + ner[1] + ner[2] # getting just first 3 characters of ner i.e. loc, org and per
ner = str.upper(ner)
if consecutiveSameTypeEntities == False:
ner = "I-" + ner
else:
ner = "B-" + ner
consecutiveSameTypeEntities = False
entities.append(ner)
entTokCount1 = entTokCount2 = 0
for ent1 in okeEntities:
ent1 = ent1[0] #[0] is added for hmariEntities only
text = ent1['text']
# ent1Toks = nltk.word_tokenize(text)
docE = nlp(text)
ent1Toks = [token.text for token in docE]
entTokCount1 += len(ent1Toks)#(text.split(' '))
for ent2 in entities:
if ent2 != "O":
entTokCount2 += 1
if entTokCount2 != entTokCount1:
print("docNo: " + str(docNo) + " , ENTITIES list is NOT CORRECTLY CREATED!!!!!!!!!!!!")
print(entTokCount1)
print(entTokCount2)
print(entities)
# break
allEntities.append(entities)
entities = []
with open(outputFile, 'w', encoding='utf-8') as outF:
json.dump(allEntities, outF, sort_keys=True, ensure_ascii=False)
def writeGenderOutputFileOke(folder): # this writes the male/female of OKE dataset files in format required for ner evaluation script i.e. like this [['O', 'O', 'O', 'B-MALE', 'I-MALE', 'I-MALE', 'O'], ['B-FEMALE', 'I-FEMALE', 'O']]
inputFile = 'inputOKE\okeEvalInputTexts.txt' # OKE DATASET sentences
inputFile2Dir = 'outputOKE\\eval\okeEntitiesCorrected\\'+folder+'\\output'
outputFile = 'outputOKE\\eval\okeEntitiesCorrected\\'+folder+'\\allEntities.txt'
allEntities = []
entities = []
with open(inputFile, 'r', encoding='utf-8', errors='ignore') as inF:
for docNo, line in enumerate(inF): # one line of inF is one doc
tokens = nltk.word_tokenize(line)
inputFile2 = inputFile2Dir + str(docNo) + '.txt'
inF2 = io.open(inputFile2, 'r', encoding='utf-8', errors='ignore')
okeEntities = json.load(inF2)
inF2.close()
entityNo = 0
charNoOkeFile = charEndNoOkeFile = 0 # this keeps track of the token being read (its stard and end character no) in the oke input sentences file
if len(okeEntities) > 0:
entity = okeEntities[entityNo]
entityStart = int(entity['characterOffsetBegin'])
entityEnd = int(entity['characterOffsetEnd'])
else:
entityStart = entityEnd = 0
consecutiveSameTypeEntities = False
for token in tokens:
gender = "O"
if token == "``":
token = "\""
if token == "\'\'":
# print(token)
token = "\""
# print(token)
# if docNo == 38 and token == "de":
# print(len(token))
temp = str.find(line, token, charEndNoOkeFile - 1)
if temp != -1:
charNoOkeFile = temp
charEndNoOkeFile = charNoOkeFile + len(token)
else:
charNoOkeFile = charEndNoOkeFile + 1
charEndNoOkeFile = charNoOkeFile + len(token)
if charNoOkeFile > entityEnd:
entityNo += 1
if entityNo < len(okeEntities):
entity = okeEntities[entityNo]
entityStart = int(entity['characterOffsetBegin'])
entityEnd = int(entity['characterOffsetEnd'])
offsetRangeEntity = range(entityStart, entityEnd) # offset range of current entity
offsetRangeTokenRead = range(charNoOkeFile,charEndNoOkeFile) # offset range of current token being read
offsetRangesOverlap = [i for i in offsetRangeEntity if i in offsetRangeTokenRead]
if len(offsetRangesOverlap) > 0: # if entityStart <= charNoOkeFile and charNoOkeFile < entityEnd:
ner = entity['ner']
text = entity['text']
if 'gender' in entity.keys():
prevGender = ""
gender = entity['gender']
if entityNo > 0 and entityNo < len(okeEntities):
prevEntity = okeEntities[entityNo - 1]
prevNer = prevEntity['ner']
if 'gender' in prevEntity.keys():
prevGender = prevEntity['gender']
if prevNer == ner =='PERSON':
if prevGender!="" and prevGender == gender:
if entityStart == int(prevEntity['characterOffsetEnd']) + 1:
if text.split(' ')[
0] == token: # if its the first token of this entity, because B- tag is only for beginning of entity (which is consecutive and having same type)
consecutiveSameTypeEntities = True
if consecutiveSameTypeEntities == False:
gender = "I-" + gender
else:
gender = "B-" + gender
consecutiveSameTypeEntities = False
entities.append(gender)
entTokCount1 = entTokCount2 = 0 #token count of male/female entities
for ent1 in okeEntities:
if 'gender' in ent1.keys():
text = ent1['text']
ent1Toks = nltk.word_tokenize(text)
entTokCount1 += len(ent1Toks) # (text.split(' '))
if 'Jr.' in text:
entTokCount1 -= 1
for ent2 in entities:
if ent2 != "O":
entTokCount2 += 1
if entTokCount2 != entTokCount1:
print("docNo: " + str(docNo) + " , ENTITIES list is NOT CORRECTLY CREATED!!!!!!!!!!!!")
print(entTokCount1)
print(entTokCount2)
print(entities)
# break
allEntities.append(entities)
entities = []
with open(outputFile, 'w', encoding='utf-8') as outF:
json.dump(allEntities, outF, sort_keys=True, ensure_ascii=False)
# def writeNERoutputFileOkeOthers():#for oke dataset, this writes the named entities of input file in format required for ner evaluation i.e. like this [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
# inputFile = 'inputOKE\okeEvalInputTexts.txt' # OKE DATASET sentences
# inputFile2Dir = 'outputOKE\\eval\okeEntities\\doc' # oke Entities files directory
# outputFile = 'outputOKE\\eval\okeEntities\\allEntities.txt' # oke Entities output file
# allEntities = []
# entities = []
# with open(inputFile, 'r', encoding='utf-8', errors='ignore') as inF:
# for docNo,line in enumerate(inF):#one line of inF is one doc
# tokens = tokenize(line)
# inputFile2 = inputFile2Dir + docNo + '.txt'
# inF2 = io.open(inputFile2, 'r', encoding='utf-8', errors='ignore')
# okeEntities = json.load(inF2)
# inF2.close()
# systemEntityNo = 0
# charNoConllFile = -1 # this keeps track of the character no being read in the conll dataset file
# systemEntityEnd = 0
# consecutiveSameTypeEntities = False
# for token in tokens:
# ner = "O"
# if charNoConllFile > systemEntityEnd:
# systemEntityNo += 1
# if systemEntityNo < len(systemEntities):
# systemEntity = systemEntities[systemEntityNo]
# if system == 'ours':
# # print(line)
# systemEntity = systemEntity[0]
# systemEntityStart = systemEntity['characterOffsetBegin']
# systemEntityEnd = systemEntity['characterOffsetEnd']
# if systemEntityStart <= charNoConllFile and charNoConllFile < systemEntityEnd:
# if 'ner' in dict.keys(systemEntity):
# ner = systemEntity['ner']
# elif 'label' in dict.keys(systemEntity):
# ner = systemEntity['label']
# if 'text' in dict.keys(systemEntity):
# text = systemEntity['text']
# elif 'tokens' in dict.keys(systemEntity):
# text = systemEntity['tokens']
#
# if systemEntityNo > 0 and systemEntityNo < len(systemEntities):
# prevSystemEntity = systemEntities[systemEntityNo - 1]
# if system == 'ours':
# prevSystemEntity = prevSystemEntity[0]
# if 'ner' in dict.keys(prevSystemEntity):
# prevNer = prevSystemEntity['ner']
# elif 'label' in dict.keys(prevSystemEntity):
# prevNer = prevSystemEntity['label']
# if prevNer == ner:
# if systemEntityStart == prevSystemEntity['characterOffsetEnd'] + 1:
# if text.split(' ')[
# 0] == lineFirstTok: # if its the first token of this entity, because B- tag is only for beginning of entity (which is consecutive and having same type)
# consecutiveSameTypeEntities = True
#
# if ner.lower() == 'city' or ner.lower() == 'country' or ner.upper() == 'STATE_OR_PROVINCE': # this check added for stanford system
# ner = 'LOCATION'
# ner = ner[0] + ner[1] + ner[2] # getting just first 3 characters of ner i.e. loc, org and per
# ner = str.upper(ner)
# if consecutiveSameTypeEntities == False:
# ner = "I-" + ner
# else:
# ner = "B-" + ner
# consecutiveSameTypeEntities = False
#
# entities.append(ner)
# charNoConllFile = charNoConllFile + len(lineFirstTok) + 1
#
# if token matches in entity:
# ner = entity['ner']
#
# entities.append(ner)
# for ent1 in systemEntities:
# if system == 'ours':
# ent1 = ent1[0]
# if 'text' in dict.keys(ent1):
# text = ent1['text']
# elif 'tokens' in dict.keys(ent1):
# text = ent1['tokens']
# entTokCount1 += len(text.split(' '))
# for ent2 in entities:
# if ent2 != "O":
# entTokCount2 += 1
# if entTokCount2 != entTokCount1:
# print("docNo: " + str(docNo) + " , ENTITIES list is NOT CORRECTLY CREATED!!!!!!!!!!!!")
# print(entTokCount1)
# print(entTokCount2)
# print(entities)
# # break
# if len(conllEntities[docNo]) != len(entities):
# print("docNo: " + str(docNo) + " , ENTITIES list SIZE is NOT CORRECT!!!!!!!!!!!!")
# print(len(conllEntities[docNo]))
# print(len(entities))
# # break
# allEntities.append(entities)
# entities = []
# with open(outputFile, 'w', encoding='utf-8') as outF:
# json.dump(allEntities, outF, sort_keys=True, ensure_ascii=False)
def writeNERoutputFileOthers(system,trainOrEval):#for conll dataset, this writes the named entities of input file in format required for ner evaluation i.e. like this [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
if trainOrEval=='train':
inputFile = 'inputConll\conll2003.eng.train.txt' # CONLL Training DATASET #
elif trainOrEval == 'eval':
inputFile = 'inputConll\conll2003.eng.testb.txt' # CONLL EVALUATION DATASET
directory = 'outputConll\\'+trainOrEval+'\\'
conllEntitiesFile = 'outputConll\\'+trainOrEval+'\conllEntities\\allEntities.txt' # CoNLL Entities file
if system=='ours':
directory = directory + 'hmariEntities\\allEntities\\'
inputFile2Dir = directory + '\\output'
outputFile = directory + '\\allEntities.txt' #
elif system=='illinois':
directory = directory + 'illinois\\miscRemoved\\allEntities\\'
inputFile2Dir = directory + '\\outputIllinois'
outputFile = directory + '\\allEntities.txt'
elif system=='stanford':
directory = directory + 'stanford\\cleaned\\miscRemoved\\allEntities\\'
inputFile2Dir = directory + '\\outputNER'
outputFile = directory + '\\allEntities.txt'
allEntities = []
entities = []
conllEntitiesF = io.open(conllEntitiesFile,'r',encoding='utf-8',errors='ignore')
conllEntities = json.load(conllEntitiesF)
conllEntitiesF.close()
with open(inputFile, 'r', encoding='utf-8', errors='ignore') as inF:
# inputData = inF.read()
docNo = -1
inF2 = None
systemEntityNo = 0
charNoConllFile = -1 #this keeps track of the character no being read in the conll dataset file
systemEntityEnd = 0
consecutiveSameTypeEntities = False
for tokNo,line in enumerate(inF):
ner = "O"
if (line.find('-DOCSTART-') == -1 and line.find('-DOCEND-') == -1): # within a doc
# if docNo<13: continue
# if systemEntityNo==7:
# print()
if line != '\n':
line = line.split('\n')[0]
x = line.split(' ')
lineFirstTok = x[0] # first token of a line of conll dataset i.e. the token
if charNoConllFile > systemEntityEnd:
systemEntityNo += 1
if systemEntityNo<len(systemEntities):
systemEntity = systemEntities[systemEntityNo]
if system=='ours':
# print(line)
systemEntity = systemEntity[0]
systemEntityStart = systemEntity['characterOffsetBegin']
systemEntityEnd = systemEntity['characterOffsetEnd']
if systemEntityStart<=charNoConllFile and charNoConllFile<systemEntityEnd:
if 'ner' in dict.keys(systemEntity):
ner = systemEntity['ner']
elif 'label' in dict.keys(systemEntity):
ner = systemEntity['label']
if 'text' in dict.keys(systemEntity):
text = systemEntity['text']
elif 'tokens' in dict.keys(systemEntity):
text = systemEntity['tokens']
if systemEntityNo>0 and systemEntityNo<len(systemEntities):
prevSystemEntity = systemEntities[systemEntityNo-1]
if system=='ours':
prevSystemEntity = prevSystemEntity[0]
if 'ner' in dict.keys(prevSystemEntity):
prevNer = prevSystemEntity['ner']
elif 'label' in dict.keys(prevSystemEntity):
prevNer = prevSystemEntity['label']
if prevNer==ner:
if systemEntityStart == prevSystemEntity['characterOffsetEnd']+1:
if text.split(' ')[0] == lineFirstTok: #if its the first token of this entity, because B- tag is only for beginning of entity (which is consecutive and having same type)
consecutiveSameTypeEntities = True
if ner.lower()=='city' or ner.lower()=='country' or ner.upper()=='STATE_OR_PROVINCE' :#this check added for stanford system
ner = 'LOCATION'
ner = ner[0] + ner[1] + ner[2] # getting just first 3 characters of ner i.e. loc, org and per
ner = str.upper(ner)
if consecutiveSameTypeEntities==False:
ner = "I-"+ner
else:
ner = "B-"+ner
consecutiveSameTypeEntities = False
entities.append(ner)
charNoConllFile = charNoConllFile + len(lineFirstTok) + 1
else:
charNoConllFile = charNoConllFile + 1
elif (line.find('-DOCSTART-') != -1 or line.find('-DOCEND-') != -1): # start of next doc
if docNo >= 0: #for things that should not be done before first doc
#check that the entities list is correct
entTokCount1 = entTokCount2 = 0
for ent1 in systemEntities:
if system == 'ours':
ent1 = ent1[0]
if 'text' in dict.keys(ent1):
text = ent1['text']
elif 'tokens' in dict.keys(ent1):
text = ent1['tokens']
entTokCount1 += len(text.split(' '))
for ent2 in entities:
if ent2!="O":
entTokCount2 +=1
if entTokCount2!=entTokCount1:
print("docNo: "+str(docNo)+" , ENTITIES list is NOT CORRECTLY CREATED!!!!!!!!!!!!")
print(entTokCount1)
print(entTokCount2)
print(entities)
# break
if len(conllEntities[docNo]) != len(entities):
print("docNo: " + str(docNo) + " , ENTITIES list SIZE is NOT CORRECT!!!!!!!!!!!!")
print(len(conllEntities[docNo]))
print(len(entities))
# break
allEntities.append(entities)
if inF2!=None:
inF2.close()
charNoConllFile = 0
consecutiveSameTypeEntities = False
systemEntityNo = 0
if docNo+1 < len(conllEntities):
docNo += 1
entities = []
inputFile2 = inputFile2Dir + str(docNo) + '.txt' #
inF2 = io.open(inputFile2, 'r', encoding='utf-8', errors='ignore')
systemEntities = json.load(inF2)
with open(outputFile, 'w', encoding='utf-8') as outF:
json.dump(allEntities, outF, sort_keys=True, ensure_ascii=False)
#conll dataset uses IOB1 tagging scheme #this evaluates ner systems using seqeval
def evaluateNER(system,trainOrEval,dataset):#PRE-REQUISITE: FIRST CHECK THAT THE VARIABLE "directory" IS UPDATED
if dataset=='conll':
directory = 'outputConll\\' + trainOrEval + '\\'
datasetEntitiesFile = 'outputConll\\' + trainOrEval + '\conllEntities\\conllppAllEntities.txt' # Corrected CoNLL Entities file
# datasetEntitiesFile = 'outputConll\\' + trainOrEval + '\conllEntities\\allEntities.txt' # CoNLL Entities file
if system == 'ours':
directory = directory + 'hmariEntities\\allEntities\\'
systemFile = directory + '\\allEntities.txt'
elif system == 'illinois':
directory = directory + 'illinois\\miscRemoved\\allEntities\\'
systemFile = directory + '\\allEntities.txt'
elif system == 'stanford':
directory = directory + 'stanford\\cleaned\\miscRemoved\\allEntities\\'
systemFile = directory + '\\allEntities.txt'
elif system == 'luke':
datasetEntitiesFile = 'outputConll/eval/conllEntities/allEntitiesIn1.txt' # CoNLL Entities file
# datasetEntitiesFile = 'outputConll/eval/conllEntities/conllppAllEntitiesIn1.txt' # Corrected CoNLL Entities file
systemFile = 'outputConll/eval/luke/allEntities.txt'
elif dataset=='oke':
directory = 'outputOKE\\' + trainOrEval + '\\' #
datasetEntitiesFile = 'outputOKE\\' + trainOrEval +'\okeEntitiesCorrected\withoutGender\\allEntities2.txt' # OKE Entities file
# datasetEntitiesFile = 'outputOKE\\' + trainOrEval +'\okeEntitiesCorrected\withGender\\allEntities.txt' # OKE Entities file with gender
if system == 'ours':
# directory = directory +'\okeEntitiesCorrected\genderAnnotationsByCustNER+DictLookup'# # THIS NEEDS TO BE UPDATED EVERYTIME ACCORDINGLY
directory = directory +'hmariEntities\\allEntities'# # THIS NEEDS TO BE UPDATED EVERYTIME ACCORDINGLY
if system == 'trainedNer':
directory = directory + '\\trainedNER\\trainOnOriginalEvalOnCorrected'
systemFile = directory + '\\allEntities2.txt'
with open(datasetEntitiesFile, 'r', encoding='utf-8', errors='ignore') as goldF, open(systemFile, 'r', encoding='utf-8', errors='ignore') as predF:
y_true = json.load(goldF) #[['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
y_pred = json.load(predF) #[['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
print(f1_score(y_true, y_pred))
print(classification_report(y_true, y_pred, digits=4))
def writeCoNLLentities(trainOrEval):#
# trainOrEval=1=train, trainOrEval=2=eval
#pre processing
if trainOrEval==1:#train
datasetFile = 'inputConll\conll2003.eng.train.txt' #CONLL Training DATASET
outFilePath = 'outputConll\\train\conllEntities\doc' #CoNLL Entities file path
elif trainOrEval==2:#eval
datasetFile = 'inputConll\conll2003.eng.testb.txt' #CONLL EVALUATION DATASET
outFilePath = 'outputConll\eval\conllEntities\doc' #CoNLL Entities file path
print("Output file path: "+outFilePath)
f = io.open(datasetFile, 'r', encoding='utf-8')
docNo = -1
prevLineLastTok = 'O'
e1OffsetBegin = e2OffsetBegin = e1OffsetEnd = -1
eText = prevEText = ''
newEntity = True
entities = []
for line in f: # read the file one line at a time using for loop
if (line.find('-DOCSTART-')==-1 and line.find('-DOCEND-')==-1): #within a doc
if line != '\n':
line = line.split('\n')[0]
offsetBegin = offsetConll
# print(line)
x = line.split(' ')
lineFirstTok = x[0] #first token of a line of conll dataset i.e. the token
lineLastTok = x[len(x)-1] #last token of a line of conll dataset i.e. the ner type
offsetConll += len(lineFirstTok)
offsetEnd = offsetConll
if line !='\n':
offsetConll += 1
if prevLineLastTok.startswith("B-") and lineLastTok.startswith("I-"): # if its not a new entity
x = prevLineLastTok.strip("B-")
y = lineLastTok.strip("I-")
if x == y:
newEntity = False
elif lineLastTok != prevLineLastTok and line!='\n':
newEntity = True
if lineLastTok != prevLineLastTok and line!='\n' and newEntity==True: #if its a new entity
newEntity = True
entity = {}
eText = eText.split('\n')[0]
prevEText = eText
eText = lineFirstTok
if prevLineLastTok.find('PER') != -1 or prevLineLastTok.find('LOC') != -1 or prevLineLastTok.find('ORG') != -1: # if previous was an entity
e1Ner = prevLineLastTok # previous entity's ner
e1OffsetEnd = offsetBegin - 1 # previous entity's end offset
e1OffsetBegin = e2OffsetBegin # previous entity's begin offset
if prevLineEmpty==True:
e1OffsetEnd -= 1
entity['characterOffsetBegin'] = e1OffsetBegin
entity['characterOffsetEnd'] = e1OffsetEnd
entity['ner'] = e1Ner.split('-')[1]
prevEText = str.strip(prevEText)
entity['text'] = prevEText
entities.append(entity)
if lineLastTok.find('PER')!=-1 or lineLastTok.find('LOC')!=-1 or lineLastTok.find('ORG')!=-1: # if its an entity
e2Ner = lineLastTok #this entity's ner
e2OffsetBegin = offsetBegin #this entity's begin offset
else:
eText = eText + " " + lineFirstTok
if line!='\n':
prevLineLastTok = lineLastTok # last token of previous line
prevLineEmpty = False
else:
prevLineEmpty = True
elif (line.find('-DOCSTART-')!=-1 or line.find('-DOCEND-')!=-1): #start of next doc
if docNo>=0:
outFile = outFilePath + str(docNo) + '.txt'
with open(outFile, 'w', encoding='utf-8') as outfile:
json.dump(entities, outfile, sort_keys=True, indent=4, ensure_ascii=False)
offsetConll = -1
docNo += 1
print("\nDOCUMENT NO: "+ str(docNo) + "\n")
eText = prevEText = ''
lineLastTok = prevLineLastTok = 'O'
e1OffsetBegin = e2OffsetBegin = e1OffsetEnd = -1
# print("start of next doc: "+str(docNo))
flag = False
newEntity = True
entities=[]
def removeMISCentities(trainOrEval,system,okeOrConll):
# trainOrEval=1=train, trainOrEval=2=eval
# system: 1 for Illinois, 2 for Stanford
# okeOrConll: 1=oke, 2=conll
if trainOrEval == 1: # train
subDir = "\\train"
elif trainOrEval == 2: # eval
subDir = "\eval"
if system == 1:
annotator = "\illinois\\"
key = 'label'
outputFile = 'outputIllinois'
elif system == 2:
annotator = "\\ner\cleaned\\"
key = 'ner'
outputFile = 'outputNER'
if okeOrConll == 1: # oke
dir = "outputOKE"
elif okeOrConll == 2: # conll
dir = "outputConll"
filePath = dir+subDir+annotator #Entities file path
print("Output file path: " + filePath+"miscRemoved\\")
entities = []
for filename in os.listdir(filePath):
if filename.endswith('.txt'):
readFile = filePath+filename
writeFile = filePath+"miscRemoved\\"+filename
with open(readFile, 'r', encoding='utf-8', errors='ignore') as inF:
entities = json.load(inF)
newEntities = entities.copy()
for e in entities:
if system == 1:#illinois
if e[key]=='MISC':
newEntities.remove(e)
elif system == 2:#stanford ner
if not(e[key].startswith('PER')or e[key].startswith('LOC')or e[key].startswith('CITY')or e[key].startswith('COUNTRY') or e[key].startswith('STATE_OR_PROVINCE') or e[key].startswith('ORG')):
newEntities.remove(e)
with open(writeFile, 'w', encoding='utf-8', errors='ignore') as outF:
json.dump(newEntities, outF, sort_keys=True, indent=4, ensure_ascii=False)
def compareCoNLL(trainOrEval,flagE4):#
# trainOrEval=1=train, trainOrEval=2=eval
# flagE4 is 1 normally, 0 for conll exp4 i.e. highest preference to illinois
#pre processing
if trainOrEval==1:#train
datasetFile = 'inputConll\conll2003.eng.train.txt' #CONLL Training DATASET
if flagE4==1:
hmariFilePath = 'outputConll\\train\hmariEntities\output' #HmaraNER
resultFile = 'results\ComparisonResultsOnTrainDataCoNLL.txt' # HmaraNER
elif flagE4==0:
hmariFilePath = 'outputConll\\train\hmariEntities\exp4\output' #HmaraNER
resultFile = 'results\ComparisonResultsExp4OnTrainDataCoNLL.txt' #HmaraNER
illinoisFilePath = 'outputConll\\train\illinois\outputIllinois' #Illinois
stanfordFilePath = 'outputConll\\train\\ner\cleaned\outputNER' #Stanford
elif trainOrEval==2:#eval
datasetFile = 'inputConll\conll2003.eng.testb.txt' #CONLL EVALUATION DATASET
if flagE4 == 1:
hmariFilePath = 'outputConll\eval\hmariEntities\output' #HmaraNER
resultFile = 'results\ComparisonResultsOnTrainDataCoNLL.txt' # HmaraNER
elif flagE4 == 0:
hmariFilePath = 'outputConll\eval\hmariEntities\exp4\output' #HmaraNER
resultFile = 'results\ComparisonResultsExp4OnEvalDataCoNLL.txt' #HmaraNER
illinoisFilePath = 'outputConll\eval\illinois\outputIllinois' # Illinois
stanfordFilePath = 'outputConll\eval\\ner\cleaned\outputNER' # Stanford
print("Output file: "+resultFile)
noOfDatasetEntities = 0 # the total no of entities in training/evaluation dataset
noOfDatasetPerEntities = 0 # the total no of PERSON entities in training/evaluation dataset
noOfDatasetLocEntities = 0 # the total no of LOCATION entities in training/evaluation dataset
noOfDatasetOrgEntities = 0 # the total no of ORGANIZATION entities in training/evaluation dataset
hpCount=0; hnCount=0; ipCount=0; inCount=0
f = io.open(datasetFile, 'r', encoding='utf-8')
f2 = open(resultFile, "w+")
docNo = -1
prevLineLastTok = 'O'
e1OffsetBegin = e2OffsetBegin = e1OffsetEnd = -1
eText = prevEText = ''
newEntity = True
for line in f: # read the file one line at a time using for loop
if (line.find('-DOCSTART-')==-1 and line.find('-DOCEND-')==-1): #within a doc
if line != '\n':
line = line.split('\n')[0]
offsetBegin = offsetConll
# print(line)
x = line.split(' ')
lineFirstTok = x[0] #first token of a line of conll dataset
lineLastTok = x[len(x)-1] #last token of a line of conll dataset
offsetConll += len(lineFirstTok)
offsetEnd = offsetConll
if line !='\n':
offsetConll += 1
if hmariEntityNo < len(hmariEntities):
hmariEntity = hmariEntities[hmariEntityNo][0] #for HmaraNER
if illinoisEntityNo < len(illinoisEntities):
illinoisEntity = illinoisEntities[illinoisEntityNo] # for Illinois
illinoisEntity['ner'] = illinoisEntity['label'] # for Illinois
illinoisEntity['text'] = illinoisEntity['tokens'] # for Illinois
# if stanfordEntityNo < len(stanfordEntities):
# stanfordEntity = stanfordEntities[stanfordEntityNo] # for Stanford
# if stanfordEntity['ner'] == 'CITY' or stanfordEntity['ner'] == 'STATE_OR_PROVINCE' or stanfordEntity['ner'] == 'COUNTRY':
# stanfordEntity['ner'] = 'LOCATION'
#if its not per/loc/org entity e.g misc in case of illinois
while flag==False and (not(str.startswith(illinoisEntity['ner'],'PER')) and not(str.startswith(illinoisEntity['ner'],'LOC')) and not(str.startswith(illinoisEntity['ner'],'ORG'))) :
illinoisEntityNo +=1
if illinoisEntityNo < len(illinoisEntities):
illinoisEntity = illinoisEntities[illinoisEntityNo] # for Illinois
illinoisEntity['ner'] = illinoisEntity['label']
illinoisEntity['text'] = illinoisEntity['tokens']
elif illinoisEntityNo >= len(illinoisEntities):#if its the last entity and is not ppo type
flag = True
continue
# flag = False
# # if its not per/loc/org entity e.g date title etc in case of stanford
# while flag == False and (not (str.startswith(stanfordEntity['ner'], 'PER')) and not (
# str.startswith(stanfordEntity['ner'], 'LOC')) and not (
# str.startswith(stanfordEntity['ner'], 'ORG'))):
# stanfordEntityNo += 1
# if stanfordEntityNo < len(stanfordEntities):
# stanfordEntity = stanfordEntities[stanfordEntityNo] # for Stanford
# if stanfordEntity['ner'] == 'CITY' or stanfordEntity['ner'] == 'STATE_OR_PROVINCE' or \
# stanfordEntity['ner'] == 'COUNTRY':
# stanfordEntity['ner'] = 'LOCATION'
# elif stanfordEntityNo >= len(stanfordEntities): # if its the last entity and is not ppo type
# flag = True
# continue
if prevLineLastTok.startswith("B-") and lineLastTok.startswith("I-"): # if its not a new entity
x = prevLineLastTok.strip("B-")
y = lineLastTok.strip("I-")
if x == y:
newEntity = False
if lineLastTok != prevLineLastTok and line!='\n' and newEntity==True: #if its a new entity
newEntity = True
eText = eText.split('\n')[0]
prevEText = eText
eText = lineFirstTok
if prevLineLastTok.find('PER') != -1 or prevLineLastTok.find('LOC') != -1 or prevLineLastTok.find('ORG') != -1: # if previous was an entity
e1Ner = prevLineLastTok # previous entity's ner
e1OffsetEnd = offsetBegin - 1 # previous entity's end offset
e1OffsetBegin = e2OffsetBegin # previous entity's begin offset
if prevLineEmpty==True:
e1OffsetEnd -= 1
if lineLastTok.find('PER')!=-1 or lineLastTok.find('LOC')!=-1 or lineLastTok.find('ORG')!=-1: # if its an entity
noOfDatasetEntities += 1
e2Ner = lineLastTok #this entity's ner
e2OffsetBegin = offsetBegin #this entity's begin offset
if lineLastTok.find('PER')!=-1: #if this entity is tagged person
noOfDatasetPerEntities += 1
elif lineLastTok.find('LOC')!=-1: #if this entity is tagged location
noOfDatasetLocEntities += 1
elif lineLastTok.find('ORG')!=-1: #if this entity is tagged organization
noOfDatasetOrgEntities += 1
else:
eText = eText + " " + lineFirstTok
if e1OffsetBegin != -1:
offsetRangeDataset = range(e1OffsetBegin,e1OffsetEnd)
offsetRangeHmari = range(hmariEntity['characterOffsetBegin'], hmariEntity['characterOffsetEnd'])
offsetRangeIllinois = range(illinoisEntity['characterOffsetBegin'], illinoisEntity['characterOffsetEnd'])
# offsetRangeStanford = range(stanfordEntity['characterOffsetBegin'], stanfordEntity['characterOffsetEnd'])
offsetRangesOverlapHmari = [i for i in offsetRangeDataset if i in offsetRangeHmari]
offsetRangesOverlapIllinois = [i for i in offsetRangeDataset if i in offsetRangeIllinois]
# offsetRangesOverlapStanford = [i for i in offsetRangeDataset if i in offsetRangeStanford]
e1OffsetBegin2 = e1OffsetBegin #this is to back up e1OffsetBegin as it will change in following if block and is yet needed in next if block
# print("e:\t\t" + str(e1OffsetBegin) + "\t" + str(e1OffsetEnd))
# print("hmari:\t" + str(hmariEntity['characterOffsetBegin']) + "\t" + str(hmariEntity['characterOffsetEnd']))
if len(offsetRangesOverlapHmari) > 0 or len(offsetRangesOverlapIllinois) > 0:# or len(offsetRangesOverlapStanford) > 0 :
datasetEntityNo += 1
e1OffsetBegin = -1
if len(offsetRangesOverlapHmari) > 0 and hmariEntityNo < len(hmariEntities):
hmariEntityNo += 1
# following code is added for STRONG annotation
if e1OffsetBegin2 == hmariEntity['characterOffsetBegin'] and e1OffsetEnd == hmariEntity['characterOffsetEnd'] and hmariEntityNo <= len(hmariEntities):
# CASE 1: offsets match exactly
sth=1
elif len(offsetRangesOverlapHmari) > 0 and hmariEntityNo < len(hmariEntities):
# CASE 2: offsets match partially i.e. they overlap
hpCount+=1
hnCount+=1
f2.write("HmaraNER FP: " + hmariEntity['text'] + "\t" + str(
hmariEntity['characterOffsetBegin']) + "\t" + str(
hmariEntity['characterOffsetEnd']) + "\t" + hmariEntity['ner']+ "\n")
f2.write("HmaraNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
else:
if (hmariEntity['characterOffsetBegin'] > e1OffsetEnd) or (hmariEntityNo >= len(hmariEntities)):
f2.write("HmaraNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
hnCount += 1
datasetEntityNo += 1
e1OffsetBegin = -1
elif (e1OffsetBegin2 > hmariEntity['characterOffsetEnd']):
hmariEntityNo += 1
hpCount += 1
f2.write("HmaraNER FP: " + hmariEntity['text'] + "\t" + str(
hmariEntity['characterOffsetBegin']) + "\t" + str(
hmariEntity['characterOffsetEnd']) + "\t" + hmariEntity['ner']+ "\n")
if len(offsetRangesOverlapIllinois) > 0 and illinoisEntityNo < len(illinoisEntities):
illinoisEntityNo += 1
if e1OffsetBegin2 == illinoisEntity['characterOffsetBegin'] and e1OffsetEnd == illinoisEntity['characterOffsetEnd'] and illinoisEntityNo <= len(illinoisEntities):
# CASE 1: offsets match exactly
sth = 1
elif len(offsetRangesOverlapIllinois) > 0 and illinoisEntityNo < len(illinoisEntities):
# CASE 2: offsets match partially i.e. they overlap
ipCount += 1
inCount += 1
f2.write("IllinoisNER FP: " + illinoisEntity['text'] + "\t" + str(
illinoisEntity['characterOffsetBegin']) + "\t" + str(
illinoisEntity['characterOffsetEnd']) + "\t" + illinoisEntity['ner']+ "\n")
f2.write("IllinoisNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
else:
if (illinoisEntity['characterOffsetBegin'] > e1OffsetEnd) or (illinoisEntityNo >= len(illinoisEntities)):
inCount+=1
f2.write("IllinoisNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
datasetEntityNo += 1
e1OffsetBegin = -1
elif (e1OffsetBegin2 > illinoisEntity['characterOffsetEnd']):
illinoisEntityNo += 1
ipCount+=1
f2.write("IllinoisNER FP: " + illinoisEntity['text'] + "\t" + str(
illinoisEntity['characterOffsetBegin']) + "\t" + str(
illinoisEntity['characterOffsetEnd']) + "\t" + illinoisEntity['ner']+ "\n")
# if len(offsetRangesOverlapStanford) > 0 and stanfordEntityNo < len(stanfordEntities):
# stanfordEntityNo += 1
# if e1OffsetBegin2 == stanfordEntity['characterOffsetBegin'] and e1OffsetEnd == stanfordEntity['characterOffsetEnd'] and stanfordEntityNo <= len(stanfordEntities):
# # CASE 1: offsets match exactly
# sth = 1
# elif len(offsetRangesOverlapStanford) > 0 and stanfordEntityNo < len(stanfordEntities):
# # CASE 2: offsets match partially i.e. they overlap
# f2.write("StanfordNER FP: " + stanfordEntity['text'] + "\t" + str(
# stanfordEntity['characterOffsetBegin']) + "\t" + str(
# stanfordEntity['characterOffsetEnd']) + "\t" + stanfordEntity['ner']+ "\n")
# f2.write("StanfordNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
# else:
# if (stanfordEntity['characterOffsetBegin'] > e1OffsetEnd) or (stanfordEntityNo >= len(stanfordEntities)):
# f2.write("StanfordNER FN e: " + prevEText + '\t' + str(e1OffsetEnd) + "\t" + e1Ner+ "\n")
# datasetEntityNo += 1
# e1OffsetBegin = -1
# elif (e1OffsetBegin2 > stanfordEntity['characterOffsetEnd']):
# stanfordEntityNo += 1
# f2.write("StanfordNER FP: " + stanfordEntity['text'] + "\t" + str(
# stanfordEntity['characterOffsetBegin']) + "\t" + str(
# stanfordEntity['characterOffsetEnd']) + "\t" + stanfordEntity['ner']+ "\n")
if line!='\n':
prevLineLastTok = lineLastTok # last token of previous line
prevLineEmpty = False
else:
prevLineEmpty = True
elif (line.find('-DOCSTART-')!=-1 or line.find('-DOCEND-')!=-1): #start of next doc
if hnCount!=inCount:
f2.write(str(hnCount) + "\t" + str(inCount))
docNo += 1
f2.write("\nDOCUMENT NO: "+ str(docNo) + "\n")
eText = prevEText = ''
lineLastTok = prevLineLastTok = 'O'
e1OffsetBegin = e2OffsetBegin = e1OffsetEnd = -1
# print("start of next doc: "+str(docNo))
flag = False
newEntity = True
if docNo>-1 and docNo<946:
hmariFile = hmariFilePath + str(docNo) + '.txt'
illinoisFile = illinoisFilePath + str(docNo) + '.txt'
# stanfordFile = stanfordFilePath + str(docNo) + '.txt'
with open(hmariFile, 'r', encoding='utf-8', errors='ignore') as outfile2:
hmariEntities = json.load(outfile2) # hmaraNER output file loaded as json dictionary
with open(illinoisFile, 'r', encoding='utf-8', errors='ignore') as outfile3:
illinoisEntities = json.load(outfile3) # illonois NER output file loaded as json dictionary
# with open(stanfordFile, 'r', encoding='utf-8', errors='ignore') as outfile4:
# stanfordEntities = json.load(outfile4) # stanford NER output file loaded as json dictionary
hmariEntityNo = 0
illinoisEntityNo = 0
# stanfordEntityNo = 0
datasetEntityNo = 0
offsetConll = -1
# if docNo==39:
# print()
print(str(hpCount)+"\t"+str(ipCount))
print(str(hnCount) + "\t" + str(inCount))
def evaluateCoNLL(trainOrEval,system, flagE4):#
# trainOrEval=1=train, trainOrEval=2=eval
# system: the system for evaluation, 0=HmaraNER, 1 for Illinois, 2 for Stanford
# flagE4 is 1 normally, 0 for conll exp4 i.e. highest preference to illinois
if system==0:
annotator = "HmaraNER"
elif system==1:
annotator = "IllinoisNER"
elif system==2:
annotator = "StanfordNER"
#pre processing
if trainOrEval==1:#train
sizeOfDataset=946
datasetFilePath = 'outputConll\\train\conllEntities\doc' # CONLL TRAINING DATASET FILES' path
if system==0:#HmaraNER
if flagE4==1:
hmariFilePath = 'outputConll\\train\hmariEntities\\allEntities\output' #HmaraNER
mistakesFilePath = 'outputConll\\train\hmariEntities\mistakes\output' #HmaraNER
resultFile = 'results\hmarayResultsOnTrainDataCoNLL.txt' # HmaraNER
elif flagE4==0:
hmariFilePath = 'outputConll\\train\hmariEntities\exp4\\r7\output' #HmaraNER
# hmariFilePath = 'outputConll\\train\hmariEntities\exp4\output' #HmaraNER
resultFile = 'results\Exp4 rules\\r7Exp4hmarayResultsOnTrainDataCoNLL.txt' # HmaraNER
# resultFile = 'results\Exp4hmarayResultsOnTrainDataCoNLL.txt' # HmaraNER
elif system == 1:#Illinois
hmariFilePath = 'outputConll\\train\illinois\miscRemoved\\allEntities\outputIllinois' # 1: Illinois
mistakesFilePath = 'outputConll\\train\illinois\miscRemoved\mistakes\outputIllinois' # 1: Illinois
resultFile = 'results\illinoisResultsOnTrainDataCoNLL.txt' # 2: Illinois
elif system == 2:#Stanford
hmariFilePath = 'outputConll\\train\\ner\cleaned\miscRemoved\\allEntities\outputNER' # 1: Stanford
mistakesFilePath = 'outputConll\\train\\ner\cleaned\miscRemoved\mistakes\outputNER' # 1: Stanford
resultFile = 'results\stanfordResultsOnTrainDataCoNLL.txt' # 2: Stanford
elif trainOrEval==2:#eval
sizeOfDataset=231
datasetFilePath = 'outputConll\eval\conllEntities\doc' #CONLL EVALUATION DATASET FILES' path
if system == 0:#HmaraNER
if flagE4 == 1:
hmariFilePath = 'outputConll\eval\hmariEntities\\allEntities\output' #HmaraNER
mistakesFilePath = 'outputConll\eval\hmariEntities\mistakes\output' #HmaraNER
resultFile = 'results\hmarayResultsOnEvalDataCoNLL.txt' #HmaraNER
elif flagE4 == 0:
hmariFilePath = 'outputConll\eval\hmariEntities\exp4\output' # HmaraNER
resultFile = 'results\Exp4hmarayResultsOnEvalDataCoNLL.txt' #HmaraNER
elif system == 1:#Illinois
hmariFilePath = 'outputConll\eval\illinois\miscRemoved\\allEntities\outputIllinois' # 1: Illinois
mistakesFilePath = 'outputConll\eval\illinois\miscRemoved\mistakes\outputIllinois' # 1: Illinois
resultFile = 'results\illinoisResultsOnEvalDataCoNLL.txt' # 2: Illinois
elif system == 2:#Stanford
hmariFilePath = 'outputConll\eval\\ner\cleaned\miscRemoved\\allEntities\outputNER' # 1: Stanford
mistakesFilePath = 'outputConll\eval\\ner\cleaned\miscRemoved\mistakes\outputNER' # 1: Stanford
resultFile = 'results\StanfordResultsOnEvalDataCoNLL.txt' # 2: Stanford
print("Output file: "+resultFile)
print("Output Mistakes file path: "+mistakesFilePath)
#evaluation script starts here
#following variables are for weak annotation
truePositives = 0; perTP = 0; locTP = 0; orgTP = 0
falsePositives = 0; perFP = 0; locFP = 0; orgFP = 0
falseNegatives = 0; perFN = 0; locFN = 0; orgFN = 0
# following variables are for strong annotation
struePositives = 0; sperTP = 0; slocTP = 0; sorgTP = 0
sfalsePositives = 0; sperFP = 0; slocFP = 0; sorgFP = 0
sfalseNegatives = 0; sperFN = 0; slocFN = 0; sorgFN = 0
sTPentitiesAll = []; sFPentitiesAll = []; sFNentitiesAll = []
noOfDatasetEntities = 0 #the total no of entities in training/evaluation dataset
noOfDatasetPerEntities = 0 #the total no of PERSON entities in training/evaluation dataset
noOfDatasetLocEntities = 0 #the total no of LOCATION entities in training/evaluation dataset
noOfDatasetOrgEntities = 0 #the total no of ORGANIZATION entities in training/evaluation dataset
for docNo in range(0, sizeOfDataset): #for each file/text
# if docNo<39:continue
sTPentities = []; sFPentities = []; sFNentities = []
if docNo-1>=0:
print("Doc No: " + str(docNo-1) + "\t\tTP: " + str(struePositives) + "\t\tFP: " + str(
sfalsePositives) + "\t\tFN: " + str(sfalseNegatives) + "\n\n")
datasetFile = datasetFilePath+str(docNo)+'.txt'
hmariFile = hmariFilePath+str(docNo)+'.txt' #HmaraNER output file
with open(datasetFile, 'r', encoding='utf-8', errors='ignore') as outfile:
datasetEntities = json.load(outfile) # dataset file of one sentence/doc/text loaded as json dictionary
with open(hmariFile, 'r', encoding='utf-8', errors='ignore') as outfile2:
hmariEntities = json.load(outfile2) # hmaraNER output file loaded as json dictionary
hmariEntityNo = 0
datasetEntityNo = 0
flag = False
flag2 = False
nextDatasetEntity = True
noOfDatasetEntities += len(datasetEntities)
while datasetEntityNo<len(datasetEntities) or hmariEntityNo<len(hmariEntities): #for each entity in file/text
if hmariEntityNo<len(hmariEntities):
if system==0:
hmariEntity = hmariEntities[hmariEntityNo][0] #For HmaraNER
else:
hmariEntity = hmariEntities[hmariEntityNo] #For Illinois/Stanford NER
if system == 1: # Illinois
hmariEntity['ner'] = hmariEntity['label'] # 4: for Illinois
hmariEntity['text'] = hmariEntity['tokens'] # 4: for Illinois
if system == 2: # Stanford
if hmariEntity['ner'] == 'CITY' or hmariEntity['ner'] == 'STATE_OR_PROVINCE' or hmariEntity['ner'] == 'COUNTRY':
hmariEntity['ner'] = 'LOCATION'
# if its not per/loc/org entity e.g misc in case of illinois, date title etc in case of stanford
while flag == False and (not (str.startswith(hmariEntity['ner'], 'PER')) and not (str.startswith(hmariEntity['ner'], 'LOC')) and not (str.startswith(hmariEntity['ner'], 'ORG'))):
hmariEntityNo += 1
if hmariEntityNo < len(hmariEntities):
if system == 0: # HmaraNER
hmariEntity = hmariEntities[hmariEntityNo][0] # for HmaraNER
elif system == 1 or system == 2: # Illinois or Stanford
hmariEntity = hmariEntities[hmariEntityNo] # 3: for Illinois or Stanford
if system == 1: # Illinois
hmariEntity['ner'] = hmariEntity['label'] # 4: for Illinois
hmariEntity['text'] = hmariEntity['tokens'] # 4: for Illinois
if system == 2: # Stanford
if hmariEntity['ner'] == 'CITY' or hmariEntity['ner'] == 'STATE_OR_PROVINCE' or \