forked from bohuizhang/LLMKE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparql_query.py
304 lines (280 loc) · 10.4 KB
/
sparql_query.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
import sys
from collections import Counter, defaultdict
from SPARQLWrapper import SPARQLWrapper, JSON
from pipeline.file_io import read_lm_kbc_jsonl_to_df, save_df_to_jsonl
def sparql_query(query):
""" regular sparql query with formatting functions
:param query:
:return:
"""
endpoint_url = "https://query.wikidata.org/sparql"
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
# TODO adjust user agent; see https://w.wiki/CX6
sparql = SPARQLWrapper(endpoint_url, agent=user_agent)
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
sparql_results = sparql.query().convert()
object_entities, object_entities_id = list(), list()
for result in sparql_results["results"]["bindings"]:
object_entities_id.append(result['object']['value'].strip('http://www.wikidata.org/entity/'))
object_entities.append(result['objectLabel']['value'])
if not object_entities:
return [""], [""]
return object_entities_id, object_entities
def query_answers(subject_entity_id, relation):
"""
:param subject_entity_id:
:param relation:
:return:
"""
if relation == 'BandHasMember': # train: 5, val: 5
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
?object wdt:P463 wd:%s .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CityLocatedAtRiver': # (check) train: 37
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P206 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CompanyHasParentOrganisation': # train: 2
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P749 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CompoundHasParts': # (check) train: 33
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P527 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CountryBordersCountry': # train: 9, val: 12
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P47 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CountryHasOfficialLanguage': # train: 1, val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P37 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'CountryHasStates':
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P150 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'FootballerPlaysPosition': # val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P413 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonCauseOfDeath': # val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P509 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasAutobiography': # train: 5, val: 5
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
{
?object wdt:P50 wd:%s ;
wdt:P136 wd:Q4184 .
}
UNION
{
?object wdt:P50 wd:%s ;
wdt:P136 wd:Q112983 .
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % (subject_entity_id, subject_entity_id)
elif relation == 'PersonHasEmployer': # train: 1, val: 4
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P108 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasNoblePrize':
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P166 ?object .
wd:Q7191 wdt:P527 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasNumberOfChildren': # train: 2, val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P1971 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasPlaceOfDeath': # val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P20 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasProfession': # train: 4, val: 2
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P106 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonHasSpouse': # val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P26 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonPlaysInstrument': # train: 1, val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P1303 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'PersonSpeaksLanguage': # val: 2
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P1412 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'RiverBasinsCountry':
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P205 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'SeriesHasNumberOfEpisodes': # val: 1
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P1113 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
elif relation == 'StateBordersState': # train: 6, val: 4
q = """
SELECT DISTINCT ?object ?objectLabel
WHERE
{
wd:%s wdt:P47 ?object .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
""" % subject_entity_id
else:
print("Not supported!")
return None
return sparql_query(q)
def check_completeness(data_df):
"""
:param data_df:
:return:
"""
relations = data_df['Relation'].unique()
unmatched_cases_count = defaultdict(int)
for relation in relations:
relation_df = data_df[data_df['Relation'] == relation]
relation_gt = dict(zip(relation_df['SubjectEntityID'], relation_df['ObjectEntitiesID']))
number_of_unmatched_cases = 0
for key, value in relation_gt.items():
queried_qids, _ = query_answers(key, relation)
if Counter(queried_qids) == Counter(value):
pass
else:
# print("Subject:", key)
# print("ObjectEntitiesID:", value)
# print("Query:", queried_qids)
# print("Differences:", set(queried_qids) - set(value))
number_of_unmatched_cases += 1
unmatched_cases_count[relation] = number_of_unmatched_cases
return unmatched_cases_count
def query_test_objects(test_data, output_path):
"""
:param test_data:
:param output_path:
:return:
"""
results = []
for idx, row in test_data.iterrows():
object_entities_id, object_entities = query_answers(row['SubjectEntityID'], row['Relation'])
result = {
"SubjectEntityID": row["SubjectEntityID"],
"SubjectEntity": row["SubjectEntity"],
"Relation": row["Relation"],
"ObjectEntities": object_entities,
"ObjectEntitiesID": object_entities_id
}
results.append(result)
save_df_to_jsonl(output_path, results)
# return results
if __name__ == "__main__":
# train_df = read_lm_kbc_jsonl_to_df("../data/train.jsonl")
# print(check_completeness(train_df))
# val_df = read_lm_kbc_jsonl_to_df("../data/val.jsonl")
# print(check_completeness(val_df))
test_df = read_lm_kbc_jsonl_to_df("../data/test.jsonl")
query_test_objects(test_df, "../data/test.query.jsonl")