-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathold_benchmark_and_evaluate.py
1497 lines (1295 loc) · 79 KB
/
old_benchmark_and_evaluate.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
# Benchmark imports
import pandas as pd # Import pandas library
import sys
from datasets import load_dataset
import fire
import torch
import transformers
import csv
from transformers import LlamaForCausalLM, LlamaTokenizer, GenerationConfig
import pickle
# alpaca-lora utils
from utils.callbacks import Iteratorize, Stream
from utils.prompter import Prompter
from tqdm import tqdm
# Evaluation imports
# import warnings filter
from warnings import simplefilter
from sklearn.exceptions import UndefinedMetricWarning
# ignore all UndefinedMetricWarning warnings
simplefilter(action='ignore', category=UndefinedMetricWarning)
#from bs4 import BeautifulSoup
import os
import regex as re
import itertools
import statistics
import sys
from nervaluate import Evaluator
import nltk
from nltk.util import ngrams
import string
from sklearn.metrics import precision_score, recall_score, f1_score
from sklearn import preprocessing
import json
import ast
import numpy as np
import timeit
device = "cuda"
currentpath = os.getcwd()
def benchmark(
model_path: str = "",
tok: str = "",
max_tokens: int = 1024,
dump: str = "output.pickle",
load_8bit: bool = False,
error: str = "errors0.txt",
prompt_template: str = "", # The prompt template to use, will default to alpaca.
csv_file: str = None, # New argument for CSV file
test: str = "UofA-LINGO/text_to_triplets_new_ins"
):
if model_path == "":
print("Enter the path to the model. (python benchmark_and_evaluate.py --model_path=/home/tsadler/models/vicuna-7b)")
exit()
prompter = Prompter(prompt_template)
print(f"Benchmarking model at: {model_path}")
print(f"Using tokenizer at (blank means model_path): {tok}")
# tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf")
# tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b")
tokenizer = None
if tok == "":
tokenizer = LlamaTokenizer.from_pretrained(model_path)
else:
tokenizer = LlamaTokenizer.from_pretrained(tok)
model = LlamaForCausalLM.from_pretrained(
#"/home/taesiri/src/alpaca-lora/vicuna-7b--based-export-text-to-triplets-explanation-v3/",
model_path,
load_in_8bit=load_8bit,
torch_dtype=torch.float16,
device_map="auto",
)
model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
model.config.bos_token_id = 1
model.config.eos_token_id = 2
if not load_8bit:
model.half() # seems to fix bugs for some users.
model.eval()
if torch.__version__ >= "2" and sys.platform != "win32":
model = torch.compile(model)
def evaluate(
instruction,
input=None,
error="errors0.txt",
temperature=0.1,
top_p=0.75,
top_k=40,
num_beams=4,
max_new_tokens=max_tokens,
stream_output=False,
**kwargs,
):
prompt = prompter.generate_prompt(instruction, input)
#print(prompt)
inputs = tokenizer(prompt, return_tensors="pt")
input_ids = inputs["input_ids"].to(device)
generation_config = GenerationConfig(
temperature=temperature,
top_p=top_p,
top_k=top_k,
num_beams=num_beams,
**kwargs,
)
# Was used to handle bugged autotrain model outputs, should be fixed for autotrain as long as default is not used to train.
eos_tokens = [tokenizer.eos_token_id, tokenizer.encode("### END")[-1]]#, tokenizer.encode("<s>")[-1]]
generate_params = {
"input_ids": input_ids,
"generation_config": generation_config,
"return_dict_in_generate": True,
"output_scores": True,
"max_new_tokens": max_new_tokens,
"eos_token_id": eos_tokens,
}
if stream_output:
# Stream the reply 1 token at a time.
# This is based on the trick of using 'stopping_criteria' to create an iterator,
# from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/text_generation.py#L216-L243.
def generate_with_callback(callback=None, **kwargs):
kwargs.setdefault(
"stopping_criteria", transformers.StoppingCriteriaList()
)
kwargs["stopping_criteria"].append(Stream(callback_func=callback))
with torch.no_grad():
model.generate(**kwargs)
def generate_with_streaming(**kwargs):
return Iteratorize(generate_with_callback, kwargs, callback=None)
with generate_with_streaming(**generate_params) as generator:
for output in generator:
decoded_output = tokenizer.decode(output)
if output[-1] in [tokenizer.eos_token_id]:
break
yield prompter.get_response(decoded_output)
return # early return for stream_output
# Without streaming
with torch.no_grad():
try:
generation_output = model.generate(
input_ids=input_ids,
generation_config=generation_config,
return_dict_in_generate=True,
output_scores=True,
max_new_tokens=max_new_tokens,
eos_token_id=eos_tokens,
pad_token_id=0,
)
s = generation_output.sequences[0]
except ValueError as v:
with open(error, 'a') as f:
print(model_path, '\n', v, '\n', input, '\n', file=f)
s = torch.tensor([1,2])
output = tokenizer.decode(s)
#print(output)
yield prompter.get_response(output)
# dt = load_dataset("UofA-LINGO/text_to_triplets")
# dt = load_dataset("UofA-LINGO/text_to_triplets_new_ins")
# dt = load_dataset("UofA-LINGO/webnlg-test-cleaned")
dt = load_dataset(test)
output = {}
for i in tqdm(range(len(dt["test"]))):
entry = dt["test"][i]
output[i] = list(evaluate(entry["instruction"], entry["input"], error))
#print(output[i])
with open(dump, "wb") as handle:
pickle.dump(output, handle, protocol=pickle.HIGHEST_PROTOCOL)
# TSadler: Removing intermediate CSV file for combined code
# generate dataframe for the evaluation code
# dt = load_dataset("UofA-LINGO/text_to_triplets")
# dt = load_dataset("UofA-LINGO/text_to_triplets_new_ins")
# dt = load_dataset("UofA-LINGO/webnlg-test-cleaned")
dt = load_dataset(test)
df = pd.DataFrame(dt["test"])
df["gt"] = df["output"]
df = df.drop(columns=["output"])
df["model_output"] = [x[0] for x in output.values()]
return df
#df.to_csv("vicuna-7b-with-explanasion-correct.csv", index=False)
# dump df as pickle
#with open("vicuna-7b-with-explanasion-correct-df.pickle", "wb") as handle:
# pickle.dump(df, handle, protocol=pickle.HIGHEST_PROTOCOL)
def split_ignore_quotes_and_underscore(input_string):
input_string = input_string.replace(',_', '--PLACEHOLDER--')
pattern = r',(?=(?:[^"]*"[^"]*")*[^"]*$)(?![^"]*"[^"]*(?:"[^"]*"[^"]*)*$)'
input_string = re.split(pattern, input_string)
input_string = [x.replace('--PLACEHOLDER--', ',_') for x in input_string]
return input_string
def getCandsAndRefsFromCsv(df):
#df = pd.read_csv(filepath, header=0)
print(df.head())
allcand_ids = df.index.values
all_text = df['input'].values
all_cand_triples = []
all_ref_triples = []
for i in range(len(df)):
triples_str_cand = df['model_output'].values[i]
#DEBUG: print(triples_str_cand)
# Remove EOS token
triples_str_cand = triples_str_cand.replace('###', '')
triples_str_cand = triples_str_cand.replace('</s>', '')
triples_str_cand = triples_str_cand.replace('<|im_end|>', '')
#triples_cand = re.findall(r"'(.*?)'", triples_str_cand)
#triples_cand = re.findall(r"\((.*?)\)[<\n]", triples_str_cand)
# New style triples
triples_cand = triples_str_cand.strip().split('\n')
#DEBUG: print('\n')
#DEBUG: print(triples_cand)
# Old style triples
# exp_target = "Therefore, here is the answer in the correct format:"
# Check for explanation-based model:
# if triples_str_cand.find(exp_target) == -1:
# print("Found one with diff final answer prompt.")
# else:
# Only look at final output triples.
# triples_str_cand = triples_str_cand[triples_str_cand.find(exp_target)+len(exp_target):].strip()
# This looks for the form of '...|...|...', which we expect our triples to be in. This must be followed
# with a closing square bracket or comma to match to avoid edge cases such as the one below:
# ['prop's | pred | value's'] would match to -> ['s | pred | value'] without the [],].
#triples_cand_tmp = re.findall(r"'(.*?[|].*?[|].*?)'[],]", triples_str_cand)
#triples_cand = []
#for triple in triples_cand_tmp:
# triple = triple.split(' | ')
# triples_cand.append(f'({triple[0]}, {triple[1]}, {triple[2]})')
tmp = []
#if i == 3:
#exit(0)
for triple in triples_cand:
triple = triple.replace('("', '(')
if triple.count('"') % 2 == 1:
triple = triple.replace('")', ')')
#print(triple)
# For splitting on commas, but not those that are surrounded by quotes or those followed by an underscore. Used to properly format.
t = split_ignore_quotes_and_underscore(triple)
#print(t)
if len(t) == 3:
triple = f'{t[0].strip()} | {t[1].strip()} | {t[2].strip()}'
# Do not penalize the model for errors in splitting that cause empty strings
if triple == '':
continue
if triple == '<s>':
triple = '( | , | )'
# To prevent index errors later, pad incomplete triples with empty strings.
if len(triple.split(' | ')) < 3:
if len(triple.split(' | ')) == 1:
triple += ' | , | )'
elif len(triple.split(' | ')) == 2:
triple += ' | )'
if len(triple.split(' | ')) > 3:
print(triple)
print(triple.split(' | '))
else:
tmp.append(triple)
all_cand_triples.append(tmp)
triples_str_ref = df['gt'].values[i]
triples_ref = triples_str_ref.split('\n')
# Convert triples to new format, easier to compare later on than converting the other way
# for triple in ast.literal_eval("[" + triples_str_ref + "]")[0]:
# triple = triple.split(' | ')
# triples_ref.append(f'({triple[0]} | {triple[1]} | {triple[2]})')
#DEBUG: print(triples_str_ref)
#DEBUG: print(triples_ref)
all_ref_triples.append(triples_ref)
new_cand_list = []
for entry in all_cand_triples:
new_triples = []
for triple in entry:
# Split camel case words into multiple words.
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
# Tyler Sadler: Personally, I don't agree with replacing these. If we want the model to
# follow a consistent output structure, it should be evaluated on underscores vs spaces.
# Webnlg training data heavily weighted towards underscores, as that is the dbpedia convention.
# new_triple = re.sub(r'_', ' ', new_triple).lower()
# Multiple spaces to single space
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
# adjusttriple = new_triple.split(' | ')
# Removes bracketed terms, again I don't think this should run as it removes a potential source of
# disagreement between the model and ground truth.
# manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
# if manualmodified:
# adjusttriple[-1] = manualmodified.group(1)
# new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_cand_list.append(new_triples)
#DEBUG: print(new_cand_list)
new_ref_list = []
for entry in all_ref_triples:
new_triples = []
# Same rationale as above applied here to remove parts of this.
for triple in entry:
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
# new_triple = re.sub(r'_', ' ', new_triple).lower()
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
# adjusttriple = new_triple.split(' | ')
# manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
# if manualmodified:
# adjusttriple[-1] = manualmodified.group(1)
# new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_ref_list.append(new_triples)
return allcand_ids, all_text, all_cand_triples, new_cand_list, all_ref_triples, new_ref_list
def getRefs(filepath, allcand_ids):
with open(filepath, encoding='utf-8') as fp:
refssoup = None #BeautifulSoup(fp, 'lxml')
refsentries = refssoup.find('benchmark').find('entries').find_all('entry')
all_ref_triples = []
for index in allcand_ids:
id = int(index.split('Id')[1])-1
entry = refsentries[id]
entryreftriples = []
modtriplesref = entry.find('modifiedtripleset').find_all('mtriple')
for modtriple in modtriplesref:
entryreftriples.append(modtriple.text)
all_ref_triples.append(entryreftriples)
new_ref_list = []
for entry in all_ref_triples:
new_triples = []
for triple in entry:
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
new_triple = re.sub(r'_', ' ', new_triple).lower()
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
adjusttriple = new_triple.split(' | ')
manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
if manualmodified:
adjusttriple[-1] = manualmodified.group(1)
new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_ref_list.append(new_triples)
return all_ref_triples, new_ref_list
def getCandsFromRebelTsv(filepath):
df = pd.read_csv(filepath, sep='\t', header=0)
print(df.head())
# df = df[:10]
# df = df.sort_values(by=['id'])
# print(df.head())
# Get the triples for row with id 'Id770'
# Example of triples: [('Abraham A. Ribicoff', 'born in', 'United States'), ('United States', 'has ethnic group', 'African Americans')]
# triples_str_ref = df[df['id'] == 'Id770']['triples'].values[0]
# # Convert the triples string to a list of tuples
# triples = ast.literal_eval("[" + triples_str + "]")[0]
allcand_ids = df['id'].values
all_text = df['lexs'].values
# from IPython import embed; embed()
all_cand_triples = []
for i in range(len(df)):
# new_triples = []
triples_str = df['triples'].values[i]
triples = ast.literal_eval("[" + triples_str + "]")[0]
# for triple in triples:
# triple_str = triple[0] +' | ' + triple[1] +' | '+ triple[2]
# new_triples.append(triple_str)
all_cand_triples.append(triples)
new_cand_list = []
for entry in all_cand_triples:
new_triples = []
# triple 'Turn_Me_On_(album) | runtime | 35.1'
for triple in entry:
# triple_str = triple[0] +' | ' + triple[1] +' | '+ triple[2]
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
new_triple = re.sub(r'_', ' ', new_triple).lower()
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
adjusttriple = new_triple.split(' | ')
manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
if manualmodified:
adjusttriple[-1] = manualmodified.group(1)
new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_cand_list.append(new_triples)
return allcand_ids, all_text, all_cand_triples, new_cand_list
def getCandsFromTsv(filepath):
df = pd.read_csv(filepath, sep='\t', header=0)
print(df.head())
# df = df[:10]
# df = df.sort_values(by=['id'])
# print(df.head())
# Get the triples for row with id 'Id770'
# Example of triples: [('Abraham A. Ribicoff', 'born in', 'United States'), ('United States', 'has ethnic group', 'African Americans')]
# triples_str = df[df['id'] == 'Id770']['triples'].values[0]
# # Convert the triples string to a list of tuples
# triples = ast.literal_eval("[" + triples_str + "]")[0]
allcand_ids = df['id'].values
all_text = df['lexs'].values
# from IPython import embed; embed()
all_cand_triples = []
for i in range(len(df)):
new_triples = []
triples_str = df['triples'].values[i]
triples = ast.literal_eval("[" + triples_str + "]")[0]
for triple in triples:
triple_str = triple[0] +' | ' + triple[1] +' | '+ triple[2]
new_triples.append(triple_str)
all_cand_triples.append(new_triples)
new_cand_list = []
for entry in all_cand_triples:
new_triples = []
# triple 'Turn_Me_On_(album) | runtime | 35.1'
for triple in entry:
# triple_str = triple[0] +' | ' + triple[1] +' | '+ triple[2]
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
new_triple = re.sub(r'_', ' ', new_triple).lower()
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
adjusttriple = new_triple.split(' | ')
manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
if manualmodified:
adjusttriple[-1] = manualmodified.group(1)
new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_cand_list.append(new_triples)
return allcand_ids, all_text, all_cand_triples, new_cand_list
def getCands(filepath):
with open(filepath, encoding='utf-8') as fp:
candssoup = None #BeautifulSoup(fp, 'lxml')
candssentries = candssoup.find('benchmark').find('entries').find_all('entry')
all_cand_triples = []
for entry in candssentries:
entrycandtriples = []
modtriplescand = entry.find('generatedtripleset').find_all('gtriple')
for modtriple in modtriplescand:
entrycandtriples.append(modtriple.text)
all_cand_triples.append(entrycandtriples)
new_cand_list = []
for entry in all_cand_triples:
new_triples = []
for triple in entry:
new_triple = re.sub(r"([a-z])([A-Z])", "\g<1> \g<2>", triple).lower()
new_triple = re.sub(r'_', ' ', new_triple).lower()
new_triple = re.sub(r'\s+', ' ', new_triple).lower()
adjusttriple = new_triple.split(' | ')
manualmodified = re.search(r'^(.*?)(\s\((.*?)\))$', adjusttriple[-1])
if manualmodified:
adjusttriple[-1] = manualmodified.group(1)
new_triple = ' | '.join(adjusttriple)
new_triples.append(new_triple)
new_cand_list.append(new_triples)
return all_cand_triples, new_cand_list
def findSubList(sl,l):
sll=len(sl)
#DEBUG: print([i for i,e in enumerate(l) if e==sl[0]])
for ind in (i for i,e in enumerate(l) if e==sl[0]):
if l[ind:ind+sll]==sl:
return ind,ind+sll-1
#We are going to try to find matches with the reference, starting with the highest chunk possible (all the words in the reference).
#If we don't find that, we are going to search for all n-grams -1 the number of words in the reference; than -2; than -3; etc.
def nonRefWords(new_ref_list, new_cand_list, foundnum, ngram_length):
while ngram_length > 0:
#Get a list of all the ngrams of that size
ngram_list = list(ngrams(new_cand_list, ngram_length))
#DEBUG: print("Ngram:", ngram_list)
for ngram in ngram_list:
#If we find this ngram (in the same order) in the reference
#We're getting the start and end index of the ngram in the reference
find_new_ref = findSubList(list(ngram), new_ref_list)
if find_new_ref is not None:
#DEBUG: print("find_new_ref:", find_new_ref)
#And all the numbers in between
new_ref_index = list(range(find_new_ref[0], find_new_ref[1] + 1))
#Change the matched words to FOUNDREF-[FOUNDNUMBER]-[FOUNDINDEX]
for idx in new_ref_index:
new_ref_list[idx] = 'FOUNDREF-' + str(foundnum) + '-' + str(idx)
#Now find the start and end index of the ngram in the candidate as well
find_new_cand = findSubList(list(ngram), new_cand_list)
#And all the indices in between
new_cand_index = list(range(find_new_cand[0], find_new_cand[1]+1))
# Change the matched words to FOUNDCAND-[FOUNDNUMBER]-[REFERENCE-FOUNDINDEX]
for idx, val in enumerate(new_cand_index):
new_cand_list[val] = 'FOUNDCAND-' + str(foundnum) + '-' + str(new_ref_index[idx])
foundnum += 1
#And try to find new matches again
nonRefWords(new_ref_list, new_cand_list, foundnum, ngram_length)
#If no match is found, try to find matches for ngrams 1 smaller
ngram_length -= 1
#Return the new lists if all possible ngrams have been searched
return new_ref_list, new_cand_list
def getRefDict(new_ref_list, new_cand_list, triple_type_ref, triple_type_cand, baseidx):
try:
#If some match is found with the reference
first_found_idx = new_cand_list.index([i for i in new_cand_list if re.findall(r'^FOUNDCAND', i)][0])
candidate_found = True
except IndexError:
candidate_found = False
if candidate_found:
unlinked_list = []
before_list = []
after_list = []
#If the first found candidate match is also the first word in the reference
if new_cand_list[first_found_idx].endswith('-0'):
#Flag that some words can appear before the first match, and they are linked with the first candidate match
before_linked = True
first_cand = re.search(r'^(FOUNDCAND-\d+)-', new_cand_list[first_found_idx]).group(1)
else:
before_linked = False
last_found_idx = None
after_linked = False
#If there's more words after the last reference, link those to the last reference as well
#If the last reference word is linked, but the last candidate word is not, one criterion of linking the last words is met
if (new_ref_list[-1].startswith('FOUNDREF')) and (not new_cand_list[-1].startswith('FOUNDCAND')):
#If the last linked reference word is the last linked candidate word, the other criterion is also met.
last_found = [i for i in new_cand_list if re.findall(r'^FOUNDCAND', i)][-1]
cand_version = new_ref_list[-1].replace('FOUNDREF', 'FOUNDCAND')
if last_found == cand_version:
last_found_idx = new_cand_list.index([i for i in new_cand_list if re.findall(r'^FOUNDCAND', i)][-1])
after_linked = True
last_cand = re.search(r'^(FOUNDCAND-\d+)-', last_found).group(1)
#Ensure that all the not-found blocks are separated by giving them different unlink_numbers
unlink_number = 1
for idx, can in enumerate(new_cand_list):
if not can.startswith('FOUNDCAND'):
if (idx < first_found_idx) and before_linked:
new_cand_list[idx] = first_cand + '-LINKED'
before_list.append(first_cand + '-LINKED')
elif (last_found_idx != None) and (idx > last_found_idx) and after_linked:
new_cand_list[idx] = last_cand + '-LINKED'
after_list.append(last_cand + '-LINKED')
else:
unlinked_list.append('NOTFOUND-' + str(unlink_number))
else:
unlink_number += 1
total_list = before_list + new_ref_list + after_list + unlinked_list
ref_start = len(before_list)
ref_end = (len(before_list) + len(new_ref_list)) - 1
ref_dict_list = [{'label': triple_type_ref, 'start': baseidx + ref_start, 'end': baseidx + ref_end}]
total_list2 = [x.replace('FOUNDREF', 'FOUNDCAND') for x in total_list]
cand_dict_list = []
current_candidate = ''
beginidx = ''
endidx = ''
collecting = False
for idx, candidate in enumerate(total_list2):
if (candidate.startswith('FOUNDCAND')) or (candidate.startswith('NOTFOUND')):
collecting = True
curcan = re.search(r'^((.*?)-\d+)', candidate).group(1)
if curcan != current_candidate:
if current_candidate != '':
endidx = idx-1
cand_dict_list.append({'label': triple_type_cand, 'start': baseidx + beginidx, 'end': baseidx + endidx})
current_candidate = curcan
beginidx = idx
if idx == len(total_list2)-1:
endidx = idx
cand_dict_list.append({'label': triple_type_cand, 'start': baseidx + beginidx, 'end': baseidx + endidx})
else:
if collecting:
endidx = idx-1
cand_dict_list.append({'label': triple_type_cand, 'start': baseidx + beginidx, 'end': baseidx + endidx})
else:
if len(new_ref_list) == 0:
ref_dict_list = []
cand_dict_list = [{'label': triple_type_cand, 'start': baseidx, 'end': baseidx + (len(new_cand_list) - 1)}]
total_list = new_cand_list
elif len(new_cand_list) == 0:
cand_dict_list = []
ref_dict_list = [{'label': triple_type_ref, 'start': baseidx, 'end': baseidx + (len(new_ref_list) - 1)}]
total_list = ref_dict_list
else:
total_list = new_ref_list + new_cand_list
ref_dict_list = [{'label': triple_type_ref, 'start': baseidx, 'end': baseidx + (len(new_ref_list) - 1)}]
cand_dict_list = [{'label': triple_type_cand, 'start': baseidx + len(new_ref_list), 'end': baseidx + (len(total_list) - 1)}]
return candidate_found, ref_dict_list, cand_dict_list, total_list
def evaluateRefCand(reference, candidate):
new_ref = reference.split(' | ')
new_cand = candidate.split(' | ')
#DEBUG: print("Ref:", new_ref)
#DEBUG: print("Cand:", new_cand)
# Check if triples got split inside a literal value
# IDEA: Just reconstruct the portion of the list that is a literal that got split.
# Check for unmatched quotes
if len(new_ref) > 3:
if new_ref[0].strip('(').strip(')')[0] == '\"' and new_ref[0].strip('(').strip(')')[-1] != '\"':
rep_ref = []
end = 0
for i in range(1, len(new_ref)):
new_ref[i] = new_ref[i].strip('\'')
if new_ref[i].strip('(').strip(')')[-1] == '\"':
end = i
rep_ref.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_ref[0:end+1])))
rep_ref.append(new_ref[-2])
rep_ref.append(new_ref[-1])
new_ref = rep_ref
if new_ref[1].strip('(').strip(')')[0] == '\"' and new_ref[1].strip('(').strip(')')[-1] != '\"':
rep_ref = []
rep_ref.append(new_ref[0])
end = 0
for i in range(1, len(new_ref)):
new_ref[i] = new_ref[i].strip('\'')
if new_ref[i].strip('(').strip(')')[-1] == '\"':
end = i
rep_ref.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_ref[1:end+1])))
rep_ref.append(new_ref[-1])
new_ref = rep_ref
if new_ref[2].strip('(').strip(')')[0] == '\"' and new_ref[2].strip('(').strip(')')[-1] != '\"':
rep_ref = []
rep_ref.append(new_ref[0])
rep_ref.append(new_ref[1])
end = 0
for i in range(2, len(new_ref)):
new_ref[i] = new_ref[i].strip('\'')
if new_ref[i].strip('(').strip(')')[-1] == '\"':
end = i
rep_ref.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_ref[2:end+1])))
new_ref = rep_ref
if len(new_cand) > 3:
if new_cand[0].strip('(').strip(')')[0] == '\"' and new_cand[0].strip('(').strip(')')[-1] != '\"':
rep_cand = []
end = 0
for i in range(1, len(new_cand)):
new_cand[i] = new_cand[i].strip('\'')
if new_cand[i][-1].strip('(').strip(')') == '\"':
end = i
rep_cand.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_cand[0:end+1])))
rep_cand.append(new_cand[-2])
rep_cand.append(new_cand[-1])
new_cand = rep_cand
if new_cand[1].strip('(').strip(')')[0] == '\"' and new_cand[1].strip('(').strip(')')[-1] != '\"':
rep_cand = []
rep_cand.append(new_cand[0])
end = 0
for i in range(1, len(new_cand)):
new_cand[i] = new_cand[i].strip('\'')
if new_cand[i][-1].strip('(').strip(')') == '\"':
end = i
rep_cand.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_cand[1:end+1])))
rep_cand.append(new_cand[-1])
new_cand = rep_cand
if new_cand[2].strip('(').strip(')')[0] == '\"' and new_cand[2].strip('(').strip(')')[-1] != '\"':
rep_cand = []
rep_cand.append(new_cand[0])
rep_cand.append(new_cand[1])
end = 0
for i in range(1, len(new_cand)):
new_cand[i] = new_cand[i].strip('\'')
if new_cand[i][-1].strip('(').strip(')') == '\"':
end = i
rep_cand.append(", ".join(f'{w.strip("[").strip("]")}' for w in (new_cand[2:end+1])))
new_cand = rep_cand
# Make sure that reference or candidate aren't '' values originally.
if (len(new_ref) > 1) and (len(new_cand) > 1):
index_triple = new_ref
elif (len(new_ref) == 1) :
index_triple = new_cand
new_ref = ['', '', '']
else:
index_triple = new_ref
new_cand = ['', '', '']
subject_ref_list = None
subject_cand_list = None
subject_total_list = None
predicate_ref_list = None
predicate_cand_list = None
predicate_total_list = None
object_ref_list = None
object_cand_list = None
object_total_list = None
subject_found = False
predicate_found = False
object_found = False
for idx, attrib in enumerate(index_triple):
#Let's go over each attribute of the triple one by one
try:
refsub = new_ref[idx]
candsub = new_cand[idx]
except IndexError as i:
print(i)
print("idx:",idx)
print("refsub:",refsub)
print("candsub:",candsub)
print("reflist:",new_ref,len(new_ref))
print("candlist:",new_cand,len(new_cand))
print("candidate:",candidate)
exit(0)
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'^[' + re.escape(string.punctuation) + r']+$', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'^[' + re.escape(string.punctuation) + r']+$', x) == None]
#DEBUG: print("Ref List:", ref_list)
#DEBUG: print("Cand List:", cand_list)
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the reference
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
if idx == 0:
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'SUB', 'SUB', 0)
subject_found = candidate_found
subject_ref_list = ref_dict_list.copy()
subject_cand_list = cand_dict_list.copy()
subject_total_list = total_list.copy()
elif idx == 1:
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'PRED', 'PRED', len(subject_total_list))
predicate_found = candidate_found
predicate_ref_list = ref_dict_list.copy()
predicate_cand_list = cand_dict_list.copy()
predicate_total_list = total_list.copy()
else:
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'OBJ', 'OBJ', len(subject_total_list) + len(predicate_total_list))
object_found = candidate_found
object_ref_list = ref_dict_list.copy()
object_cand_list = cand_dict_list.copy()
object_total_list = total_list.copy()
switch_match_found = False
#If no matches were found for two or more attributes, we are going to try and compare different attributes to each other.
#First let's try to match the candidate subject and reference object (and vice versa)
if not subject_found and not object_found:
refsub = new_ref[0]
candsub = new_cand[2]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'SUB', 'OBJ', 0)
refsub = new_ref[2]
candsub = new_cand[0]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found2, ref_dict_list2, cand_dict_list2, total_list2 = getRefDict(new_ref_list, new_cand_list, 'OBJ', 'SUB', len(total_list) + len(predicate_total_list))
# subject_found is based in reference
if candidate_found or candidate_found2:
subject_found = candidate_found
subject_ref_list = ref_dict_list.copy()
subject_cand_list = cand_dict_list.copy()
subject_total_list = total_list.copy()
object_found = candidate_found2
object_ref_list = ref_dict_list2.copy()
object_cand_list = cand_dict_list2.copy()
object_total_list = total_list2.copy()
# get the new mapping of the predicate
refpred = new_ref[1]
candpred = new_cand[1]
ref_list = nltk.word_tokenize(refpred)
cand_list = nltk.word_tokenize(candpred)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
# debugging wrong code here nothing to do with predicate
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'PRED', 'PRED', len(subject_total_list))
predicate_found = candidate_found
predicate_ref_list = ref_dict_list.copy()
predicate_cand_list = cand_dict_list.copy()
predicate_total_list = total_list.copy()
switch_match_found = True
else:
switch_match_found = False
# Then, let's try to switch subject and predicate
if (not subject_found and not predicate_found) and not switch_match_found:
refsub = new_ref[0]
candsub = new_cand[1]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'SUB', 'PRED', 0)
refsub = new_ref[1]
candsub = new_cand[0]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found2, ref_dict_list2, cand_dict_list2, total_list2 = getRefDict(new_ref_list, new_cand_list, 'PRED', 'SUB', len(total_list))
if candidate_found or candidate_found2:
subject_found = candidate_found
subject_ref_list = ref_dict_list.copy()
subject_cand_list = cand_dict_list.copy()
subject_total_list = total_list.copy()
predicate_found = candidate_found2
predicate_ref_list = ref_dict_list2.copy()
predicate_cand_list = cand_dict_list2.copy()
predicate_total_list = total_list2.copy()
switch_match_found = True
else:
switch_match_found = False
# Finally, let's try to switch predicate and object
if (not predicate_found and not object_found) and not switch_match_found:
refsub = new_ref[1]
candsub = new_cand[2]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found, ref_dict_list, cand_dict_list, total_list = getRefDict(new_ref_list, new_cand_list, 'PRED', 'OBJ', len(subject_total_list))
refsub = new_ref[2]
candsub = new_cand[1]
ref_list = nltk.word_tokenize(refsub)
cand_list = nltk.word_tokenize(candsub)
ref_list = [x.lower() for x in ref_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
cand_list = [x.lower() for x in cand_list if re.search(r'[' + re.escape(string.punctuation) + r']', x) == None]
new_ref_list = ref_list.copy()
new_cand_list = cand_list.copy()
# Start with an ngram the full number of words in the candidate
ngram_length = len(new_cand_list)
new_ref_list, new_cand_list = nonRefWords(new_ref_list, new_cand_list, 1, ngram_length)
candidate_found2, ref_dict_list2, cand_dict_list2, total_list2 = getRefDict(new_ref_list, new_cand_list, 'OBJ', 'PRED', len(subject_total_list) + len(total_list))
if candidate_found or candidate_found2:
predicate_found = candidate_found
predicate_ref_list = ref_dict_list.copy()
predicate_cand_list = cand_dict_list.copy()
predicate_total_list = total_list.copy()
object_found = candidate_found2
object_ref_list = ref_dict_list2.copy()
object_cand_list = cand_dict_list2.copy()
object_total_list = total_list2.copy()
switch_match_found = True
else:
switch_match_found = False
all_ref_dict = subject_ref_list + predicate_ref_list + object_ref_list
all_cand_dict = subject_cand_list + predicate_cand_list + object_cand_list
all_total_list = subject_total_list + predicate_total_list + object_total_list
evaluator = Evaluator([all_ref_dict], [all_cand_dict], tags=['SUB', 'PRED', 'OBJ'])
# Returns overall metrics and metrics for each tag
results, results_per_tag = evaluator.evaluate()
return results, results_per_tag
def calculateAllScores(new_ref_list, new_cand_list):
#DEBUG: print(new_ref_list)
#DEBUG: print(new_cand_list)
total_sem_eval_list = []
total_sem_eval_list_per_tag = []
for idx, candidate in enumerate(new_cand_list):
#print('evaluating candidate ' + str(idx) + ' of ' + str(len(new_cand_list)))
# Ensure list lengths are equal, pad with empty strings.
if len(new_cand_list[idx]) != len(new_ref_list[idx]):
difference_between = abs(len(new_cand_list[idx]) - len(new_ref_list[idx]))
difference_list = [''] * difference_between
if len(new_cand_list[idx]) < len(new_ref_list[idx]):
new_cand_list[idx] = new_cand_list[idx] + difference_list
else:
new_ref_list[idx] = new_ref_list[idx] + difference_list
# Evaluate every triple against each reference triple
for idx, candidate in enumerate(new_cand_list):
candidate_sem_eval = []
candidate_sem_eval_per_tag = []
for triple in candidate:
triple_sem_eval = []
triple_sem_eval_per_tag = []
for reference in new_ref_list[idx]:
results, results_per_tag = evaluateRefCand(reference, triple)
triple_sem_eval.append(results)
triple_sem_eval_per_tag.append(results_per_tag)
candidate_sem_eval.append(triple_sem_eval)
candidate_sem_eval_per_tag.append(triple_sem_eval_per_tag)
total_sem_eval_list.append(candidate_sem_eval)
total_sem_eval_list_per_tag.append(candidate_sem_eval_per_tag)