forked from ZonglinY/ECBRF_Case_Based_Reasoning_with_PLM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_TST.py
2604 lines (2464 loc) · 145 KB
/
utils_TST.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 tqdm import tqdm
from transformers import (CONFIG_NAME, WEIGHTS_NAME)
import pandas as pd
import numpy as np
import random
import torch
import pandas
import json
import os
import time
import math
import copy
import nltk
# remove stop words
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# TreebankWordDetokenizer: reverse word_tokenize
from nltk.tokenize.treebank import TreebankWordDetokenizer
nltk.download('stopwords')
nltk.download('punkt')
relations = [
'AtLocation', 'CapableOf', 'Causes', 'CausesDesire',
'CreatedBy', 'DefinedAs', 'DesireOf', 'Desires', 'HasA',
'HasFirstSubevent', 'HasLastSubevent', 'HasPainCharacter',
'HasPainIntensity', 'HasPrerequisite', 'HasProperty',
'HasSubevent', 'InheritsFrom', 'InstanceOf', 'IsA',
'LocatedNear', 'LocationOfAction', 'MadeOf', 'MotivatedByGoal',
'NotCapableOf', 'NotDesires', 'NotHasA', 'NotHasProperty',
'NotIsA', 'NotMadeOf', 'PartOf', 'ReceivesAction', 'RelatedTo',
'SymbolOf', 'UsedFor'
]
split_into_words = {
'AtLocation': "at location",
'CapableOf': "capable of",
'Causes': "causes",
'CausesDesire': "causes desire",
'CreatedBy': "created by",
'DefinedAs': "defined as",
'DesireOf': "desire of",
'Desires': "desires",
'HasA': "has a",
'HasFirstSubevent': "has first subevent",
'HasLastSubevent': "has last subevent",
'HasPainCharacter': "has pain character",
'HasPainIntensity': "has pain intensity",
'HasPrerequisite': "has prequisite",
# actually it is "has prerequisite, but models were trained on it ..."
'HasProperty': "has property",
'HasSubevent': "has subevent",
'InheritsFrom': "inherits from",
'InstanceOf': 'instance of',
'IsA': "is a",
'LocatedNear': "located near",
'LocationOfAction': "location of action",
'MadeOf': "made of",
'MotivatedByGoal': "motivated by goal",
'NotCapableOf': "not capable of",
'NotDesires': "not desires",
'NotHasA': "not has a",
'NotHasProperty': "not has property",
'NotIsA': "not is a",
'NotMadeOf': "not made of",
'PartOf': "part of",
'ReceivesAction': "receives action",
'RelatedTo': "related to",
'SymbolOf': "symbol of",
'UsedFor': "used for",
"/olympics/olympic_participating_country/athletes./olympics/olympic_athlete_affiliation/olympics": "participate in olympics",
"/film/film/music": "has music composed by",
"/award/award_category/category_of": "is an award category of",
"/music/performance_role/regular_performances./music/group_membership/role": None,
"/location/country/capital": "capital",
"/government/legislative_session/members./government/government_position_held/legislative_sessions": "members also attend",
"/location/administrative_division/first_level_division_of": "is one of the first level administrtive division of",
"/tv/tv_program/program_creator": "created by",
"/base/americancomedy/celebrity_impressionist/celebrities_impersonated": "has impersonated",
"/government/legislative_session/members./government/government_position_held/district_represented": "has members representing",
"/education/educational_institution/students_graduates./education/education/student": "has graduated student",
"/tv/tv_program/languages": "is spoken in",
"/people/person/spouse_s./people/marriage/location_of_ceremony": "location of marriage ceremony",
"/award/award_ceremony/awards_presented./award/award_honor/award_winner": "awarded to",
"/government/politician/government_positions_held./government/government_position_held/basic_title": "has title in government",
"/location/location/time_zones": "in time zone",
"/film/person_or_entity_appearing_in_film/films./film/personal_film_appearance/type_of_appearance": "type of appearance in film",
"/military/military_conflict/combatants./military/military_combatant_group/combatants": "has combatants",
"/film/film_set_designer/film_sets_designed": "designed film set",
"/medicine/symptom/symptom_of": "is a symptom of",
"/language/human_language/countries_spoken_in": "is spoken in",
"/base/popstra/celebrity/dated./base/popstra/dated/participant": "dated with",
"/people/person/place_of_birth": "is born in",
"/organization/organization/headquarters./location/mailing_address/country": "is located in",
"/education/educational_institution/students_graduates./education/education/major_field_of_study": "major field of study",
"/music/group_member/membership./music/group_membership/group": "is a member of",
"/music/performance_role/regular_performances./music/group_membership/group": "played by",
"/base/x2010fifaworldcupsouthafrica/world_cup_squad/current_world_cup_squad./base/x2010fifaworldcupsouthafrica/current_world_cup_squad/current_club": "from club",
"/location/statistical_region/religions./location/religion_percentage/religion": "has main religion",
"/education/educational_institution_campus/educational_institution": "educational institution",
"/award/award_winning_work/awards_won./award/award_honor/honored_for": "won same awards with",
"/film/film/produced_by": "is produced by",
"/award/award_winning_work/awards_won./award/award_honor/award_winner": "earn awards to",
"/people/profession/specialization_of": "is a specialization of",
"/film/film/edited_by": "is edited by",
"/film/film/release_date_s./film/film_regional_release_date/film_release_distribution_medium": "distributed by",
"/location/statistical_region/gdp_real./measurement_unit/adjusted_money_value/adjustment_currency": "gdp measured by adjustment currency",
"/sports/sports_position/players./american_football/football_historical_roster_position/position_s": "both football positions",
"/location/location/partially_contains": "partially contains",
"/film/film/story_by": "story by",
"/base/popstra/location/vacationers./base/popstra/vacation_choice/vacationer": "has vacationer",
"/base/localfood/seasonal_month/produce_available./base/localfood/produce_availability/seasonal_months": None,
"/baseball/baseball_team/team_stats./baseball/baseball_team_stats/season": "participate in baseball season",
"/music/instrument/instrumentalists": "played by",
"/government/governmental_body/members./government/government_position_held/legislative_sessions": "take part in",
"/organization/organization/headquarters./location/mailing_address/citytown": "headquarter located in",
"/location/statistical_region/rent50_2./measurement_unit/dated_money_value/currency": None,
"/sports/sports_position/players./sports/sports_team_roster/team": None,
"/influence/influence_node/influenced_by": "is influenced by",
"/food/food/nutrients./food/nutrition_fact/nutrient": "has nutrient",
"/film/film/film_festivals": "is shown in festival",
"/music/artist/track_contributions./music/track_contribution/role": "contribute to track as a role of",
"/award/award_category/disciplines_or_subjects": "is an award of the discipline of",
"/film/film_distributor/films_distributed./film/film_film_distributor_relationship/film": "distributed film",
"/medicine/disease/notable_people_with_this_condition": "notable people with this condition",
"/tv/tv_program/country_of_origin": "originated in",
"/organization/organization/headquarters./location/mailing_address/state_province_region": "located in",
"/sports/sports_position/players./sports/sports_team_roster/position": None,
"/location/hud_foreclosure_area/estimated_number_of_mortgages./measurement_unit/dated_integer/source": "number of mortgages measured by",
"/film/film/other_crew./film/film_crew_gig/film_crew_role": "take the role of",
"/people/deceased_person/place_of_death": "place of death",
"/base/marchmadness/ncaa_basketball_tournament/seeds./base/marchmadness/ncaa_tournament_seed/team": "has seed team",
"/user/jg/default_domain/olympic_games/sports": "includes sports",
"/location/hud_county_place/place": None,
"/film/film/distributors./film/film_film_distributor_relationship/region": "distributed in region",
"/music/genre/artists": "played by artists",
"/film/film/costume_design_by": "costume designed by",
"/people/ethnicity/geographic_distribution": "geographically distributed in",
"/organization/endowed_organization/endowment./measurement_unit/dated_money_value/currency": "endowment measured by currency",
"/people/person/gender": "of gender",
"/base/eating/practicer_of_diet/diet": "practicer of diet",
"/base/schemastaging/organization_extra/phone_number./base/schemastaging/phone_sandbox/service_language": "serve with language",
"/film/film/release_date_s./film/film_regional_release_date/film_regional_debut_venue": "premiere at",
"/music/artist/origin": "comes from",
"/influence/influence_node/peers./influence/peer_relationship/peers": "is in peer relationship with",
"/sports/sports_league_draft/picks./sports/sports_league_draft_pick/school": "has attendee",
"/award/award_category/winners./award/award_honor/award_winner": "awarded to",
"/olympics/olympic_games/participating_countries": "participating countries",
"/film/film/production_companies": "produced by companies",
"/government/political_party/politicians_in_this_party./government/political_party_tenure/politician": "has member",
"/education/university/domestic_tuition./measurement_unit/dated_money_value/currency": "domestic tuition measured by currency",
"/film/film/other_crew./film/film_crew_gig/crewmember": "has pther crew member",
"/base/schemastaging/organization_extra/phone_number./base/schemastaging/phone_sandbox/contact_category": "category of contact",
"/award/award_nominee/award_nominations./award/award_nomination/award_nominee": "has same award nomination as ",
"/film/film/dubbing_performances./film/dubbing_performance/actor": "dubbed by",
"/location/country/form_of_government": "form of government",
"/base/schemastaging/person_extra/net_worth./measurement_unit/dated_money_value/currency": "net worth measured by currency",
"/film/film/distributors./film/film_film_distributor_relationship/film_distribution_medium": "film distributed in the form of",
"/base/biblioness/bibs_location/state": None,
"/sports/sports_team/roster./american_football/football_historical_roster_position/position_s": "has position",
"/location/capital_of_administrative_division/capital_of./location/administrative_division_capital_relationship/administrative_division": "capital of",
"/music/record_label/artist": "owns artist",
"/olympics/olympic_participating_country/medals_won./olympics/olympic_medal_honor/olympics": "won olympic medals in",
"/business/business_operation/assets./measurement_unit/dated_money_value/currency": "assets measured by currency",
"/film/film/written_by": "written by",
"/film/film/release_date_s./film/film_regional_release_date/film_release_region": "released in",
"/tv/tv_writer/tv_programs./tv/tv_program_writer_relationship/tv_program": "writer tv program",
"/film/film/film_production_design_by": "film production designed by",
"/travel/travel_destination/how_to_get_here./travel/transportation/mode_of_transportation": "transportation to get there",
"/sports/sports_team/roster./baseball/baseball_roster_position/position": "has position",
"/award/award_nominee/award_nominations./award/award_nomination/award": "is nominated for",
"/tv/tv_program/regular_cast./tv/regular_tv_appearance/actor": "has an actor",
"/base/popstra/celebrity/canoodled./base/popstra/canoodled/participant": "canoodled with",
"/common/topic/webpage./common/webpage/category": "category of webpage",
"/location/country/second_level_divisions": "is one of the second level administrtive division of",
"/military/military_combatant/military_conflicts./military/military_combatant_group/combatants": "has military conflicts with",
"/award/award_category/winners./award/award_honor/ceremony": "is awarded in ceremony",
"/celebrities/celebrity/celebrity_friends./celebrities/friendship/friend": "is a friend of",
"/tv/non_character_role/tv_regular_personal_appearances./tv/tv_regular_personal_appearance/person": "role taken by",
"/sports/sports_league/teams./sports/sports_league_participation/team": "has participants",
"/olympics/olympic_sport/athletes./olympics/olympic_athlete_affiliation/olympics": "is a sport in",
"/user/tsegaran/random/taxonomy_subject/entry./user/tsegaran/random/taxonomy_entry/taxonomy": None,
"/base/petbreeds/city_with_dogs/top_breeds./base/petbreeds/dog_city_relationship/dog_breed": "has top dog breed",
"/education/educational_degree/people_with_this_degree./education/education/student": "people with this degree",
"/business/business_operation/industry": "main business",
"/education/university/fraternities_and_sororities": "has fraternities and sororities",
"/people/person/places_lived./people/place_lived/location": "lived in",
"/dataworld/gardening_hint/split_to": None,
"/organization/role/leaders./organization/leadership/organization": "is a leader position in",
"/music/performance_role/guest_performances./music/recording_contribution/performance_role": "is a performance role in",
"/base/aareas/schema/administrative_area/capital": "has capital",
"/music/genre/parent_genre": "is genre of",
"/people/person/spouse_s./people/marriage/type_of_union": "has type of union with spouse",
"/soccer/football_player/current_team./sports/sports_team_roster/team": "is a soccer player in",
"/sports/sports_team_location/teams": "has team",
"/people/cause_of_death/people": "causes death to",
"/location/location/adjoin_s./location/adjoining_relationship/adjoins": "adjoins",
"/business/business_operation/operating_income./measurement_unit/dated_money_value/currency": "has income type of",
"/government/government_office_category/officeholders./government/government_position_held/jurisdiction_of_office": "is government position in",
"/film/film/featured_film_locations": "has filming locations in",
"/olympics/olympic_sport/athletes./olympics/olympic_athlete_affiliation/country": "has atheletes from",
"/base/aareas/schema/administrative_area/administrative_area_type": "has administrative type of",
"/film/film/personal_appearances./film/personal_film_appearance/person": "has appearances of",
"/sports/sports_team/colors": "has color in",
"/base/biblioness/bibs_location/country": "locates in",
"/film/film/estimated_budget./measurement_unit/dated_money_value/currency": "has value in the currency of",
"/education/educational_institution/colors": "has color in",
"/award/hall_of_fame/inductees./award/hall_of_fame_induction/inductee": "has inductee",
"/government/politician/government_positions_held./government/government_position_held/legislative_sessions": "has politic position in",
"/film/actor/film./film/performance/film": "acts in",
"/award/award_winner/awards_won./award/award_honor/award_winner": "wins the same award with",
"/education/university/local_tuition./measurement_unit/dated_money_value/currency": "has tuition measured by",
"/base/popstra/celebrity/breakup./base/popstra/breakup/participant": "breaks up with",
"/time/event/instance_of_recurring_event": "is an instance of",
"/people/person/profession": "has profession in",
"/education/field_of_study/students_majoring./education/education/student": "is a major of",
"/user/ktrueman/default_domain/international_organization/member_states": "has member",
"/music/instrument/family": "belongs to the musical instrument family of",
"/ice_hockey/hockey_team/current_roster./sports/sports_team_roster/position": "has position type of",
"/people/person/languages": "can speak",
"/base/locations/continents/countries_within": "contains the country",
"/music/artist/contribution./music/recording_contribution/performance_role": "contributes to the musical performance role of",
"/government/politician/government_positions_held./government/government_position_held/jurisdiction_of_office": "has political power to govern",
"/people/marriage_union_type/unions_of_this_type./people/marriage/location_of_ceremony": "is held in",
"/education/educational_institution/campuses": "is an institution of",
"/organization/organization/child./organization/organization_relationship/child": "has a children organization",
"/sports/sports_team/sport": "is a team in",
"/location/statistical_region/places_exported_to./location/imports_and_exports/exported_to": "exports to",
"/award/award_nominated_work/award_nominations./award/award_nomination/nominated_for": "win awards at the same time with",
"/soccer/football_team/current_roster./soccer/football_roster_position/position": "has position in",
"/film/actor/film./film/performance/special_performance_type": "performs in the type of",
"/award/award_ceremony/awards_presented./award/award_honor/honored_for": "gives award honor to",
"/organization/organization_member/member_of./organization/organization_membership/organization": "is a member of",
"/sports/sport/pro_athletes./sports/pro_sports_played/athlete": "has previous athlete",
"/sports/pro_athlete/teams./sports/sports_team_roster/team": "previously played in",
"/time/event/locations": "located in",
"/tv/tv_personality/tv_regular_appearances./tv/tv_regular_personal_appearance/program": "appears in the program of",
"/business/business_operation/revenue./measurement_unit/dated_money_value/currency": "operates business in the currency of",
"/people/person/employment_history./business/employment_tenure/company": "worked in",
"/location/statistical_region/gdp_nominal./measurement_unit/dated_money_value/currency": "measures gdp by the currency of",
"/soccer/football_team/current_roster./sports/sports_team_roster/position": "plays in the position of",
"/film/film/language": "has film language",
"/location/statistical_region/gdp_nominal_per_capita./measurement_unit/dated_money_value/currency": "measures per capita gdp by the currency of",
"/olympics/olympic_games/sports": "had sports",
"/location/statistical_region/gni_per_capita_in_ppp_dollars./measurement_unit/dated_money_value/currency": "measures per capital ppp gdp by the currency of",
"/education/field_of_study/students_majoring./education/education/major_field_of_study": "is a major as well as",
"/medicine/disease/risk_factors": "has risk factor of",
"/film/film/cinematography": "is cinematographed by",
"/tv/tv_program/genre": "is genre of",
"/film/film/genre": "is genre of",
"/film/film/country": "is produced from",
"/award/award_winning_work/awards_won./award/award_honor/award": "receives the award",
"/film/film/executive_produced_by": "has executive producer",
"/people/person/sibling_s./people/sibling_relationship/sibling": "is a sibling of",
"/film/actor/dubbing_performances./film/dubbing_performance/language": "dubs by the language of",
"/tv/tv_producer/programs_produced./tv/tv_producer_term/producer_type": "is a",
"/olympics/olympic_participating_country/medals_won./olympics/olympic_medal_honor/medal": "won",
"/sports/professional_sports_team/draft_picks./sports/sports_league_draft_pick/draft": "participated in",
"/film/film/runtime./film/film_cut/film_release_region": "is released in",
"/film/film/prequel": "has prequel",
"/sports/sports_team/roster./american_football/football_roster_position/position": "has football position in",
"/education/university/international_tuition./measurement_unit/dated_money_value/currency": "measures its tuition by the currency of",
"/music/performance_role/track_performances./music/track_contribution/role": "plays the role of",
"/location/country/official_language": "has official language",
"/tv/tv_program/tv_producer./tv/tv_producer_term/producer_type": "has the producer type of",
"/music/group_member/membership./music/group_membership/role": "plays the role in",
"/tv/tv_network/programs./tv/tv_network_duration/program": "has tv program",
"/people/deceased_person/place_of_burial": "is buried in",
"/tv/tv_producer/programs_produced./tv/tv_producer_term/program": "produces",
"/base/aareas/schema/administrative_area/administrative_parent": "is a part of",
"/base/saturdaynightlive/snl_cast_member/seasons./base/saturdaynightlive/snl_season_tenure/cast_members": "is a cast member in the time with",
"/broadcast/content/artist": "has the artist",
"/award/award_category/nominees./award/award_nomination/nominated_for": "has nominees",
"/base/schemastaging/organization_extra/phone_number./base/schemastaging/phone_sandbox/service_location": "has service location in",
"/film/film/film_format": "is a format of",
"/education/educational_institution/school_type": "is a type of",
"/education/educational_degree/people_with_this_degree./education/education/major_field_of_study": "has a field in",
"/olympics/olympic_games/medals_awarded./olympics/olympic_medal_honor/medal": "has medal honor of",
"/people/ethnicity/people": "is the ethnicity of",
"/award/award_nominee/award_nominations./award/award_nomination/nominated_for": "win award by",
"/location/location/contains": "contains",
"/people/ethnicity/languages_spoken": "speaks",
"/base/popstra/celebrity/friendship./base/popstra/friendship/participant": "is a friend of",
"/location/hud_county_place/county": "is a county in",
"/sports/sports_team/roster./basketball/basketball_roster_position/position": "has basketball position in",
"/sports/professional_sports_team/draft_picks./sports/sports_league_draft_pick/school": "picks a player from",
"/film/special_film_performance_type/film_performance_type./film/performance/film": "is the type of",
"/celebrities/celebrity/sexual_relationships./celebrities/romantic_relationship/celebrity": "has a romantic relationship with",
"/location/us_county/county_seat": "has a county seat of",
"/organization/non_profit_organization/registered_with./organization/non_profit_registration/registering_agency": "is registered with",
"/base/culturalevent/event/entity_involved": "involves",
"/american_football/football_team/current_roster./sports/sports_team_roster/position": "has football position in",
"/people/person/nationality": "is a person of",
"/travel/travel_destination/climate./travel/travel_destination_monthly_climate/month": "can be traveled in",
"/film/film_subject/films": "is the subject of",
"/award/ranked_item/appears_in_ranked_lists./award/ranking/list": "gets rank in the list of",
"/people/person/spouse_s./people/marriage/spouse": "has a marriage with",
"/user/alexander/philosophy/philosopher/interests": "has interests in",
"/location/administrative_division/country": "is a part of",
"/business/job_title/people_with_this_title./business/employment_tenure/company": "is a position in",
"/film/film/film_art_direction_by": "has art director",
"/media_common/netflix_genre/titles": "is the genre of",
"/organization/organization_founder/organizations_founded": "founded",
"/organization/organization/place_founded": "is founded in",
"/people/person/religion": "has the belief of",
"/education/educational_degree/people_with_this_degree./education/education/institution": "is a degree in",
"/film/director/film": "directs"
}
relations_atomic = ["oReact", "oEffect", "oWant", "xAttr", "xEffect", "xIntent", \
"xNeed", "xReact", "xWant"]
split_into_words_atomic = {
'<oReact>': 'As a result, others feel',
'<oEffect>': 'Others then',
# TODO: some value here might not contain 'to' but need 'to'
'<oWant>': 'As a result, others want',
'<xAttr>': 'This person is seen as',
'<xEffect>': 'This person then',
# TODO: some value here might not contain 'to' but need 'to'
'<xIntent>': 'Because this person wanted',
'<xNeed>': 'Before, this person needed',
'<xReact>': 'As a result, this person feels',
'<xWant>': 'As a result, this person wants'
}
def load_conceptnet_noCase(dataset_path=None,
cls_token=None,
eos_token=None,
sep_token=None,
rel_lang=True,
toy=False,
discard_negative=True,
sep=False,
add_sep=False,
prefix=None,
model_type=None):
if not eos_token:
end_token = ""
with open(dataset_path, encoding='utf_8') as f:
f = f.read().splitlines()
if toy:
# no shuffle
# raise Exception
random.shuffle(f)
f = f[:1000]
print("Warning: toy experiment")
output = []
# for line in tqdm(f):
for id_line, line in enumerate(f):
try:
rel, e1, e2, label = line.split("\t")
except:
print(line.split("\t"))
raise ValueError
if discard_negative and label == "0":
continue
if not discard_negative:
# convert to int, to avoid being encoded
try:
label = int(label)
except:
# in ConceptNet training data the label is float
label = -1
# e1
if 'bert' in model_type:
e1 += (" " + sep_token)
e1 = cls_token + " " + e1
else:
if add_sep:
e1 += (" " + sep_token)
if prefix:
e1 = prefix + " " + e1
# e2
e2 += (" " + eos_token)
# rel
if rel_lang:
rel = split_into_words[rel]
if not rel:
continue
else:
rel = rel.lower()
if 'bert' in model_type:
rel += (" " + sep_token)
elif add_sep:
rel += (" " + sep_token)
# [CLS] e1 [SEP] rel [SEP] e2 [EOS]
output.append((e1, rel, e2, label, id_line))
# print some samples for sure
print(output[-3:])
return output
## index builder functions
def load_conceptnet_withCase_withMidPrompt(args,
dataset_path=None,
cases_path=None,
cls_token=None,
eos_token=None,
sep_token=None,
rel_lang=True,
toy=False,
discard_negative=True,
sep=False,
add_sep=False,
prefix=None,
model_type=None,
if_without_case=False,
num_cases=3):
if not eos_token:
end_token = ""
if not args.if_without_case:
with open(cases_path, encoding='utf_8') as case_f:
case_lines = case_f.readlines()
with open(dataset_path, encoding='utf_8') as f:
f = f.read().splitlines()
# # 2400
# print("len(f): ", len(f))
# # 1200
# print("len(case_lines): ", len(case_lines))
# this should hold in most cases (except for using dev2)
if not args.if_without_case:
# case_lines_cnter
if 'dev1' in dataset_path.split('/')[-1]:
case_lines_cnter = 0
elif 'dev2' in dataset_path.split('/')[-1]:
case_lines_cnter = 600
else:
case_lines_cnter = 0
output = []
# for line in tqdm(f):
for id_line, line in enumerate(f):
rel, e1, e2, label = line.split("\t")
if discard_negative and label == "0":
continue
if not discard_negative:
# convert to int, to avoid being encoded
try:
label = int(label)
except:
# in ConceptNet training data the label is float
label = -1
if not args.if_without_case:
# label's positive, begin collect cases
# cases: rel\te1\te2\t\t..
cases = case_lines[case_lines_cnter].strip('\n')
cases = cases.split('\t\t')
# Q: restrict number of cases to use
assert len(cases) == num_cases
if len(cases) > num_cases:
cases = cases[0:num_cases]
case_sents = []
for id_case, case in enumerate(cases):
case = case.split('\t')
# print('case')
# print(case)
case_rel = case[0]
# if no cases for current data
if case_rel == '':
break
if rel_lang:
case_rel = split_into_words[case_rel]
if not case_rel:
raise Exception
else:
case_rel = case_rel.lower()
# can't be 0 or 1
assert args.dataset_selection > 1
if args.use_special_tokens_to_split_retrieved_cases:
case[1] += "<split_source/target>"
case[2] += "<split_cases>"
if args.if_only_use_relation_and_retrieved_target:
case = ' '.join([case_rel, case[2]])
elif args.if_only_use_retrieved_target:
case = case[2]
else:
case = ' '.join([case[1], case_rel, case[2]])
case_sents.append(case)
if args.if_with_strt_mid_promp and not args.if_without_case:
strt_prompt = 'Here are some similar cases to infer from: '
mid_prompt ='With the similar cases we can infer that: '
case_sents = strt_prompt + ' '.join(case_sents) + mid_prompt
else:
case_sents = ' '.join(case_sents)
# case_sents = ' '.join(case_sents) + " " + sep_token
# e2
# e2 <eos>
e2 += (" " + eos_token)
# e1
if args.use_special_tokens_to_split_retrieved_cases:
e1 += (" " + "<split_source/target>")
# rel
if rel_lang:
if rel in split_into_words:
rel = split_into_words[rel]
else:
print('rel:', rel)
rel = rel
if not rel:
print(id_line, rel, e1, e2)
raise Exception
else:
rel = rel.lower()
raise Exception
# COMET baseline
if if_without_case:
# case_sents = '[SEP]'
case_sents = " "
# only print once
if id_line == 0:
print('INFO: No cases are allowed to be used')
output.append((case_sents, e1, rel, e2, label, id_line))
if not args.if_without_case:
case_lines_cnter += 1
# print some samples for sure
print(output[-3:])
return output
def zipped_flatten(outer):
return [(key, fill, el) for key, fill, inner in outer for el in inner]
# add if_without_none
def load_data_atomic(dataset_path, if_without_none=False):
data = []
print("Loading data from ", dataset_path)
df = pandas.read_csv(dataset_path, index_col=0)
df.iloc[:, :9] = df.iloc[:, :9].apply(
lambda col: col.apply(json.loads))
cat_len_noter = []
for cat in relations_atomic:
attr = df[cat]
# print(len(attr))
tmp_rel_data = zipped_flatten(zip(
attr.index, ["<{}>".format(cat)] * len(attr), attr.values))
if if_without_none:
tmp_rel_data_without_none = []
for id_line, line in enumerate(tmp_rel_data):
e1, rel, e2 = line
if "none" in e2.lower():
continue
tmp_rel_data_without_none.append(line)
tmp_rel_data = tmp_rel_data_without_none
data += tmp_rel_data
cat_len_noter.append(len(data))
# TOCHECK: not same number of data?
print('info', len(df), len(data))
print('atomic_data: ', data[0])
return data, cat_len_noter
def load_atomic_noCase(dataset_path=None,
cls_token=None,
eos_token=None,
sep_token=None,
rel_lang=True,
add_sep=False,
prefix=None,
model_type=None):
print(dataset_path)
loaded_data, _ = load_data_atomic(dataset_path)
if not eos_token:
end_token = ""
# with open(dataset_path, encoding='utf_8') as f:
# f = f.read().splitlines()
output = []
# for line in tqdm(f):
for id_line, line in enumerate(loaded_data):
e1, rel, e2 = line
# all label for atomic is 1, to be in the same form with conceptnet
label = 1
# e1
if 'bert' in model_type:
e1 += (" " + sep_token)
e1 = cls_token + " " + e1
else:
if add_sep:
e1 += (" " + sep_token)
if prefix:
e1 = prefix + " " + e1
# e2
e2 += (" " + eos_token)
# rel
if rel_lang:
rel = split_into_words_atomic[rel]
if not rel:
raise Exception
continue
else:
rel = rel.lower()
if 'bert' in model_type:
rel += (" " + sep_token)
elif add_sep:
rel += (" " + sep_token)
# [CLS] e1 [SEP] rel [SEP] e2 [EOS]
output.append((e1, rel, e2, label, id_line))
# print some samples for sure
print(output[-3:])
return output
def load_atomic_withCase(dataset_path=None,
cases_path=None,
cls_token=None,
eos_token=None,
sep_token=None,
rel_lang=True,
add_sep=False,
prefix=None,
model_type=None,
if_without_case=False,
if_allow_same_sub=False):
loaded_data, _ = load_data_atomic(dataset_path)
if not eos_token:
end_token = ""
with open(cases_path, encoding='utf_8') as case_f:
case_lines = case_f.readlines()
output = []
for id_line, line in enumerate(loaded_data):
# label: to keep in same format with conceptnet
label = 1
e1, rel, e2 = line
# label's positive, begin collect cases
# cases: rel\te1\te2\t\t..
cases = case_lines[id_line].strip('\n')
cases = cases.split('\t\t')
assert len(cases) == 5
# Q:
# cases = select_cases_from_given_cases_v2(cases, e1, rel, e2, if_allow_same_sub)
# cases = cases[0:5]
case_sents = []
for id_case, case in enumerate(cases):
case = case.split('\t')
# print('case')
# print(case)
case_rel = case[0]
# if no cases for current data
if case_rel == '' or case_rel == '\n':
break
if rel_lang:
if case_rel in split_into_words_atomic:
case_rel = split_into_words_atomic[case_rel]
else:
print('case_rel, case')
print(case_rel, case)
raise Exception
if not case_rel:
raise Exception
else:
case_rel = case_rel.lower()
# raise Exception
# add '.' to obj of an case that not ends with '.'
if not case[2].strip().endswith('.'):
case[2] += '.'
case = ' '.join([case[1] + '.', case_rel, case[2]])
case_sents.append(case)
case_sents = ' '.join(case_sents)
# case_sents
# e1 rel e2. e1 rel e2. ...[SEP]
if 'bert' in model_type:
# e1 += (" " + sep_token)
# e1 = cls_token + " " + e1
case_sents += (" " + sep_token)
case_sents = cls_token + " " + case_sents
else:
if add_sep:
# e1 += (" " + sep_token)
case_sents += (" " + sep_token)
else:
raise Exception
if prefix:
# e1 = prefix + " " + e1
case_sents = prefix + " " + case_sents
raise Exception
# e2
# e2 <eos>
e2 += (" " + eos_token)
# e1
e1 += '.'
# rel
if rel_lang:
if rel in split_into_words_atomic:
rel = split_into_words_atomic[rel]
else:
print('rel:', rel)
rel = rel
raise Exception
if not rel:
print(id_line, rel, e1, e2)
raise Exception
else:
rel = rel.lower()
# JUSTTRY:
if if_without_case:
case_sents = ''
# only print once
if id_line == 0:
print('INFO: No cases are allowed to be used')
output.append((case_sents, e1, rel, e2, label, id_line))
# print some samples for sure
print(output[-3:])
return output
def load_conceptnet_pure(dataset_path=None, rel_lang=True, discard_negative=True):
with open(dataset_path, encoding='utf_8') as f:
f = f.read().splitlines()
output = []
# for line in tqdm(f):
for id_line, line in enumerate(f):
rel, e1, e2, label = line.split("\t")
# filter data instances whose label is not positive
if discard_negative and label == "0":
continue
e1 = e1.strip()
e2 = e2.strip()
if e1.endswith('.'):
e1 = e1[:-1]
if e2.endswith('.'):
e2 = e2[:-1]
# print("e2 ends with '.'")
if not discard_negative:
# convert to int, to avoid being encoded
try:
label = int(label)
except:
# in ConceptNet training data the label is float
label = -1
# rel
if rel_lang:
rel = split_into_words[rel]
if not rel:
print("Warning: ", rel, " not found in dict split_into_words")
continue
else:
rel = rel.lower()
# no special tokens added
output.append((e1, rel, e2, label, id_line))
# print some samples
print("load_conceptnet_pure, output[-3:]: ", output[-3:])
return output
# load_atomic_pure: not adding any special tokens
def load_atomic_pure(dataset_path=None, rel_lang=True, toy=False, if_without_none=False):
if not toy:
loaded_data, _ = load_data_atomic(dataset_path, if_without_none=if_without_none)
else:
# this loaded_data is sampled
# with open('~/Data/try/sampled_atomic_loaded_data.json', 'r') as f:
# loaded_data = json.load(f)
raise Exception("Toy data is used")
output = []
for id_line, line in enumerate(loaded_data):
e1, rel, e2 = line
# Newly added in 2/19/2021; do not need to predict '.', we added '.' for each additional case
e1 = e1.strip()
rel = rel.strip()
e2 = e2.strip()
if e1.endswith('.'):
e1 = e1[:-1]
if e2.endswith('.'):
e2 = e2[:-1]
# rel
if rel_lang:
rel = split_into_words_atomic[rel]
if not rel:
raise Exception
else:
rel = rel.lower()
# all label for atomic is 1, to be in the same form with conceptnet
label = 1
# no special tokens
output.append((e1, rel, e2, label, id_line))
# print some samples for sure
print("load_atomic_pure, output[-3:]:", output[-3:])
return output
# output: train_datasets, eval_datasets, test_datasets
# train_datasets: [(e1, rel, e2, label, id_line), (), ...]
def load_shakespear(args, dataset_path):
ori_dataset_path = os.path.join(dataset_path, 'Shakes_data')
processed_dataset_path = os.path.join(dataset_path, 'Shakes_processed_lines')
all_file_names = os.listdir(ori_dataset_path)
# newly added
all_file_names = sorted(all_file_names)
train_datasets, eval_datasets, test_datasets = [], [], []
# for retriever's usage
train_lines, eval_lines, test_lines = [], [], []
assert len(all_file_names) % 2 == 0 and len(all_file_names) > 0
## get lines and datasets
for ith_poem in range(int(len(all_file_names)/2)):
tmp_modern_file = all_file_names[2*ith_poem]
tmp_origin_file = all_file_names[2*ith_poem+1]
# same poem
assert tmp_modern_file.split('_')[0] == tmp_origin_file.split('_')[0]
# modern and original
assert 'modern' in tmp_modern_file and 'original' in tmp_origin_file
cur_lines = train_lines
cur_datasets = train_datasets
if 'twelfthnight' in tmp_modern_file:
cur_lines = eval_lines
cur_datasets = eval_datasets
elif 'romeojuliet' in tmp_modern_file:
cur_lines = test_lines
cur_datasets = test_datasets
len_cur_datasets = len(cur_datasets)
# open modern file
cnt_included_data_cur_file = 0
with open(os.path.join(ori_dataset_path, tmp_modern_file), 'r') as fm, \
open(os.path.join(ori_dataset_path, tmp_origin_file), 'r') as fo:
cur_modern_lines = fm.readlines()
cur_origin_lines = fo.readlines()
assert len(cur_modern_lines) == len(cur_origin_lines) and len(cur_origin_lines) > 0
for id_line in range(len(cur_modern_lines)):
tmp_modern_line = cur_modern_lines[id_line].strip()
tmp_origin_line = cur_origin_lines[id_line].strip()
if tmp_modern_line == '':
assert tmp_origin_line == ''
print("Warning: tmp_modern_line is '', which is empty")
continue
e1 = tmp_modern_line
if args.if_use_relation_for_shakes:
rel = "Shakespeare's style is "
else:
rel = ' '
e2 = tmp_origin_line
label = 1
if len(e1) >= args.max_e1:
print("e1: {}, max_e1: {}".format(e1, args.max_e1))
continue
if len(e2) >= args.max_e2:
print("e2: {}, max_e2: {}".format(e2, args.max_e2))
continue
cnt_included_data_cur_file += 1
cur_lines.append(rel + '\t' + e1 + '\t' + e2 + '\n')
# cur_datasets.append((e1, rel, e2, label, len_cur_datasets + id_line))
cur_datasets.append((e1, rel, e2, label, len_cur_datasets + cnt_included_data_cur_file))
print("len(train_lines): {}, len(eval_lines): {}, len(test_lines): {}".format(len(train_lines), len(eval_lines), len(test_lines)))
print("len(train_datasets): {}, len(eval_datasets): {}, len(test_datasets): {}".format(len(train_datasets), len(eval_datasets), len(test_datasets)))
if 'train_lines.txt' not in os.listdir(processed_dataset_path):
print('Creating train lines, eval lines and test lines')
with open(os.path.join(processed_dataset_path, 'train_lines.txt'), 'w') as f:
f.writelines(train_lines)
with open(os.path.join(processed_dataset_path, 'eval_lines.txt'), 'w') as f:
f.writelines(eval_lines)
with open(os.path.join(processed_dataset_path, 'test_lines.txt'), 'w') as f:
f.writelines(test_lines)
return [train_datasets], [eval_datasets], [test_datasets]
# load and preprocess shakespeare data during generation
def load_shakes_withCase(args,
dataset_path=None,
cases_path=None,
cls_token=None,
eos_token=None,
sep_token=None,
rel_lang=True,
add_sep=False,
prefix=None,
model_type=None,
if_without_case=False,
if_allow_same_sub=False):
_, _, loaded_data = load_shakespear(args, dataset_path=dataset_path)
assert len(loaded_data) == 1
loaded_data = loaded_data[0]
# loaded_data, _ = load_data_atomic(dataset_path)
if not eos_token:
end_token = ""
if not args.if_without_case:
with open(cases_path, encoding='utf_8') as case_f:
case_lines = case_f.readlines()
if not len(case_lines) == len(loaded_data):
print('len(case_lines): ', len(case_lines), 'len(loaded_data): ', len(loaded_data))
raise Exception("len(case_lines) != len(loaded_data)")
print('len(case_lines): ', len(case_lines), 'len(loaded_data): ', len(loaded_data))
output = []
for id_line, line in enumerate(loaded_data):
# label: to keep in same format with conceptnet
label = 1
try:
e1, rel, e2, label, data_id = line
except:
print("line: ", line)
raise Exception
# e2 <eos>
e2 += (" " + eos_token)
if args.use_special_tokens_to_split_retrieved_cases:
e1 += (" " + "<split_source/target>")
if not args.if_without_case:
# label's positive, begin collect cases
# cases: rel\te1\te2\t\t..
cases = case_lines[id_line].strip('\n')
cases = cases.split('\t\t')
# len(cases) should equals num_cases
assert len(cases) >= 1
case_sents = []
for id_case, case in enumerate(cases):
case = case.split('\t')
case_rel = case[0]
# case[2] += ';'
if args.use_special_tokens_to_split_retrieved_cases:
case[1] += "<split_source/target>"
case[2] += "<split_cases>"
if args.if_only_use_relation_and_retrieved_target:
case = ' '.join([case_rel, case[2]])
elif args.if_only_use_retrieved_target:
case = case[2]
else:
case = ' '.join([case[1], case_rel, case[2]])
case_sents.append(case)
if args.if_with_strt_mid_promp and not args.if_without_case:
strt_prompt = 'Here are some similar cases to infer from: '
mid_prompt ='With the similar cases we can infer that: '
case_sents = strt_prompt + ' '.join(case_sents) + mid_prompt
else:
case_sents = ' '.join(case_sents)
case_sents += " " + sep_token
else:
# case_sents = sep_token
case_sents = " "
# only print once
if id_line == 0:
print('INFO: No cases are allowed to be used')
output.append((case_sents, e1, rel, e2, label, id_line))
# print some samples for sure
print(output[-3:])
return output
def load_e2e(args, dataset_path, data_type):
if data_type == 'train':
data = pd.read_csv(os.path.join(dataset_path, 'trainset.csv'))
path_lines = os.path.join(dataset_path, 'train_lines.txt')
elif data_type == 'eval':
data = pd.read_csv(os.path.join(dataset_path, 'devset.csv'))
path_lines = os.path.join(dataset_path, 'eval_lines.txt')
elif data_type == 'test':
data = pd.read_csv(os.path.join(dataset_path, 'testset_w_refs.csv'))
path_lines = os.path.join(dataset_path, 'test_lines.txt')
datasets, lines = [], []
ref = data['ref']
mr = data['mr']
assert len(ref) == len(mr)
print('len(lines): ', len(lines))
print('len(mr): ', len(mr))
for ith_table in range(len(mr)):
if not ('\r\n' in mr[ith_table] or '\n' in mr[ith_table]):
e1 = mr[ith_table]
else:
print("Warning: found '\\r\\n': mr[ith_table]: {}".format(mr[ith_table]))
e1 = mr[ith_table].replace('\r\n', ' ')
e1 = e1.replace('\n', ' ')
rel = ' '
if not ('\r\n' in ref[ith_table] or '\n' in ref[ith_table]):
e2 = ref[ith_table]
else:
print("Warning: found '\\r\\n': ref[ith_table]: {}".format(ref[ith_table]))
e2 = ref[ith_table].replace('\r\n', ' ')
e2 = e2.replace('\n', ' ')
print("e2: ", e2)
label = 1
id_line = ith_table
lines.append(rel + '\t' + e1 + '\t' + e2 + '\n')
datasets.append((e1, rel, e2, label, id_line))
assert len(lines) == len(mr)
# write lines
with open(path_lines, 'w') as f:
f.writelines(lines)
# checking whether more lines are created
with open(path_lines, 'r') as f:
tmp_lines = f.readlines()
try:
assert len(tmp_lines) == len(lines)
except:
print('len(tmp_lines): ', len(tmp_lines))
print('len(lines): ', len(lines))
raise Exception
return [datasets]
# load and preprocess e2e data during generation
def load_e2e_withCase(args,
dataset_path=None,
cases_path=None,