-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmqa35.py
6413 lines (5051 loc) · 288 KB
/
tmqa35.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().run_line_magic('autosave', '180')
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
import requests
import time
from datetime import datetime
import itertools as it
import re
#import numpy
from copy import copy
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
#from pprint import pprint
import time
import json
import os
import networkx as nx
from math import sqrt
import spacy
from hdt import HDTDocument
import multiprocessing as mp
import torch
import random
from transformers import BertTokenizer, BertModel, BertForMaskedLM, GPT2Tokenizer, GPT2LMHeadModel
os.environ['CUDA_VISIBLE_DEVICES'] = "0,1"
from deepcorrect import DeepCorrect
corrector = DeepCorrect('data/deep_punct/deeppunct_params_en', 'data/deep_punct/deeppunct_checkpoint_wikipedia')
# In[3]:
print("Hi! My PID is",os.getpid())
# In[4]:
hdt_wd = HDTDocument("data/kb/wikidata2018_09_11.hdt")
# In[5]:
# Load pre-trained language models and tokenizers
#https://github.com/huggingface/transformers/blob/master/docs/source/pretrained_models.rst
#bert_modelpath = "bert-large-uncased"
#bert_model = BertForMaskedLM.from_pretrained(bert_modelpath)
#bert_tokenizer = BertTokenizer.from_pretrained(bert_modelpath)
#
#gpt2_modelpath = "gpt2-xl"
#gpt2_tokenizer = GPT2Tokenizer.from_pretrained(gpt2_modelpath)
#gpt2_model = GPT2LMHeadModel.from_pretrained(gpt2_modelpath)
# In[6]:
#nlp = spacy.load("en_core_web_lg")
nlp = spacy.load("/data/users/romain.claret/tm/wiki-kb-linked-entities/nlp_custom_6")
#print(nlp.pipeline)
# In[7]:
# load settings
with open( "settings-graphqa.json", "r") as settings_data:
settings = json.load(settings_data)
use_cache = settings['use_cache']
save_cache = settings['save_cache']
cache_path = settings['cache_path']
#cache_path
# In[8]:
save_cache = True
def save_cache_data(save_cache=save_cache):
if save_cache:
with open(os.path.join(cache_path,'wd_local_statements_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_local_statements_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'wd_labels_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_labels_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'wd_local_word_ids_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_local_word_ids_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'wd_online_word_ids_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_online_word_ids_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'wd_local_predicate_ids_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_local_predicate_ids_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'wd_online_predicate_ids_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(wd_online_predicate_ids_dict, separators=(',',':')).encode('utf8'))
with open(os.path.join(cache_path,'word_similarities_dict.json'), 'wb') as outfile:
outfile.write(json.dumps(word_similarities_dict, separators=(',',':')).encode('utf8'))
# In[9]:
# Load statements cache
use_cache = True
def load_cache_data(use_cache=False):
if use_cache:
path_wd_local_statements_dict = "wd_local_statements_dict.json"
path_wd_labels_dict = 'wd_labels_dict.json'
path_wd_local_word_ids_dict = 'wd_local_word_ids_dict.json'
path_wd_online_word_ids_dict = 'wd_online_word_ids_dict.json'
path_wd_local_predicate_ids_dict = 'wd_local_predicate_ids_dict.json'
path_wd_online_predicate_ids_dict = 'wd_online_predicate_ids_dict.json'
path_word_similarities_dict = 'word_similarities_dict.json'
else:
path_wd_local_statements_dict = "wd_local_statements_dict_empty.json"
path_wd_labels_dict = 'wd_labels_dict_empty.json'
path_wd_local_word_ids_dict = 'wd_local_word_ids_dict_empty.json'
path_wd_online_word_ids_dict = 'wd_online_word_ids_dict_empty.json'
path_wd_local_predicate_ids_dict = 'wd_local_predicate_ids_dict_empty.json'
path_wd_online_predicate_ids_dict = 'wd_online_predicate_ids_dict_empty.json'
path_word_similarities_dict = 'word_similarities_dict_empty.json'
with open(os.path.join(cache_path,path_wd_local_statements_dict), "rb") as data:
wd_local_statements_dict = json.load(data)
with open(os.path.join(cache_path,path_wd_labels_dict), "rb") as data:
wd_labels_dict = json.load(data)
with open(os.path.join(cache_path,path_wd_local_word_ids_dict), "rb") as data:
wd_local_word_ids_dict = json.load(data)
with open(os.path.join(cache_path,path_wd_online_word_ids_dict), "rb") as data:
wd_online_word_ids_dict = json.load(data)
with open(os.path.join(cache_path,path_wd_local_predicate_ids_dict), "rb") as data:
wd_local_predicate_ids_dict = json.load(data)
with open(os.path.join(cache_path,path_wd_online_predicate_ids_dict), "rb") as data:
wd_online_predicate_ids_dict = json.load(data)
with open(os.path.join(cache_path,path_word_similarities_dict), "rb") as data:
word_similarities_dict = json.load(data)
return (wd_local_statements_dict, wd_labels_dict,
wd_local_word_ids_dict, wd_online_word_ids_dict,
wd_local_predicate_ids_dict, wd_online_predicate_ids_dict,
word_similarities_dict)
(wd_local_statements_dict, wd_labels_dict,
wd_local_word_ids_dict, wd_online_word_ids_dict,
wd_local_predicate_ids_dict, wd_online_predicate_ids_dict,
word_similarities_dict) = load_cache_data(use_cache=True)
#print("wd_local_statements_dict",len(wd_local_statements_dict))
#print("wd_labels_dict",len(wd_labels_dict))
#print("wd_local_word_ids_dict",len(wd_local_word_ids_dict))
#print("wd_online_word_ids_dict",len(wd_online_word_ids_dict))
#print("wd_local_predicate_ids_dict",len(wd_local_predicate_ids_dict))
#print("wd_online_predicate_ids_dict",len(wd_online_predicate_ids_dict))
#print("word_similarities_dict",len(word_similarities_dict))
# In[10]:
def get_kb_ents(text):
#doc = nlp_kb(text)
doc = nlp(text)
#for ent in doc.ents:
# print(" ".join(["ent", ent.text, ent.label_, ent.kb_id_]))
return doc.ents
#ent_text_test = (
# "In The Hitchhiker's Guide to the Galaxy, written by Douglas Adams, "
# "Douglas reminds us to always bring our towel, even in China or Brazil. "
# "The main character in Doug's novel is the man Arthur Dent, "
# "but Dougledydoug doesn't write about George Washington or Homer Simpson."
#)
#
#en_text_test_2 = ("Which actor voiced the Unicorn in The Last Unicorn?")
#
#print([ent.kb_id_ for ent in get_kb_ents(ent_text_test)])
#[ent.kb_id_ for ent in get_kb_ents(en_text_test_2)]
# In[11]:
def get_nlp(sentence, autocorrect=False, banning_str=False):
sentence = sentence.replace("’", "\'")
nlp_sentence = nlp(sentence)
nlp_sentence_list = list(nlp_sentence)
meaningful_punct = []
for i_t, t in enumerate(nlp_sentence_list):
#print(t,t.pos_, t.lemma_)
if t.lemma_ == "year":
nlp_sentence_list[i_t] = "date"
elif t.text == "\'s" or t.text == "s":
if t.lemma_ == "be" or t.lemma_ == "s":
nlp_sentence_list[i_t] = "is"
else: nlp_sentence_list[i_t] = ""
elif t.text == "\'ve" or t.text == "ve":
if t.lemma_ == "have":
nlp_sentence_list[i_t] = "have"
else: nlp_sentence_list[i_t] = ""
elif t.text == "\'re" or t.text == "re":
if t.lemma_ == "be":
nlp_sentence_list[i_t] = "are"
else: nlp_sentence_list[i_t] = ""
elif t.text == "\'ll" or t.text == "ll":
if t.lemma_ == "will":
nlp_sentence_list[i_t] = "will"
else: nlp_sentence_list[i_t] = ""
elif t.text == "\'d" or t.text == "d":
if t.lemma_ == "have":
nlp_sentence_list[i_t] = "had"
elif t.lemma_ == "would":
nlp_sentence_list[i_t] = "would"
else: nlp_sentence_list[i_t] = ""
elif t.is_space:
nlp_sentence_list[i_t] = ""
elif t.pos_ == "PUNCT":
if t.text.count(".") > 2:
meaningful_punct.append((i_t,"..."))
nlp_sentence_list[i_t] = "..."
else:
nlp_sentence_list[i_t] = ""
else: nlp_sentence_list[i_t] = nlp_sentence_list[i_t].text
nlp_sentence_list = [w for w in nlp_sentence_list if w]
#print("nlp_sentence_list",nlp_sentence_list)
if autocorrect:
nlp_sentence = " ".join(nlp_sentence_list)
nlp_sentence = (nlp_sentence.replace("’", "\'").replace("€", "euro").replace("ç", "c")
.replace("à", "a").replace("é","e").replace("ä","a").replace("ö","o")
.replace("ü","u").replace("è","e").replace("¨","").replace("ê","e")
.replace("â","a").replace("ô","o").replace("î","i").replace("û","u")
.replace("_"," ").replace("°","degree").replace("§","section")
.replace("š","s").replace("Š","S").replace("ć","c").replace("Ç", "C")
.replace("À", "A").replace("É","E").replace("Ä","A").replace("Ö","O")
.replace("Ü","U").replace("È","E").replace("Ê","E").replace("Ë","E")
.replace("Â","A").replace("Ô","O").replace("Î","I").replace("Û","U")
.replace("á","a").replace("Á","Á").replace("ó","o").replace("Ó","O")
.replace("ú","u").replace("Ú","U").replace("í","i").replace("Í","I")
.replace("–","-").replace("×","x").replace("“","\"").replace("ř","r")
.replace("ø","o").replace("ı","i").replace("ş","s").replace("Á","A")
.replace("Ō","O").replace("ã","a").replace("ū","u").replace("ō","o")
.replace("ñ","n").replace("Ł","L").replace("ł","l").replace("Ñ","N")
.replace("Ō","O").replace("Ā","A").replace("ē","e").replace("ǟ","a")
.replace("ȱ","o").replace("ō","o").replace("ȭ","o").replace("ī","i")
.replace("ū","u").replace("ȯ","o").replace("ä","a").replace("õ","o")
.replace("Ā","A").replace("ū","u").replace("ī","i").replace("ē","e")
.replace("ō","o").replace("Ā","A").replace("ā","a").replace("Ǟ","A")
.replace("ǟ","a").replace("Ḇ","B").replace("ḇ","b").replace("C̄","C")
.replace("c̄","c").replace("Ḏ","D").replace("ḏ","d").replace("ḕ","e")
.replace("Ē","E").replace("ē","e").replace("Ḕ","E").replace("Ḗ","E")
.replace("ḗ","e").replace("Ḡ","G").replace("ḡ","g").replace("ẖ","h")
.replace("Ī","ī").replace("Ḹ","L").replace("ḹ","l").replace("Ḻ","L")
.replace("ḻ","l").replace("Ṉ","N").replace("ṉ","n").replace("Ȫ","O")
.replace("ȫ","o").replace("Ṑ","O").replace("ṑ","o").replace("ß","ss")
.replace("Ṓ","O").replace("ṓ","o").replace("Ṝ","R").replace("ṝ","r")
.replace("Ṟ","R").replace("ṟ","r").replace("Ṯ","T").replace("ṯ","t")
.replace("Ū","U").replace("ū","u").replace("Ǘ","U").replace("ǘ","u")
.replace("Ǖ","U").replace("ǖ","u").replace("Ṻ","U").replace("ṻ","u")
.replace("Ȳ","Y").replace("ȳ","y").replace("ẕ","z").replace("Ẕ","Z")
.replace("Ǣ","AE").replace("ǣ","ae").replace("ė","e").replace("å","a")
.replace("æ","ae").replace("Æ","AE").replace("ą","a").replace("ț","t")
.replace("ï","i").replace("Ț","T").replace("İ","I").replace("ʻ","\'")
.replace("ń","n").replace("Ń","N").replace("Č","C").replace("ø","o")
.replace("č","c").replace("ž","z").replace("Ž","Z").replace("Ø","O")
.replace("ễ","e").replace("Ê","E").replace("ă","a").replace("Ă","A")
.replace("ệ","e").replace("Ş","S").replace("ş","s").replace("~"," ")
.replace("œ","oe").replace("Œ","OE").replace("ě","e").replace("Ě","E")
.replace("đ","d").replace("Đ","D").replace("Я","R").replace("я","r")
.replace("ý","y").replace("Ý","Y").replace("Ż","Z").replace("ż","z")
.replace("ș","s").replace("¡","i").replace("´","\'").replace("Ș","S")
.replace("ò","o").replace("Ò","O").replace("ë","e")
)
if banning_str:
for ban in banning_str:
nlp_sentence = nlp_sentence.replace(ban[0],ban[1])
nlp_sentence = corrector.correct(nlp_sentence)
nlp_sentence = nlp_sentence[0]["sequence"]
nlp_sentence = nlp(nlp_sentence)
nlp_sentence_list = list(nlp_sentence)
for i_t, t in enumerate(nlp_sentence_list):
if t.pos_ == "PUNCT":
if i_t in [mpunct[0] for mpunct in meaningful_punct]:
for mpunct in meaningful_punct:
if i_t == mpunct[0]:
nlp_sentence_list[mpunct[0]] = mpunct[1]
else: nlp_sentence_list[i_t] = ''
else:
nlp_sentence_list[i_t] = nlp_sentence_list[i_t].text
for mpunct in meaningful_punct:
if mpunct[0] < len(nlp_sentence_list):
if nlp_sentence_list[mpunct[0]] != mpunct[1]:
nlp_sentence_list.insert(mpunct[0], mpunct[1])
return nlp(" ".join(nlp_sentence_list).replace(" ", " ").replace(". &",".").replace("/",""))
#get_nlp("Which genre of album is harder.....faster?", autocorrect=True)
#get_nlp("Which genre of album is Harder ... Faster", autocorrect=True)
#get_nlp("Which home is an example of italianate architecture?", autocorrect=True)
#get_nlp("Your mom's father, were nice in the Years.!?\'\":`’^!$£€\(\)ç*+%&/\\\{\};,àéäöüè¨êâôîû~-_<>°§...@.....", autocorrect=True)
#get_nlp("of what nationality is ken mcgoogan", autocorrect=True)
#get_nlp("you're fun", autocorrect=True)
#get_nlp("where's the fun", autocorrect=True)
#get_nlp("whats the name of the organization that was founded by frei otto", True)
#get_nlp("Hurry! We’re late!",True)
#get_nlp("Who was an influential figure for miško Šuvaković",True)
#get_nlp("what is the second level division of the division crixás do tocantins",True)
#get_nlp("what is the second level division of the division crixás do tocantins",True)
#get_nlp("2×4",autocorrect=True,banning_str=[["×","x"]])
#get_nlp("what types of music is p.a.r.c.e.",autocorrect=True)
# In[12]:
def is_wd_entity(to_check):
pattern = re.compile('^Q[0-9]*$')
if pattern.match(to_check.strip()): return True
else: return False
def is_wd_predicate(to_check):
pattern = re.compile('^P[0-9]*$')
if pattern.match(to_check.strip()): return True
else: return False
def is_valide_wd_id(to_check):
if is_wd_entity(to_check) or is_wd_predicate(to_check): return True
else: return False
#print(is_wd_entity("Q155"))
# In[13]:
# TODO redo the functions and optimize
def is_entity_or_literal(to_check):
if is_wd_entity(to_check.strip()):
return True
pattern = re.compile('^[A-Za-z0-9]*$')
if len(to_check) == 32 and pattern.match(to_check.strip()):
return False
return True
# return if the given string is a literal or a date
def is_literal_or_date(to_check):
return not('www.wikidata.org' in to_check)
# return if the given string describes a year in the format YYYY
def is_year(year):
pattern = re.compile('^[0-9][0-9][0-9][0-9]$')
if not(pattern.match(year.strip())):
return False
else:
return True
# return if the given string is a date
def is_date(date):
pattern = re.compile('^[0-9]+ [A-z]+ [0-9][0-9][0-9][0-9]$')
if not(pattern.match(date.strip())):
return False
else:
return True
# return if the given string is a timestamp
def is_timestamp(timestamp):
pattern = re.compile('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T00:00:00Z')
if not(pattern.match(timestamp.strip())):
return False
else:
return True
# convert the given month to a number
def convert_month_to_number(month):
return{
"january" : "01",
"february" : "02",
"march" : "03",
"april" : "04",
"may" : "05",
"june" : "06",
"july" : "07",
"august" : "08",
"september" : "09",
"october" : "10",
"november" : "11",
"december" : "12"
}[month.lower()]
# convert a date from the wikidata frontendstyle to timestamp style
def convert_date_to_timestamp (date):
sdate = date.split(" ")
# add the leading zero
if (len(sdate[0]) < 2):
sdate[0] = "0" + sdate[0]
return sdate[2] + '-' + convert_month_to_number(sdate[1]) + '-' + sdate[0] + 'T00:00:00Z'
# convert a year to timestamp style
def convert_year_to_timestamp(year):
return year + '-01-01T00:00:00Z'
# get the wikidata id of a wikidata url
def wikidata_url_to_wikidata_id(url):
if not url:
return False
if "XMLSchema#dateTime" in url or "XMLSchema#decimal" in url:
date = url.split("\"", 2)[1]
date = date.replace("+", "")
return date
if(is_literal_or_date(url)):
if is_year(url):
return convert_year_to_timestamp(url)
if is_date(url):
return convert_date_to_timestamp(url)
else:
url = url.replace("\"", "")
return url
else:
url_array = url.split('/')
# the wikidata id is always in the last component of the id
return url_array[len(url_array)-1]
# fetch all statements where the given qualifier statement occurs as subject
def get_all_statements_with_qualifier_as_subject(qualifier):
statements = []
triples, cardinality = hdt_wd.search_triples(qualifier, "", "")
for triple in triples:
sub, pre, obj = triple
# only consider triples with a wikidata-predicate
if pre.startswith("http://www.wikidata.org/"):
statements.append({'entity': sub, 'predicate': pre, 'object': obj})
return statements
# fetch the statement where the given qualifier statement occurs as object
def get_statement_with_qualifier_as_object(qualifier):
triples, cardinality = hdt_wd.search_triples("", "", qualifier)
for triple in triples:
sub, pre, obj = triple
# only consider triples with a wikidata-predicate
if pre.startswith("http://www.wikidata.org/") and sub.startswith("http://www.wikidata.org/entity/Q"):
return (sub, pre, obj)
return False
# returns all statements that involve the given entity
def get_all_statements_of_entity(entity_id):
# check entity pattern
if not is_wd_entity(entity_id.strip()):
return False
if wd_local_statements_dict.get(entity_id) != None:
#print("saved statement")
return wd_local_statements_dict[entity_id]
entity = "http://www.wikidata.org/entity/"+entity_id
statements = []
# entity as subject
triples_sub, cardinality_sub = hdt_wd.search_triples(entity, "", "")
# entity as object
triples_obj, cardinality_obj = hdt_wd.search_triples("", "", entity)
if cardinality_sub + cardinality_obj > 5000:
wd_local_statements_dict[entity_id] = []
return []
# iterate through all triples in which the entity occurs as the subject
for triple in triples_sub:
sub, pre, obj = triple
# only consider triples with a wikidata-predicate or if it is an identifier predicate
if not pre.startswith("http://www.wikidata.org/"):# or (wikidata_url_to_wikidata_id(pre) in identifier_predicates):
continue
# object is statement
if obj.startswith("http://www.wikidata.org/entity/statement/"):
qualifier_statements = get_all_statements_with_qualifier_as_subject(obj)
qualifiers = []
for qualifier_statement in qualifier_statements:
if qualifier_statement['predicate'] == "http://www.wikidata.org/prop/statement/" + wikidata_url_to_wikidata_id(pre):
obj = qualifier_statement['object']
elif is_entity_or_literal(wikidata_url_to_wikidata_id(qualifier_statement['object'])):
qualifiers.append({
"qualifier_predicate":{
"id": wikidata_url_to_wikidata_id(qualifier_statement['predicate'])
},
"qualifier_object":{
"id": wikidata_url_to_wikidata_id(qualifier_statement['object'])
}})
statements.append({'entity': {'id': wikidata_url_to_wikidata_id(sub)}, 'predicate': {'id': wikidata_url_to_wikidata_id(pre)}, 'object': {'id': wikidata_url_to_wikidata_id(obj)}, 'qualifiers': qualifiers})
else:
statements.append({'entity': {'id': wikidata_url_to_wikidata_id(sub)}, 'predicate': {'id': wikidata_url_to_wikidata_id(pre)}, 'object': {'id': wikidata_url_to_wikidata_id(obj)}, 'qualifiers': []})
# iterate through all triples in which the entity occurs as the object
for triple in triples_obj:
sub, pre, obj = triple
# only consider triples with an entity as subject and a wikidata-predicate or if it is an identifier predicate
if not sub.startswith("http://www.wikidata.org/entity/Q"):# or not pre.startswith("http://www.wikidata.org/") or wikidata_url_to_wikidata_id(pre) in identifier_predicates:
continue
if sub.startswith("http://www.wikidata.org/entity/statement/"):
statements_with_qualifier_as_object = get_statement_with_qualifier_as_object(sub, process)
# if no statement was found continue
if not statements_with_qualifier_as_object:
continue
main_sub, main_pred, main_obj = statements_with_qualifier_as_object
qualifier_statements = get_all_statements_with_qualifier_as_subject(sub)
qualifiers = []
for qualifier_statement in qualifier_statements:
if wikidata_url_to_wikidata_id(qualifier_statement['predicate']) == wikidata_url_to_wikidata_id(main_pred):
main_obj = qualifier_statement['object']
elif is_entity_or_literal(wikidata_url_to_wikidata_id(qualifier_statement['object'])):
qualifiers.append({
"qualifier_predicate":{"id": wikidata_url_to_wikidata_id(qualifier_statement['predicate'])},
"qualifier_object":{"id": wikidata_url_to_wikidata_id(qualifier_statement['object'])}
})
statements.append({
'entity': {'id': wikidata_url_to_wikidata_id(main_sub)},
'predicate': {'id': wikidata_url_to_wikidata_id(main_pred)},
'object': {'id': wikidata_url_to_wikidata_id(main_obj)},
'qualifiers': qualifiers
})
else:
statements.append({'entity': {'id': wikidata_url_to_wikidata_id(sub)}, 'predicate': {'id': wikidata_url_to_wikidata_id(pre)}, 'object': {'id': wikidata_url_to_wikidata_id(obj)}, 'qualifiers': []})
# cache the data
wd_local_statements_dict[entity_id] = statements
return statements
#print(len(get_all_statements_of_entity("Q267721")))
#for s in get_all_statements_of_entity("Q267721"):
# print(s)
#save_cache_data(save_cache=save_cache)
# In[14]:
def get_wd_ids_online(name, is_predicate=False, top_k=3, sim_threshold=0.5):
name = name.split('(')[0]
if is_predicate and wd_online_predicate_ids_dict.get(name) != None and use_cache and len(wd_online_predicate_ids_dict)>0:
res_ids = wd_online_predicate_ids_dict[name][:top_k]
to_return = []
for res_id in res_ids:
if get_nlp(get_wd_label(res_id)).similarity(get_nlp(name)) >= sim_threshold:
to_return.append(res_id)
return to_return #wd_online_predicate_ids_dict[name][:top_k]
elif not is_predicate and wd_online_word_ids_dict.get(name) != None and use_cache and len(wd_online_word_ids_dict)>0:
#print("saved word online")
res_ids = wd_online_word_ids_dict[name][:top_k]
to_return = []
for res_id in res_ids:
if get_nlp(get_wd_label(res_id)).similarity(get_nlp(name)) >= sim_threshold:
to_return.append(res_id)
return to_return #wd_online_word_ids_dict[name][:top_k]
request_successfull = False
entity_ids = ""
while not request_successfull:
try:
if is_predicate:
entity_ids = requests.get('https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&language=en&type=property&limit=' + str(top_k) + '&search='+name).json()
else:
entity_ids = requests.get('https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&language=en&limit=' + str(top_k) + '&search='+name).json()
request_successfull = True
except Exception as e:
print("ERROR:",e)
time.sleep(5)
results = entity_ids.get("search")
if not results:
if is_predicate: wd_online_predicate_ids_dict[name] = []
else: wd_online_word_ids_dict[name] = []
return []
if not len(results):
if is_predicate: wd_online_predicate_ids_dict[name] = []
else: wd_online_word_ids_dict[name] = []
return []
res = []
for result in results:
res_id = result['id']
#print(res_id,get_nlp(get_wd_label(res_id)).similarity(get_nlp(name)))
if get_nlp(get_wd_label(res_id)).similarity(get_nlp(name)) >= sim_threshold:
res.append(res_id)
if is_predicate: wd_online_predicate_ids_dict[name] = res
else: wd_online_word_ids_dict[name] = res
if res:
return res[:top_k]
else:
return []
#print(get_wd_ids_online("did", is_predicate=False, top_k=3))
#print(get_wd_ids_online("voiced", is_predicate=True, top_k=3))
# In[15]:
# very computational
def get_most_similar(word, top_k=3):
BANNED_WORDS = ["benteen"]
if word in BANNED_WORDS:
return []
print("behold: get_most_similar started with:", word)
word_text = str(word.lower())
if word_similarities_dict.get(word) != None and use_cache and len(word_similarities_dict)>0:
return word_similarities_dict[word][:top_k]
word = nlp.vocab[word_text]
queries = [w for w in word.vocab if w.is_lower == word.is_lower and w.prob >= -15]
if len(queries) > 32994:
return []
by_similarity = sorted(queries, key=lambda w: word.similarity(w), reverse=True)
word_similarities = [(w.text.lower(),float(w.similarity(word))) for w in by_similarity[:10] if w.lower_ != word.lower_]
word_similarities_dict[word_text] = word_similarities
save_cache_data(save_cache=save_cache)
return word_similarities[:top_k]
#print(get_most_similar("dog", top_k=3))
#save_cache_data(save_cache=save_cache)
# In[16]:
def get_wd_ids(word, is_predicate=False, top_k=3, limit=6, online=False, sim_threshold=0.5):
#if is_predicate and wd_local_predicate_ids_dict.get(word) != None and use_cache and len(wd_local_predicate_ids_dict)>0:
# #print("saved predicate local")
# res_ids = wd_local_predicate_ids_dict[word][:top_k]
# to_return = []
# for res_id in res_ids:
# if get_nlp(get_wd_label(res_id)).similarity(get_nlp(word)) >= sim_threshold:
# to_return.append(res_id)
# return to_return #wd_local_predicate_ids_dict[word][:top_k]
#
#elif not is_predicate and wd_local_word_ids_dict.get(word) != None and use_cache and len(wd_local_word_ids_dict)>0:
# #print("saved word local")
# res_ids = wd_local_word_ids_dict[word][:top_k]
# to_return = []
# for res_id in res_ids:
# if get_nlp(get_wd_label(res_id)).similarity(get_nlp(word)) >= sim_threshold:
# to_return.append(res_id)
# return to_return #wd_local_word_ids_dict[word][:top_k]
language = "en"
word_formated = str("\""+word+"\""+"@"+language)
to_remove = len("http://www.wikidata.org/entity/")
t_name, card_name = hdt_wd.search_triples("", "http://schema.org/name", word_formated, limit=top_k)
#print("names cardinality of \"" + word+"\": %i" % card_name)
t_alt, card_alt = hdt_wd.search_triples("", 'http://www.w3.org/2004/02/skos/core#altLabel', word_formated, limit=top_k)
#print("alternative names cardinality of \"" + word+"\": %i" % card_alt)
results = list(set(
[t[0][to_remove:] for t in t_name if is_valide_wd_id(t[0][to_remove:])] +
[t[0][to_remove:] for t in t_alt if is_valide_wd_id(t[0][to_remove:])]
))
res = []
for result in results:
#print(result,get_nlp(get_wd_label(result)).similarity(get_nlp(word)))
if get_nlp(get_wd_label(result)).similarity(get_nlp(word)) >= sim_threshold:
res.append(result)
if is_predicate: res = [r for r in res if is_wd_predicate(r)]
# cache the data
if is_predicate: wd_local_predicate_ids_dict[word] = res
else: wd_local_word_ids_dict[word] = res
#print("res",res)
#print("limit",limit)
if limit<=0:
#print("if limit<=0",top_k)
return res[:top_k]
else:
#print("else limit<=0",limit)
if limit-1>=0: return res[:limit-1]
else: return res[:limit]
#print(get_wd_ids("did", is_predicate=False, top_k=1))
#get_wd_ids("The Last Unicorn", is_predicate=False,top_k=0, limit=10)
#print(get_wd_ids("wife", is_predicate=False , top_k=0, limit=0))
#print(get_wd_ids("voiced", is_predicate=True , top_k=0, limit=0))
# In[17]:
def get_wd_label(from_id, language="en"):
#print("from_id",from_id)
if is_valide_wd_id(from_id):
if wd_labels_dict.get(from_id) != None and use_cache and len(wd_labels_dict)>0:
#print("saved label local")
return wd_labels_dict[from_id]
id_url = "http://www.wikidata.org/entity/"+from_id
t_name, card_name = hdt_wd.search_triples(id_url, "http://schema.org/name", "")
name = [t[2].split('\"@'+language)[0].replace("\"", "") for t in t_name if "@"+language in t[2]]
#name = [t[2].split('@en')[0] for t in t_name if "@"+language in t[2]]
result = name[0] if name else ''
wd_labels_dict[from_id] = result #caching
return result
else:
return from_id
#print(get_wd_label("P725"))
#get_wd_label("Q20789322")
#get_wd_label("Q267721")
# In[18]:
# Building colors from graph
def get_color(node_type):
if node_type == "entity": return "violet"#"cornflowerblue"
elif node_type == "predicate": return "yellow"
else: return "red"
# Building labels for graph
def get_elements_from_graph(graph):
node_names = nx.get_node_attributes(graph,"name")
node_types = nx.get_node_attributes(graph,"type")
colors = [get_color(node_types[n]) for n in node_names]
return node_names, colors
# Plotting the graph
def plot_graph(graph, name, title="Graph"):
fig = plt.figure(figsize=(14,14))
ax = plt.subplot(111)
ax.set_title(str("answer: "+title), fontsize=10)
#pos = nx.spring_layout(graph)
labels, colors = get_elements_from_graph(graph)
nx.draw(graph, node_size=30, node_color=colors, font_size=10, font_weight='bold', with_labels=True, labels=labels)
plt.tight_layout()
plt.savefig("tmqa1_graphs_imgs/"+str(name)+".png", format="PNG", dpi = 300)
plt.show()
#plot_graph(graph, "file_name_graph", "Graph_title")
# In[19]:
def make_statements_graph_worker(graph, predicate_nodes, turn, indexing_predicates, BANNED_WD_IDS, BANNED_WD_PRED_IDS, BANNED_WD_KEYWORDS, BANNED_WD_PRED_KEYWORDS, in_mp_queue, out_mp_queue, predicate_nodes_lock, node_weight, qa):
#for statement in statements:
sentinel = None
for statement in iter(in_mp_queue.get, sentinel):
#print("statement",statement)
#if (statement['entity']['id'][0] != "Q"
# or statement['entity']['id'] in BANNED_WD_IDS
# or statement['predicate']['id'][0] != "P"
# or statement['predicate']['id'] in BANNED_WD_PRED_IDS
# or statement['object']['id'][0] != "Q"
# or statement['object']['id'] in BANNED_WD_IDS):
# continue
if (
statement['entity']['id'] in BANNED_WD_IDS
or statement['predicate']['id'][0] != "P"
or statement['predicate']['id'] in BANNED_WD_PRED_IDS
or statement['object']['id'] in BANNED_WD_IDS
):
continue
continue_flag = False
for key in BANNED_WD_PRED_KEYWORDS:
if (get_wd_label(statement['predicate']['id']).find(key) != -1): continue_flag = True
for key in BANNED_WD_KEYWORDS:
if (get_wd_label(statement['entity']['id']).find(key) != -1): continue_flag = True
if (get_wd_label(statement['object']['id']).find(key) != -1): continue_flag = True
if continue_flag: continue
#print(statement)
if not statement['entity']['id'] in graph:
graph.add_node(statement['entity']['id'], name=get_wd_label(statement['entity']['id']), type='entity', turn=turn, weight=node_weight, qa=qa)
if not statement['object']['id'] in graph:
graph.add_node(statement['object']['id'], name=get_wd_label(statement['object']['id']), type='entity', turn=turn, weight=node_weight, qa=qa)
with predicate_nodes_lock:
# increment index of predicate or set it at 0
if not statement['predicate']['id'] in predicate_nodes or not indexing_predicates:
predicate_nodes_index = 1
predicate_nodes[statement['predicate']['id']] = 1
else:
predicate_nodes[statement['predicate']['id']] += 1
predicate_nodes_index = predicate_nodes[statement['predicate']['id']]
# add the predicate node
predicate_node_id = (statement['predicate']['id'])
if indexing_predicates: predicate_node_id += "-" + str(predicate_nodes_index)
graph.add_node(predicate_node_id, name=get_wd_label(statement['predicate']['id']), type='predicate', turn=turn, weight=node_weight)
# add the two edges (entity->predicate->object)
#statement['entity']['id'] in BANNED_WD_IDS
#statement['object']['id'] in BANNED_WD_IDS
#statement['predicate']['id'] in BANNED_WD_PRED_IDS
#if (statement['predicate']['id'] in BANNED_WD_PRED_IDS): break
graph.add_edge(statement['entity']['id'], predicate_node_id)
graph.add_edge(predicate_node_id, statement['object']['id'])
out_mp_queue.put(graph)
# In[20]:
# TODO: handle special literals? which one
def make_statements_graph(statements, indexing_predicates=True, potential_predicates=False, cores=mp.cpu_count(), context_graph=False, node_weight=1, qa=False, max_deepness=3):
BANNED_WD_IDS = [
"Q4167410","Q66087861","Q65932995","Q21281405","Q17442446","Q41770487","Q29548341",
"Q29547399","Q25670","Q21286738"
]
BANNED_WD_PRED_IDS = [
"P1687","P7087","P1889","P646", "P227", "P1256", "P1257", "P1258", "P1260", "P301",
"P18","P1266","P487","P1970","P2529", "P4390", "P4342", "P4213", "P487", "P2624",
"P4953", "P2241", "P345","P703", "P2163", "P18", "P436", "P227", "P646", "P2581",
"P1006", "P244", "P214", "P1051", "P1296","P461", "P2959", "P1657", "P3834","P243",
"P3306","P6932","P356","P1630","P3303","P1921","P1793","P1628","P1184","P1662","P2704",
"P4793","P1921","P2302","P6562","P6127","P4342","P6145","P5786","P5099","P4947","P5032",
"P4933","P4632","P4529","P4277","P4282","P3135","P4276","P3593","P2638","P3804","P3145",
"P2509","P3212","P2704","P480","P3844","P3141","P3808","P3933","P2346","P3077","P3417",
"P2529","P3302","P3143","P2334","P3129","P3138","P3107","P2603","P2631","P2508","P2465",
"P2014", "P1874", "P2518", "P1265", "P1237","P1712", "P1970","P1804","P905","P1562",
"P1258","P646","P345",'http://www.w3.org/2002/07/owl#sameAs'
]
BANNED_WD_KEYWORDS = ["_:"]
BANNED_WD_PRED_KEYWORDS = [
"ID", "ISBN","Identifier","identifier", "IDENTIFIER", "isbn", "ISSN", "issn","id","Id","iD","ISNI"
]
predicate_nodes = mp.Manager().dict()
predicate_nodes_lock = mp.Manager().Lock()
if context_graph:
latest_turn = sorted([y["turn"] for x,y in context_graph.nodes(data=True)])[-1]
turn = latest_turn+1
graph = context_graph.copy()
previous_predicates_ids = [x for x,y in context_graph.nodes(data=True) if y["type"]=="predicate"]
if previous_predicates_ids:
if previous_predicates_ids[0].find("-") != -1:
for ppi in previous_predicates_ids:
ppi_id = ppi[:ppi.find("-")]
ppi_value = ppi[ppi.find("-")+1:]
if ppi_id in predicate_nodes:
if int(ppi_value) > predicate_nodes[ppi_id]:
predicate_nodes[ppi_id] = int(ppi_value)
else:
predicate_nodes[ppi_id] = int(ppi_value)
#print("predicate_nodes from context",predicate_nodes.keys())
else:
turn=1
graph = nx.Graph()
if cores <= 0: cores = 1
out_mp_queue = mp.Queue()
in_mp_queue = mp.Queue()
sentinel = None
for statement in statements:
in_mp_queue.put(statement)
procs = [mp.Process(target = make_statements_graph_worker, args = (graph, predicate_nodes, turn, indexing_predicates, BANNED_WD_IDS, BANNED_WD_PRED_IDS, BANNED_WD_KEYWORDS, BANNED_WD_PRED_KEYWORDS, in_mp_queue, out_mp_queue, predicate_nodes_lock, node_weight, qa)) for i in range(cores)]
for proc in procs:
proc.daemon = True
proc.start()
for proc in procs:
in_mp_queue.put(sentinel)
for proc in procs:
local_g = out_mp_queue.get()
graph = nx.compose(graph,local_g)
for proc in procs:
proc.join()
if context_graph:
previous_entities_ids = [x for x,y in context_graph.nodes(data=True) if y["type"]=="entity"]
#print("previous_entities_ids",previous_entities_ids)
for n in graph.copy().nodes():
is_entity_present = [nx.has_path(graph, n, pei) for pei in previous_entities_ids if graph.has_node(pei) and graph.has_node(n)]
#print("is_entity_present for n",n,is_entity_present)
if not any(iep for iep in is_entity_present):
graph.remove_node(n)
else:
shortest_paths = [nx.shortest_path(graph, n, pei) for pei in previous_entities_ids if graph.has_node(pei) and graph.has_node(n)]
#print("shortest_paths",shortest_paths)
shortest_paths_len = [len(sp) for sp in shortest_paths]
#print("shortest_paths_len",shortest_paths_len)
if not any((spl <= max_deepness and spl>1) for spl in shortest_paths_len):
graph.remove_node(n)
#print("Any is smaller than max_deepness")
#else:
#print("None is smaller than max_deepness")
#if previous_predicates_ids
#print("1 len(graph)",len(graph))
if previous_predicates_ids:
if previous_predicates_ids[0].find("-") != -1:
previous_predicates_ids_only = [p[:p.find("-")] for p in previous_predicates_ids]
else:
previous_predicates_ids_only = previous_predicates_ids
else: previous_predicates_ids_only=[]
#print("previous_predicates_ids",previous_predicates_ids)
#print("previous_predicates_ids_only",previous_predicates_ids_only)
spo_list = [[list(graph.neighbors(p))[0],p[:p.find("-")],list(graph.neighbors(p))[1]] for p in previous_predicates_ids]
spo_list_tagged = [[list(graph.neighbors(p))[0],p,list(graph.neighbors(p))[1]] for p in previous_predicates_ids]
for spo in spo_list_tagged:
#print("graph.nodes(data=True)",graph.nodes(data=True))
#print("before spo weights",spo,graph.nodes[spo[0]]['weight'],graph.nodes[spo[1]]['weight'],graph.nodes[spo[2]]['weight'])
graph.nodes[spo[0]]['weight'] += 1
graph.nodes[spo[1]]['weight'] += 1
graph.nodes[spo[2]]['weight'] += 1
#print("after spo weights",spo,graph.nodes[spo[0]]['weight'],graph.nodes[spo[1]]['weight'],graph.nodes[spo[2]]['weight'])
for p in [x for x,y in graph.nodes(data=True) if y["type"]=="predicate"]:
p_n = list(graph.neighbors(p))
if p.find("-") != -1:
p_id = p[:p.find("-")]
p_value = p[p.find("-")+1:]
else:
p_id = p
p_value = 0
if len(p_n) > 1: spo_tuple = [p_n[0],p_id,p_n[1]]
else: spo_tuple = []
if spo_tuple not in spo_list and spo_tuple:
spo_list.append(spo_tuple)
else:
if p not in previous_predicates_ids:
graph.remove_node(p)
#print("2 len(graph)",len(graph))
for spo in spo_list:
if spo[1] in previous_predicates_ids_only:
if spo[0] not in previous_entities_ids and spo[2] not in previous_entities_ids:
bad_paths = [p for p in nx.all_shortest_paths(graph, source=spo[0], target=spo[2]) if p[1][:p[1].find("-")] == spo[1]]
for bp in bad_paths:
graph.remove_node(bp[1])
#print("3 len(graph)",len(graph))
local_main_themes=[]
for p in [x for x,y in graph.nodes(data=True) if y["type"]=="entity"]:
if len(list(graph.neighbors(p)))>2: local_main_themes.append(p)
meaningful_paths = []
#for t in [x for x,y in graph.nodes(data=True) if y["type"]=="entity"]:
for t in local_main_themes:
statements = get_all_statements_of_entity(t)
if not statements:
continue
for statement in statements:
tmp_statement_basic = []
s_entity = statement["entity"]['id']
if t!=s_entity:
continue
s_predicate = statement["predicate"]['id']