-
Notifications
You must be signed in to change notification settings - Fork 1
/
KnowledgeGraphPopulate.py
173 lines (164 loc) · 5.87 KB
/
KnowledgeGraphPopulate.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
import rdflib
#import random
import csv
import pickle
KnowledgeGraph={}
#Dictionary of {"s":["LABEL","TYPE",list[(("o",type_of_o),list["p"])]]} object and list of predicates hashed with respect to
# #hop distance
PREFIX="http://data.linkedmdb.org/"
LABEL,TYPE,GRAPH=0,1,2
def save_obj(obj, name ):
with open('./'+ name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open('./' + name + '.pkl', 'rb') as f:
return pickle.load(f)
def write_to_csv(uri_actor_id,class_name):
uri_actor_id_dict={}
row = 1
temp_file=open("temp_csv.csv","a")
temp_csv = csv.writer(temp_file)
for i in uri_actor_id:
try:
uri_actor_id_dict[i]=out_degree(i)
temp_csv.writerow([row,i,uri_actor_id_dict[i]])
temp_file.flush()
print(row,i,uri_actor_id_dict[i])
row = row+1
except:
pass
#writing the dictionary as csv
w = csv.writer(open(class_name+"_weight.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])
def out_degree(url):
deg=0
if PREFIX in url:
g1=rdflib.Graph()
g1.parse(url)
# print(g1.)
actor_id=url.split("/")[-1]
for s,p,o in g1:
if PREFIX in p:
#print(s,p,o)
deg+=1
return deg
"""For computing the weight based weight[u]=sum([outdegree[v] for v in OUT(u)])
"""
def weight(url):
g1=rdflib.Graph()
g1.parse(url)
# print(g1.)
weight_edge=0
if PREFIX in url:
g1=rdflib.Graph()
g1.parse(url)
# print(g1.)
actor_id=url.split("/")[-1]
for s,p,o in g1:
if PREFIX in o:
#print("Object:",o)
try:
weight_edge+=out_degree(o)
except:
pass
return weight_edge
def comp(s1):
return weight(s1)
def FindLabel(url):
g=rdflib.Graph()
g.parse(url)
O,S=None,None
for s,p,o in g:
if('dc' in p) and ('title' in p):
try:
return str(o),s.split("/")[-2]
except:
pass
return O,S
def fn(URI):
return out_degree(URI[0])
def URLQuestionsCompute(url,URLname,URLid):
g1=rdflib.Graph()
g1.parse(url)
print("Start")
if PREFIX not in url:
return
#Helper function
def isdigit(string):
try:
string=int(string)
return True
except:
return False
#For a given url entity two types of questions can be generated
# s,p,o where s is url or o is url,p is the connective between them
for s,p,o in g1:
if (str(URLid) in o) and (PREFIX in s) and isdigit(s.split("/")[-1]):
try:
#print("This is p : ",p)
label_S,type_P=FindLabel(s)
if label_S:
KnowledgeGraph[URLname][GRAPH].append(((label_S,type_P),p.split("/")[-1]))
except Exception as e:
print("Error: ",e)
if (str(URLid) in s) and (PREFIX in o) and isdigit(o.split("/")[-1]):
try:
label_O,type_P=FindLabel(o)
if label_O:
KnowledgeGraph[URLname][GRAPH].append(((label_O,type_P),p.split("/")[-1]))
except Exception as e:
print("Error: ",e)
def RankEntitiesBasedOnClass(base_url,class_name):
class_name.lower().strip()
url = base_url+class_name
print("\n")
print("Extracting Data From "+str(url))
g=rdflib.Graph()
g.parse(url)
entities,entity_id,type_of_entity = [],[],None
for s,p,o in g:
if('label' in p):
try:
entity = str(o.split('(')[-2].strip(' '))
entities.append(entity)
entity_id.append(s.split("/")[-1])
except Exception as e:
print("Error:", e)
#print(s,"|||",p,"|||",o)
if (not type_of_entity) and ('foaf' in o):
type_of_entity=o.split("/")[-1]
print(" ")
print("Total "+str(len(entities))+" entities found! Showing first "+str(min(10, len(entities)))+" entities")
print(" ")
Entities=list(zip(entity_id,entities))
Entities.sort(key=fn,reverse=True)
for i in range(len(Entities)):
print(str(i+1)+": ", Entities[i][1])
if Entities[i][1] not in list(KnowledgeGraph.keys()):
KnowledgeGraph[Entities[i][1]]=[class_name,type_of_entity,[]]
print("\n")
print(base_url[:-4]+"data/"+class_name+"/"+entity_id[0])
uri_actor_id=[ base_url[:-4]+"data/"+class_name+"/"+entity_id[i] for i in range(len(entity_id))]
print("Out degree of the first one:",out_degree(base_url[:-4]+"data/"+class_name+"/"+entity_id[0]))
#write_to_csv(uri_actor_id,class_name)
#print("Weight of first one :",uri_actor_id[0],weight(uri_actor_id[0]))
return base_url,class_name,[Entities[i][0] for i in range(len(Entities))],[Entities[i][1] for i in range(len(Entities))]
def KnowledgeGraphCompute(base_url,class_name):
base_url,class_name,actor_id,entities=RankEntitiesBasedOnClass(base_url,class_name)
for i in range(1):
URLQuestionsCompute(base_url[:-4]+"data/"+class_name+"/"+actor_id[i],entities[i],actor_id[i])
save_obj(KnowledgeGraph,"KnowledgeGraph_"+class_name)
KG=load_obj("KnowledgeGraph_"+class_name)
# print(type(KG))
def main():
ListOfClasses=["actor","cinematographer","director","editor","film_art_director","film_casting_director"
,"film_character","film_costume_designer","film_crewmember","film_critic","film_distributor",
"film_festival_sponsor","film_production_designer","film_story_contributor","film_theorist"
,"music_contributor","producer","writer"]
base_url = 'http://data.linkedmdb.org/all/'
class_name="actor"
KnowledgeGraphCompute(base_url,class_name)
print(len(list(KnowledgeGraph.keys())))
if __name__ == '__main__':
main()