forked from bennokr/wdps
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEntityLinking.py
204 lines (160 loc) · 5.64 KB
/
EntityLinking.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
import sys
_, DOMAIN_TRIDENT, DOMAIN_ELASTIC = sys.argv
ELASTICSEARCH_URL = 'http://%s/freebase/label/_search' % DOMAIN_ELASTIC
TRIDENT_URL = 'http://%s/sparql' % DOMAIN_TRIDENT
with open('Entities.csv', 'r') as csvfile:
queries = csv.reader(csvfile)
queries = list(queries)
for index in range(len(queries)):
query = queries[index][0] # token obtained
print('Searching for "%s"...' % query)
#looking for queries that we get from the token with elasticsearch
response = requests.get(ELASTICSEARCH_URL, params={'q': query, 'size':1000})
#select unique query results
ids = set()
labels = {}
scores = {}
#obtain freebase id's from elasticsearch responses
if response:
response = response.json()
for hit in response.get('hits', {}).get('hits', []):
freebase_id = hit.get('_source', {}).get('resource')
label = hit.get('_source', {}).get('label')
score = hit.get('_score', 0)
ids.add( freebase_id )
scores[freebase_id] = max(scores.get(freebase_id, 0), score)
labels.setdefault(freebase_id, set()).add( label )
print('Found %s results.' % len(labels))
#predixes to use shortnames in SPARQL query
prefixes = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX fbase: <http://rdf.freebase.com/ns/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wds: <http://www.wikidata.org/entity/statement/>
PREFIX wdv: <http://www.wikidata.org/value/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
"""
### look at NER tag. if person filter with personEntity, if location filter with locationEntity if organisation
#filter with organisation entity
#select person entity
personEntity_same_as_template = prefixes + """
SELECT DISTINCT ?person
WHERE
{
?person wdt:P31 wd:Q5 . #where ?person isa(wdt:P31) human(wd:Q5)
?s owl:sameAs fbase:%s .
{ ?s owl:sameAs ?person .} UNION { ?person owl:sameAs ?s .}
}
"""
#select organisation enitity
organisationEntity_same_as_template = prefixes + """
SELECT DISTINCT ?organisation ?organisation2
WHERE
{
?organisation wdt:P31 wd:Q43229. #organisation(Q43229) (collective goal)
?organisation2 wdt:P31 wd:Q2029841. #organisation(Q2029841) (economical concept)
?s owl:sameAs fbase:%s .
{ ?s owl:sameAs ?organisation . OR ?s owl:sameAs ?organisation . } UNION { ?organisation owl:sameAs ?s . OR ?organisation2 owl:sameAs ?s .}
}
"""
#select location enitity
locationEntity_same_as_template = prefixes + """
SELECT DISTINCT ?location
WHERE
{
?location wdt:P31 wd:Q17334923. #where ?location isA location(Q17334923)
?s owl:sameAs fbase:%s .
{ ?s owl:sameAs ?location .} UNION { ?location owl:sameAs ?s .}
}
"""
#get the word similar to the freebase hit %s
same_as_template = prefixes + """
SELECT DISTINCT ?same
WHERE
{
?s owl:sameAs fbase:%s .
{ ?s owl:sameAs ?same .} UNION { ?same owl:sameAs ?s .}
}
"""
# get the complete template for the freebase hit %s
po_template = prefixes + "SELECT DISTINCT * WHERE {fbase: %s ?p ?o.}"
print('Counting KB facts...')
#Link all results from elasticsearch to trident database. %s in po_templare (are the unique freebase hits)
facts = {}
n_total = 0
### Parallel Utils ###
def process_id(id):
"""process a single ID"""
# and update some data with PUT
# requests.put(url_t % id, data=data)
id = id.replace('/', '.')
id = id[1:]
response = requests.post(TRIDENT_URL, data={'print': False, 'query': po_template % id})
return response.json()
def process_range(id, store=None):
"""process a number of ids, storing the results in a dict"""
if store is None:
store = {}
store[id] = process_id(id)
return store
from threading import Thread
def threaded_process_range(nthreads, ids):
"""process the id range in a specified number of threads"""
store = {}
threads = []
# create the threads
for i in range(nthreads):
id = ids[i]
t = Thread(target=process_range, args=(id, store))
threads.append(t)
# start the threads
[t.start() for t in threads]
# wait for the threads to finish
[t.join() for t in threads]
return store
##################################################
ids = list(ids)
dict = threaded_process_range(len(ids),ids)
for i in ids:
response = dict[i]
n = int(response.get('stats', {}).get('nresults', 0))
print(i, ':', n)
# sys.stdout.flush()
facts[i] = n
n_total = n_total + n
for i in ids:
i = i.replace('/','.')
i = i[1:]
response = requests.post(TRIDENT_URL, data={'print': False, 'query': po_template % i})
if response:
response = response.json()
n = int(response.get('stats',{}).get('nresults',0))
print(i, ':', n)
sys.stdout.flush()
facts[i] = n
n_total = n_total+n
translate = {}
# Replacing / in freebase ID's in scores dict
for k, v in facts.items():
new_key = k.replace('.','/')
new_key = '/' + new_key
translate[k] = new_key
for old, new in translate.items():
facts[new] = facts.pop(old)
# the normalized score, which we will use when ranking the obtained entities
def get_best(i):
norm_score = facts[i] / n_total
return math.log(norm_score+0.0000001) * scores[i] # Avoid math errors
#best matches are filtered based on the entity type
print('Best matches:')
pred = {}
for i in sorted(ids, key=get_best, reverse=True)[:1]:
print(i, ':', labels[i], '(facts: %s, score: %.2f)' % (facts[i], scores[i]) )
labels = list[labels[i]]
pred[labels] = i
sys.stdout.flush()
with open("sample_predictions.tsv", 'wb') as f:
writer = csv.DictWriter(f, delimiter='\t')
writer.writerows(pred)