-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
244 lines (205 loc) · 8.92 KB
/
main.py
File metadata and controls
244 lines (205 loc) · 8.92 KB
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
import requests
from requests_futures.sessions import FuturesSession
import concurrent
from concurrent.futures import ALL_COMPLETED
import cherrypy
import json
import glob
from itertools import groupby
from bs4 import BeautifulSoup
import copy
from functools import partial
CHUNK_SIZE = 10 # Number of paragraphs in a chunk
PARALLEL_REQUESTS = 10
PROMETHEUS_URL = 'http://localhost:8080/api/en/extract'
PROMETHEUS_TIMEOUT = 120 # Maximum number of seconds to wait for Prometheus for one page extraction
class FactChecker(object):
def __init__(self):
self.data_cache = []
self.label_cache = {}
def label_for(self, q):
q = q.upper()
if q in self.label_cache:
return self.label_cache[q]
cherrypy.log(f"Resolving name for {q}")
url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&props=labels&ids=%s&languages=en&format=json' % q
resp = requests.get(url)
try:
v = resp.json()['entities'][q]['labels']['en']['value']
self.label_cache[q] = v
except Exception as e:
cherrypy.log(f"Could not resolve name for {q}")
v = "unknown"
return v
def link_for(self, q):
return f"https://www.wikidata.org/wiki/{q}"
def wiki_link_for(self, name):
name_quoted = name.replace(" ", "_")
return f"https://en.wikipedia.org/wiki/{name_quoted}"
def chunk_text(self, text, chunks = []):
if not text:
return chunks
else:
chunk = ".".join(text.split(".")[:5]) + "."
rest = ".".join(text.split(".")[5:])
return self.chunk_text(rest, chunks + [chunk])
# Get a list of extracted relations from Prometheus for "page"
# The page is chunked by CHUNK_SIZE number of paragraphs and sent up to PARALLEL_REQUESTS in parallel
# If any of those requests fails, it will be logged but no further action will be taken
# The return value is a list of relations
def get_relations(self, page):
soup = BeautifulSoup(page, 'html.parser')
# Chunking
paragraphs = [p.getText().strip() for p in soup.find_all('p')]
paragraphs = [c for c in paragraphs if c != '']
chunks = []
for i in range(0, len(paragraphs), CHUNK_SIZE):
chunks.append('. '.join(paragraphs[i:i+CHUNK_SIZE]))
session = FuturesSession(max_workers=PARALLEL_REQUESTS)
fs = []
# Send concurrent requests to extract chunks
if not chunks:
cherrypy.log("No text in page")
for chunk in chunks:
resp = session.post(
PROMETHEUS_URL,
data=chunk.encode('UTF-8'),
headers={
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
timeout=60)
fs.append(resp)
cherrypy.log("Sent chunk for extraction")
# Print some info when responses complete
def response_completed_callback(data, f):
cherrypy.log("An extraction request completed")
try:
res = f.result()
if res.status_code != 200:
cherrypy.log("HTTP Status Code NOK!")
cherrypy.log("Original data was")
cherrypy.log(data)
except Exception as e:
cherrypy.log(f"Raised exception")
cherrypy.log("Original data was:")
cherrypy.log(data)
resp.add_done_callback(partial(response_completed_callback, chunk))
# Await completion of all reponses
try:
cherrypy.log(f"Waiting up to {PROMETHEUS_TIMEOUT} s for all extraction requests to complete...")
(done, not_done) = concurrent.futures.wait(fs, timeout=PROMETHEUS_TIMEOUT, return_when=ALL_COMPLETED)
fs = done
cherrypy.log("Done")
except Exception as e:
cherrypy.log("Some requests did not finish within {PROMETHEUS_TIMEOUT} s.")
for f in not_done:
f.cancel()
relations = []
for f in fs:
try:
# Low timeout because above wait should have ensured all were completed
resp = f.result(timeout=0.001)
if resp.status_code == 200:
relations.append(resp.json())
else:
cherrypy.log(f"Response: {resp.status_code} {resp.text}")
except Exception as e:
cherrypy.log(f"Request failed: {e}")
return self.flatten(relations)
def flatten(self, the_list):
return [val for sublist in the_list for val in sublist]
@cherrypy.expose
def index(self):
return "POST with URL to /check to do fact checking"
@cherrypy.expose
@cherrypy.tools.json_out()
def check(self, url=None):
if url is not None:
# GET the page
cherrypy.log(f"GET {url}")
try:
page = requests.get(url, timeout=10).text
except Exception as e:
cherrypy.log(f"Could not get url: {url}: {e}")
cherrypy.response.status = '503'
return f"Could not get the requested url: {url}"
# Connect to Prometheus
cherrypy.log("Extracting relations from Prometheus...")
relations = self.get_relations(page)
# Group extracted relations by relation triple
def keyfunc(relation):
return (relation['subject'], relation['predictedPredicate'], relation['obj'])
extractions = []
data = sorted(relations, key=keyfunc)
for k, g in groupby(data, keyfunc):
extractions.append(list(g)) # Store group iterator as a list
results = []
for extraction in extractions:
# only check once per actual relation
evidence = self.check_relation(extraction[0])
result = {}
result['subject'] = {
'name': self.label_for(extraction[0]['subject']),
'link': self.link_for(extraction[0]['subject'])
}
result['object'] = {
'name': self.label_for(extraction[0]['obj']),
'link': self.link_for(extraction[0]['obj'])
}
result['predicate'] = {
'name': self.label_for(extraction[0]['predictedPredicate']),
'link': self.link_for(extraction[0]['predictedPredicate'])
}
result['sentences'] = list(map(lambda r: r['sentence'], extraction))
result['type'] = evidence[0]
for match in evidence[1]:
match['subject'] = self.label_for(match['subject'])
match['predictedPredicate'] = self.label_for(match['predictedPredicate'])
match['obj'] = self.label_for(match['obj'])
result['evidence'] = list(map(lambda e: self.trim_evidence(e), evidence[1]))
result['probablity'] = extraction[0]['probability']
results.append(result)
return results
else:
cherrypy.response.status = '400'
return "No URL to check supplied"
def trim_evidence(self, evidence):
name = evidence['source'].split(":")
if len(name) == 3:
name = name[2]
else:
name = ""
return {
'subject': evidence['subject'],
'object': evidence['obj'],
'predicate': evidence['predictedPredicate'],
'snippet': evidence['sentence'],
'link': self.wiki_link_for(self.label_for(name)),
'source': 'Wikipedia',
'probability': evidence['probability']
}
def check_relation(self, relation):
sub = relation['subject']
obj = relation['obj']
pred = relation['predictedPredicate']
if len(self.data_cache) == 0:
# read data
files = glob.glob("extractions/part-*")
for path in files:
with open(path) as file:
lines = file.readlines()
self.data_cache.extend([json.loads(l) for l in lines])
matches = [match for match in self.data_cache if (match['subject'] == sub
and match['predictedPredicate'] == pred)]
if len(matches) == 0:
return ("unknown", [])
for match in matches:
if match['obj'] == obj:
# found one match, the relation is considered True
return ("verified", [copy.deepcopy(match)])
return ("conflicting", copy.deepcopy(matches))
if __name__ == "__main__":
cherrypy.config.update(
{'server.socket_port': 8081,
'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(FactChecker())