-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.py
1378 lines (1012 loc) · 39.5 KB
/
utils.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
# Authors : Debanjali Biswas
# Theresa Schmidt ([email protected])
# Iris Ferrazzo ([email protected])
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utility functions
"""
# importing libraries
import os
import re
import torch
import pickle
import pandas as pd
import matplotlib.pyplot as plt
from conllu import parse
from matplotlib import style
from constants import prediction_file
from ast import literal_eval
import pandas as pd
from conllu2crowd_topk import generate_pairs_experiment
from constants import test_folder, folder
from conllu2crowd_topk import Recipe
style.use("ggplot")
def generate_recipe_dict(recipe, action_list, device):
"""
Generate List of Recipe Dictionary
Parameters
----------
recipe : List
Conllu parsed file for recipe.
action_list : List
List of action ids in recipe.
device : object
torch device where model tensors are saved.
Returns
-------
recipe_node_list : List of Dict
List of Dictionary for every action in the recipe.
Dictionary contains Action_id, Action, Parent_List, Child_List
"""
# No Alignment case
empty_dict = {
"Action_id": 0,
"Action": torch.empty(0),
"Parent_List": [],
"Child_List": [],
}
recipe_node_list = [empty_dict]
for action_id in action_list:
action_node, parent_list, child_list = generate_data_line(
action_id, recipe, device
)
# Recipe Dictionary
recipe_dict = {
"Action_id": action_id,
"Action": action_node,
"Parent_List": parent_list,
"Child_List": child_list,
}
# Append Dictionary to List
recipe_node_list.append(recipe_dict)
#print(recipe_node_list)
return recipe_node_list
#####################################
def generate_elmo_embeddings(emb_model, tokenizer, recipe, device):
"""
Generate Elmo Embeddings
Parameters
----------
emb_model : ElmoEmbedding object
Elmo Embedding model from Flair.
tokenizer : flair.data.Sentence object
Flair Data Sentence.
recipe : List
Conllu parsed file for recipe.
device : object
torch device where model tensors are saved.
Returns
-------
embedding_vectors : Dict
Embedding dictionary for a particular Recipe;
where keys are vector_lookup_list token_ids and values are their corresponding Elmo embeddings.
vector_lookup_list : Dict
Look up dictionary for a particular Recipe embeddings;
where key is the Conllu file token 'id' and values are list of token_ids generated using Elmo.
"""
recipe_text = ""
recipe_text_list = []
for line in recipe[0]:
recipe_text += line["form"] + " "
recipe_text_list.append(line["form"])
recipe_text = recipe_text.rstrip()
recipe_tokens = tokenizer(recipe_text) # Flair Sentence Representation
emb_model.embed(recipe_tokens) # Elmo Embeddings
embedding_vector = {}
for i, token in enumerate(recipe_tokens):
embedding_vector[i] = token.embedding
#print(embedding_vector)
vector_lookup_list = {}
for i, token in enumerate(recipe_tokens):
vector_lookup_list[i + 1] = [i]
#print(vector_lookup_list)
return embedding_vector, vector_lookup_list
#####################################
def generate_bert_embeddings(emb_model, tokenizer, recipe, device):
"""
Generate Bert Embeddings for a recipe
Parameters
----------
emb_model : BertModel object
Bert Embedding Model from HuggingFace.
tokenizer : BertTokenizer object
Tokenizer.
recipe : List
Conllu parsed file for recipe.
device : object
torch device where model tensors are saved.
Returns
-------
embedding_vectors : Dict
Embedding dictionary for a particular Recipe;
where keys are vector_lookup_list token_ids and values are their corresponding BERT embeddings.
vector_lookup_list : Dict
Look up dictionary for a particular Recipe embeddings;
where key is the Conllu file token 'id' and values are list of token_ids generated using BERT tokenizer.
"""
# TODO this is a more pythonic way for the code below
# until recipe_tokens = ...
# recipe_text_list = [line['form'] for line in recipe[0]]
# recipe_text = " ".join(recipe_text_list)
recipe_text = ""
recipe_text_list = []
for line in recipe[0]:
recipe_text += line["form"] + " "
recipe_text_list.append(line["form"])
recipe_text = recipe_text.rstrip()
recipe_tokens = tokenizer.encode(recipe_text) # Tokenize Recipe
recipe_tensor = torch.LongTensor([recipe_tokens]).to(device)
emb_model.eval()
with torch.no_grad():
outputs = emb_model(recipe_tensor)
hidden = outputs[2]
token_embeddings = torch.stack(hidden, dim=0)
token_embeddings = torch.squeeze(token_embeddings, dim=1)
token_embeddings = token_embeddings.permute(1, 0, 2)
# Stores the token vectors
token_vecs_sum = []
# For each token in the recipe...
for token in token_embeddings:
# Sum the vectors from the last four layers.
sum_vec = torch.sum(token[-2:], dim=0)
# Use `sum_vec` to represent `token`.
token_vecs_sum.append(sum_vec)
embedding_vector = {}
for i, emb in enumerate(token_vecs_sum):
embedding_vector[i] = emb
vector_lookup_list = {}
count = 1
for i, token in enumerate(recipe_text_list):
tokenize = tokenizer.tokenize(token)
vector_lookup_list[i + 1] = list(range(count, count + len(tokenize)))
count += len(tokenize)
return embedding_vector, vector_lookup_list
#####################################
def fetch_parsed_recipe(recipe_filename):
"""
Fetch conllu parsed file
Parameters
----------
recipe_filename : String
Recipe Filename.
Returns
-------
parsed_recipe : List
Conllu parsed file to generate a list of sentences.
"""
file = open(recipe_filename, "r", encoding="utf-8") # Recipe file
conllu_file = file.read() # Reading recipe file
parsed_recipe = parse(conllu_file) # Parsed Recipe File
return parsed_recipe
#####################################
def fetch_dish_train(dish, folder, alignment_file, recipe_folder_name, emb_model, tokenizer, device, embedding_name):
"""
Reads in the data.
Author: Theresa Schmidt
Parameters
----------
dish : String
Dish name.
folder : String
Path to data folder.
alignment_file : String
Filename of the alignment files.
recipe_folder_name : String
What the subfolder with the recipes is called in the dish folder.
emb_model : Embedding Model object
Model.
tokenizer : Tokenizer object
Tokenizer.
device : object
torch device where model tensors are saved.
embedding_name : String
Either 'elmo' or 'bert'.
Returns
----------
dish_dict : dict
Contains all information from this dish. Keys: recipe names. Values: dictionaries with keys "Embedding_Vectors", "Vector_Lookup_Lists", "Action_Dicts_List" and values according to fetch_recipe().
dish_group_alignments : pd.DataFrame
All alignments (token ID's) for the dish, grouped by pairs of recipe names.
"""
# Recipe names for the dish
data_folder = os.path.join(folder, dish) # dish folder
recipe_folder = os.path.join(data_folder, recipe_folder_name) # recipe folder, e.g. data/dish-name/recipes
recipe_list = os.listdir(recipe_folder)
recipe_list = [recipe for recipe in recipe_list if not recipe.startswith(".")]
# Read in recipes of the dish
dish_dict = dict()
for recipe in recipe_list:
recipe_filename = os.path.join(recipe_folder, recipe)
embedding_vectors, vector_lookup_lists, action_dicts_list = fetch_recipe_train(
recipe_filename, emb_model, tokenizer, device, embedding_name,
)
recipe_name = recipe.split(".")[0]
dish_dict[recipe_name] = {"Embedding_Vectors" : embedding_vectors, "Vector_Lookup_Lists" : vector_lookup_lists, "Action_Dicts_List" : action_dicts_list}
# Gold Standard Alignments between all recipes for dish
alignment_file_path = os.path.join(
data_folder, alignment_file
) # alignment file, e.g. data/dish-name/alignments.tsv
alignments = pd.read_csv(
alignment_file_path, sep="\t", header=0, skiprows=0, encoding="utf-8"
)
# Group by Recipe pairs
dish_group_alignments = alignments.groupby(["file1", "file2"])
return dish_dict, dish_group_alignments
###########################################
def fetch_dish_test(dish, folder, recipe_folder_name, emb_model, tokenizer, device, embedding_name):
"""
Reads in the data.
Author: Theresa Schmidt
Parameters
----------
dish : String
Dish name.
folder : String
Path to data folder.
alignment_file : String
Filename of the alignment files.
recipe_folder_name : String
What the subfolder with the recipes is called in the dish folder.
emb_model : Embedding Model object
Model.
tokenizer : Tokenizer object
Tokenizer.
device : object
torch device where model tensors are saved.
embedding_name : String
Either 'elmo' or 'bert'.
Returns
----------
dish_dict : dict
Contains all information from this dish. Keys: recipe names. Values: dictionaries with keys "Embedding_Vectors", "Vector_Lookup_Lists", "Action_Dicts_List" and values according to fetch_recipe().
dish_group_alignments : pd.DataFrame
All alignments (token ID's) for the dish, grouped by pairs of recipe names.
"""
# Recipe names for the dish
sub_directories=[]
data_folder = os.path.join(folder, dish) # dish folder
recipe_folder = os.path.join(data_folder, recipe_folder_name) # recipe folder, e.g. data/dish-name/recipes
recipe_list = os.listdir(recipe_folder)
recipe_list = [recipe for recipe in recipe_list if not recipe.startswith(".")]
sub_directories.append(recipe_folder)
# Read in recipes of the dish
dish_dict = dict()
for recipe in recipe_list:
#print(recipe)
recipe_filename = os.path.join(recipe_folder, recipe)
#print(recipe_filename)
embedding_vectors, vector_lookup_lists, action_dicts_list, recipe_actionlist_dict = fetch_recipe_test(
recipe_filename, emb_model, tokenizer, device, embedding_name,
)
recipe_name = recipe.split(".")[0]
#print(recipe_name)
dish_dict[recipe_name] = {"Embedding_Vectors" : embedding_vectors, "Vector_Lookup_Lists" : vector_lookup_lists, "Action_Dicts_List" : action_dicts_list, "Action_id_List":recipe_actionlist_dict[recipe_name]}
#print(dish_dict)
# (Not Gold) Alignments between all recipes for dish
# 3) extract actions to pair
recipes_ids={}
for recipe in recipe_list:
#print(recipe)
value_ids=[]
recipe_filename = os.path.join(recipe_folder, recipe)
recipe_open=open(recipe_filename).readlines()
for line in recipe_open:
#print(line)
columns = line.strip().split()
id = columns[0]
token = columns[1]
tag = columns[4]
if tag[0] == "B":
#print(id)
value_ids.append(int(id))
recipes_ids[recipe]=value_ids
#print(recipes_ids)
# 1) pair recipes using function generate_pairs_experiment from conllu2crowd
for recipe in recipe_list:
#print(recipe)
pairs = generate_pairs_experiment(recipe_folder,#os.path.join(recipe_folder,recipe)
r1_indexed=False,
r1_shuffled=False,
r2_indexed=True,
r2_indices_from=1)
#print(pairs)
# 2) convert class objects to strings
pairings=[]
for pair in pairs:
source=pair[0].name#+".conllu"
target=pair[1].name#+".conllu"
pair=(source,target)
pairings.append(pair)
#print(pairings)
#exit()
#for pair in pairings:
# recipes_of_dish.append(pair[0])
# print(recipes_ids[recipe_1])
# 4) prepare replacement for dish_group_alignments
#print("keys of recipes_ids are",recipes_ids.keys())
#print("pairings are",pairings)
alignments=[]
#for recipe in recipes_ids.keys():
# print(recipe)
#used_tokens=[]
for pair in pairings:
#print(pair[0])
#if recipe==pair[0]:
# print("yes")
# exit()
used_tokens=[]
recipe_1= pair[0]+".conllu"
recipe_2= pair[1]+".conllu"
try:
for value in recipes_ids[recipe_1]:
if value not in used_tokens:
alignment=(pair[0],value,pair[1])
#alignment.append(recipe_1)
#alignment.append(value)
used_tokens.append(value)
#alignment.append(recipe_2)
alignments.append(list(alignment))
used_tokens=[]
except KeyError:
print("No match was found for recipe", recipe_1)
#print(alignments)
# 5) execute replacement for dish_group_alignments
# I need the format list of lists
dish_alignments = pd.DataFrame(alignments, columns =["file1", "token1", "file2"])
dish_group_alignments = dish_alignments.groupby(["file1", "file2"])
# if you want to inspect the content of dish_group_alignments
#for key,item in dish_group_alignments:
# print(dish_group_alignments.get_group(key), "\n\n")
print("len 492 (pred input) ", len(dish_group_alignments), len(dish_alignments))
return dish_dict, dish_group_alignments
#####################################
def fetch_dish_test_insertion(dish, folder, recipe_folder_name, emb_model, tokenizer, device, embedding_name):
"""
Reads in the data.
Author: Theresa Schmidt
Parameters
----------
dish : String
Dish name.
folder : String
Path to data folder.
alignment_file : String
Filename of the alignment files.
recipe_folder_name : String
What the subfolder with the recipes is called in the dish folder.
emb_model : Embedding Model object
Model.
tokenizer : Tokenizer object
Tokenizer.
device : object
torch device where model tensors are saved.
embedding_name : String
Either 'elmo' or 'bert'.
Returns
----------
dish_dict : dict
Contains all information from this dish. Keys: recipe names. Values: dictionaries with keys "Embedding_Vectors", "Vector_Lookup_Lists", "Action_Dicts_List" and values according to fetch_recipe().
dish_group_alignments : pd.DataFrame
All alignments (token ID's) for the dish, grouped by pairs of recipe names.
"""
# Recipe names for the dish
sub_directories=[]
data_folder = os.path.join(folder, dish) # dish folder = ./data/baked_ziti
#print(data_folder)
recipe_folder = os.path.join(data_folder, recipe_folder_name) # recipe folder, e.g. ./data/baked_ziti/recipes, data/dish-name/recipes
#print(recipe_folder)
recipe_list = os.listdir(recipe_folder)
recipe_list = [recipe for recipe in recipe_list if not recipe.startswith(".")] # ['baked_ziti_6.conllu', 'baked_ziti_7.conllu', 'baked_ziti_9.conllu', 'baked_ziti_8.conllu', 'baked_ziti_2.conllu', 'baked_ziti_10.conllu', 'baked_ziti_3.conllu', 'baked_ziti_0.conllu', 'baked_ziti_4.conllu', 'baked_ziti_1.conllu', 'baked_ziti_5.conllu']
#print(recipe_list)
sub_directories.append(recipe_folder)
# Read in recipes of the dish
dish_dict = dict()
for recipe in recipe_list:
#print(recipe)
recipe_filename = os.path.join(recipe_folder, recipe)
#print(recipe_filename)
embedding_vectors, vector_lookup_lists, action_dicts_list, recipe_actionlist_dict = fetch_recipe_test(
recipe_filename, emb_model, tokenizer, device, embedding_name,
)
recipe_name = recipe.split(".")[0]
#print(recipe_name)
dish_dict[recipe_name] = {"Embedding_Vectors" : embedding_vectors, "Vector_Lookup_Lists" : vector_lookup_lists, "Action_Dicts_List" : action_dicts_list, "Action_id_List":recipe_actionlist_dict[recipe_name]}
#print(dish_dict)
# (Not Gold) Alignments between all recipes for dish
# 3) extract actions to pair
recipes_ids={}
for recipe in recipe_list:
#print(recipe)
value_ids=[]
recipe_filename = os.path.join(recipe_folder, recipe)
recipe_open=open(recipe_filename).readlines()
for line in recipe_open:
#print(line)
columns = line.strip().split()
id = columns[0]
token = columns[1]
tag = columns[4]
if tag[0] == "B":
#print(id)
value_ids.append(int(id))
recipes_ids[recipe]=value_ids
#print(recipes_ids)
# 1) pair recipes using function generate_pairs_experiment from conllu2crowd
for recipe in recipe_list:
#print(recipe)
pairs = generate_pairs_experiment(recipe_folder,#os.path.join(recipe_folder,recipe)
r1_indexed=False,
r1_shuffled=False,
r2_indexed=True,
r2_indices_from=1)
#print(pairs)
# 2) convert class objects to strings
pairings=[]
for pair in pairs:
source=pair[0].name#+".conllu"
target=pair[1].name#+".conllu"
pair=(source,target)
pairings.append(pair)
#print("ORIGINAL", " ", pairings)
print(pairings)
# switch the order of the each element in pairings
# this will alow us to have reversed alignment scores
# we will use them to define insertions costs (=deletions costs) and to refine substitution costs (=average of the two align. directions)
pairings_insertion=[]
for pair in pairings:
recipe1=pair[1]
recipe2=pair[0]
pair_ins=(recipe1,recipe2)
pairings_insertion.append(pair_ins)
#print("INSERTION", " ", pairings_insertion)
# 4) prepare replacement for dish_group_alignments
#print("keys of recipes_ids are",recipes_ids.keys())
#print("pairings are",pairings)
alignments=[]
#for recipe in recipes_ids.keys():
# print(recipe)
#used_tokens=[]
for pair in pairings_insertion:
#print(pair[0])
#if recipe==pair[0]:
# print("yes")
# exit()
used_tokens=[]
recipe_1= pair[0]+".conllu"
recipe_2= pair[1]+".conllu"
try:
for value in recipes_ids[recipe_1]:
if value not in used_tokens:
alignment=(pair[0],value,pair[1])
#alignment.append(recipe_1)
#alignment.append(value)
used_tokens.append(value)
#alignment.append(recipe_2)
alignments.append(list(alignment))
used_tokens=[]
except KeyError:
print("No match was found for recipe", recipe_1)
#print(alignments)
# 5) execute replacement for dish_group_alignments
# I need the format list of lists
dish_alignments = pd.DataFrame(alignments, columns =["file1", "token1", "file2"])
dish_group_alignments = dish_alignments.groupby(["file1", "file2"])
# if you want to inspect the content of dish_group_alignments
#for key,item in dish_group_alignments:
# print(dish_group_alignments.get_group(key), "\n\n")
return dish_dict, dish_group_alignments
#######################################
def fetch_recipe_train(recipe_filename, emb_model, tokenizer, device, embedding_name):
"""
Fetch List of recipe dictionary and Embedding vector dictionary
Parameters
----------
recipe_filename : String
Recipe filename (relative path).
emb_model : Embedding object
Model.
tokenizer : Tokenizer object
Tokenizer.
device : object
torch device where model tensors are saved.
Returns
-------
embedding_vectors : Dict
Embedding dictionary for a particular Recipe;
where keys are vector_lookup_list token_ids and values are their corresponding word embeddings (BERT/ELMO).
vector_lookup_list : Dict
Look up dictionary for a particular Recipe embeddings;
where key is the Conllu file token 'id' and values are list of token_ids generated using BERT/ELMO tokenizer.
action_dicts_list : List of Dict
List of Dictionary for every action in the recipe.
Dictionary contains Action_id, Action, Parent_List, Child_List.
"""
parsed_recipe = fetch_parsed_recipe(recipe_filename) # Parsed Recipe File
if(embedding_name == 'bert'):
embedding_vector, vector_lookup_list = generate_bert_embeddings(
emb_model, tokenizer, parsed_recipe, device
) # Embeddings for Recipe
elif (embedding_name == 'elmo'):
embedding_vector, vector_lookup_list = generate_elmo_embeddings(
emb_model, tokenizer, parsed_recipe, device
) # Embeddings for Recipe
# addition by Iris: create a dict with recipe names as keys and corresponding action list as value --> to use in fetch_dish
recipe_actionlist_dict=dict()
# chage file name to match the one used in fetch_dish
recipe_filename=recipe_filename.split("/")[-1]
recipe_filename=recipe_filename.split(".")[0]
action_list = fetch_action_ids(parsed_recipe) # List of actions in recipe
recipe_actionlist_dict[recipe_filename]=action_list
#print(recipe_actionlist_dict)
action_dicts_list = generate_recipe_dict(
parsed_recipe, action_list, device
) # List of Recipe dictionary
return embedding_vector, vector_lookup_list, action_dicts_list#, recipe_actionlist_dict
#####################################
def fetch_recipe_test(recipe_filename, emb_model, tokenizer, device, embedding_name):
"""
Fetch List of recipe dictionary and Embedding vector dictionary
Parameters
----------
recipe_filename : String
Recipe filename (relative path).
emb_model : Embedding object
Model.
tokenizer : Tokenizer object
Tokenizer.
device : object
torch device where model tensors are saved.
Returns
-------
embedding_vectors : Dict
Embedding dictionary for a particular Recipe;
where keys are vector_lookup_list token_ids and values are their corresponding word embeddings (BERT/ELMO).
vector_lookup_list : Dict
Look up dictionary for a particular Recipe embeddings;
where key is the Conllu file token 'id' and values are list of token_ids generated using BERT/ELMO tokenizer.
action_dicts_list : List of Dict
List of Dictionary for every action in the recipe.
Dictionary contains Action_id, Action, Parent_List, Child_List.
"""
parsed_recipe = fetch_parsed_recipe(recipe_filename) # Parsed Recipe File
if(embedding_name == 'bert'):
embedding_vector, vector_lookup_list = generate_bert_embeddings(
emb_model, tokenizer, parsed_recipe, device
) # Embeddings for Recipe
elif (embedding_name == 'elmo'):
embedding_vector, vector_lookup_list = generate_elmo_embeddings(
emb_model, tokenizer, parsed_recipe, device
) # Embeddings for Recipe
# addition by Iris: create a dict with recipe names as keys and corresponding action list as value --> to use in fetch_dish
recipe_actionlist_dict=dict()
# chage file name to match the one used in fetch_dish
recipe_filename=recipe_filename.split("/")[-1]
recipe_filename=recipe_filename.split(".")[0]
action_list = fetch_action_ids(parsed_recipe) # List of actions in recipe
recipe_actionlist_dict[recipe_filename]=action_list
#print(recipe_actionlist_dict)
action_dicts_list = generate_recipe_dict(
parsed_recipe, action_list, device
) # List of Recipe dictionary
return embedding_vector, vector_lookup_list, action_dicts_list, recipe_actionlist_dict
#####################################
def fetch_split_action(action_token_id, parsed_recipe):
"""
Fetch tagging actions for a particular split action node
Parameters
----------
action_token_id : Int
Action Token Id.
parsed_recipe : List
Conllu parsed file to generate a list of sentences.
Returns
-------
tagging_tokens : string
Tagging action sequence for a particular action node.
"""
tagging_tokens = []
token_id = action_token_id
if token_id >= len(parsed_recipe[0]):
return tagging_tokens
line = parsed_recipe[0][token_id]
# Checking for intermediate action node
while line["xpos"].startswith("I"):
tagging_tokens.append(line["id"])
token_id += 1
line = parsed_recipe[0][token_id]
return tagging_tokens
#####################################
def fetch_action_node(action_token_id, parsed_recipe, device):
"""
Fetch Action String for a particular action node
Parameters
----------
action_token_id : Int
Action Token Id.
parsed_recipe : List
Conllu parsed file to generate a list of sentences.
device : object
torch device where model tensors are saved.
Returns
-------
action : Tensor
Action sequence for a particular action node.
"""
action = [parsed_recipe[0][action_token_id - 1]["id"]]
tagged_action = fetch_split_action(action_token_id, parsed_recipe)
if tagged_action:
action.extend(tagged_action)
# action_tokens = tokenizer.encode(action) # Tokenize action node
action_tokens = torch.LongTensor(action).to(device)
return action_tokens
#####################################
def dependency_heads(deps):
"""
Interprets the entry in the DEPS column.
Returns a list of head indices.
"""
head_list = list()
"""
if deps:
deps = re.split("[( )]", deps) # TODO: rather use literaleval
unwanted = {"[", "]"}
head_list = [int(l.split(",")[0]) for l in deps if l not in unwanted]
"""
# TODO: test (as soon as recipes are non-tree graphs)
if deps:
deps = literal_eval(deps)
head_list = [int(h) for h, d in deps]
return head_list
def fetch_parent_node(action_token_id, parsed_recipe, device):
"""
Fetch List of Children for a particular action
Parameters
----------
action_token_id : Int
Action Token Id.
parsed_recipe : List
Conllu parsed file to generate a list of sentences.
device : object
torch device where model tensors are saved.
Returns
-------
parent_list : List of Tensors
List of parents for that particular action.
"""
action_line = parsed_recipe[0][action_token_id - 1]
parent_list = list()
parent_id = action_line["head"]
if parent_id != 0:
parent = [parsed_recipe[0][parent_id - 1]["id"]]
tagged_action = fetch_split_action(parent_id, parsed_recipe)
if tagged_action:
parent.extend(tagged_action)
# parent_token = tokenizer.encode(parent) # Tokenize parent node
parent_token = torch.LongTensor(parent).to(device)
parent_list.append(parent_token) # Append to parent_list
other_parents = dependency_heads(action_line["deps"]) # Other parents not belonging to head
if other_parents:
for parent_id in other_parents:
parent = [parsed_recipe[0][parent_id - 1]["id"]]
tagged_action = fetch_split_action(parent_id, parsed_recipe)
if tagged_action:
parent.extend(tagged_action)
# parent_token = tokenizer.encode(parent)
parent_token = torch.LongTensor(parent).to(device)
parent_list.append(parent_token)
return parent_list
#####################################
def fetch_child_node(action_token_id, parsed_recipe, device):
"""
Fetch List of Children for a particular action
Parameters
----------
action_token_id : Int
Action Token Id.
parsed_recipe : List
Conllu parsed file to generate a list of sentences.
device : object
torch device where model tensors are saved.
Returns
-------
child_list : List of Tensors
List of children for that particular action.
"""
child_list = list()
for line in parsed_recipe[0]:
if line["xpos"].startswith("B") and (line["head"] == action_token_id or action_token_id in dependency_heads(line["deps"])):
child_id = line["id"]
child = [parsed_recipe[0][child_id - 1]["id"]]
tagged_action = fetch_split_action(child_id, parsed_recipe)
if tagged_action:
child.extend(tagged_action)
# child_token = tokenizer.encode(child) # Tokenize Child node
child_token = torch.LongTensor(child).to(device)
child_list.append(child_token) # Append child to child_list
return child_list
#####################################
def generate_data_line(action_token_id, parsed_recipe, device):
"""
Generate action, parent list and child list for a particular action node