-
Notifications
You must be signed in to change notification settings - Fork 3
/
web.py
303 lines (270 loc) · 8.98 KB
/
web.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
"""Web interface for coreference system."""
import io
import os
import re
import sys
import json
import time
import logging
import requests
import subprocess
from lxml import etree
from flask import Flask, Markup
from flask import request, render_template, redirect, url_for
from flask_caching import Cache
import coref
DEBUG = False
APP = Flask(__name__)
CACHE = Cache(config={
'CACHE_TYPE': 'SimpleCache',
'CACHE_DEFAULT_TIMEOUT': 86400, # cache responses server side for 24hr
'CACHE_THRESHOLD': 256, # max no of items to cache
})
CACHE.init_app(APP)
LIMIT = 5000 # maximum number of bytes of input to accept
ALPINOAPI = os.getenv('ALPINOAPI', 'http://127.0.0.1:11200/json')
BERTMODEL = TOKENIZER = None
@APP.route('/')
def main():
"""Redirect to main page."""
return redirect('/andreas/coref/index')
# return redirect(url_for('index'))
@APP.route('/index')
@CACHE.cached()
def index():
"""Start page where a text can be entered."""
return render_template('index.html', limit=LIMIT)
@APP.route('/results', methods=('POST', 'GET'))
def results():
"""Get coreference and show results."""
global BERTMODEL, TOKENIZER
if request.method == 'GET':
return redirect(url_for('main'))
if 'text' not in request.form:
return 'No text supplied'
text = request.form['text']
neural = [a for a in ('span', 'feat', 'pron', 'quote')
if request.form.get(a)]
normalizespelling = bool(request.form.get('spell'))
if len(text) > LIMIT:
return 'Too much text; limit: %d bytes' % LIMIT
text = simplifyunicodespacepunct(text)
tokenized = alpinotokenize(text, normalizespelling=normalizespelling)
parses = parse(tokenized)
if parses is None:
return 'Parsing failed!'
trees = [(a, etree.parse(io.BytesIO(b))) for a, b in parses]
coref.setverbose(True, io.StringIO())
embeddings = None
if neural:
if BERTMODEL is None:
try:
TOKENIZER, BERTMODEL = bert.loadmodel()
except Exception as err:
print(err)
return 'BERT model not available'
log.info('loaded BERT model')
sentences = tuple(tuple(coref.gettokens(tree, 0, 9999))
for _, tree in trees)
embeddings = getvectors(sentences)
mentions, clusters, quotations, _idx = coref.resolvecoreference(
trees, ngdata, gadata, neural=neural, embeddings=embeddings)
corefhtml, coreftabular, debugoutput = coref.htmlvis(
trees, mentions, clusters, quotations,
parses=True, coreffmt='booknlp')
log.info('resolved coreference; %d mentions; %d clusters; %d quotations'
% (len(mentions), sum(1 for a in clusters if a), len(quotations)))
return render_template('results.html', docname='',
corefhtml=Markup(corefhtml),
coreftabular=coreftabular,
debugoutput=Markup(debugoutput),
tokenized=tokenized if normalizespelling else None,
parses=True)
@CACHE.memoize()
def getvectors(sentences):
embeddings = bert.getvectors(
'', sentences, TOKENIZER, BERTMODEL, cache=False)
log.info('got BERT token vectors; shape: %r' % (embeddings.shape, ))
return embeddings
@CACHE.memoize()
def alpinotokenize(text, normalizespelling=False):
"""Apply Alpino's tokenizer to the string `text`; returns a string.
Requires a working installation of Alpino in $ALPINO_HOME
See http://www.let.rug.nl/vannoord/alp/Alpino/versions/binary/
:param text: a string
:param normalizespelling: enable optional 19c spelling normalization
:returns: a string of space-separated tokens, one sentence per line.
>>> alpinotokenize('Hallo,\\nwereld! Het werkt.'.replace('\\n', ' '))
'Hallo , wereld !\\nHet werkt .\\n'
"""
pipeline = ('./paragraph_per_line '
'| ./add_key '
'| ./tokenize.sh '
'| ./number_sents')
proc = subprocess.run(
pipeline,
cwd=os.path.join(os.getenv('ALPINO_HOME'), 'Tokenization/'),
input=text, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, encoding='utf8', text=True, check=True)
# FIXME: more error checking? io deadlock possible?
tokenized = proc.stdout
if normalizespelling:
pipeline = ('python3 triples.py '
'| python3 meta.py spelling '
'| sed -f map.sed '
'| python3 meta.py hand2')
proc = subprocess.run(
pipeline,
cwd='../oudeboeken', # FIXME: relative to current script
shell=True, input=tokenized, encoding='utf8',
capture_output=True, text=True, check=True)
tokenized = proc.stdout
log.info(tokenized)
return tokenized
@CACHE.memoize()
def parse(tokenized):
"""Parse tokenized text with Alpino API.
Cf. https://github.com/andreasvc/alpino-api
Expects alpino-api/demo/alpiner server to be running and accessible
at URL ALPINOAPI."""
def parselabel(label):
"""
>>> parselabel('1-2')
(1, 2)"""
a, b = label.rsplit('-', 1)
return int(a), int(b)
command = {'request': 'parse', 'data_type': 'lines tokens none',
'timeout': 60, 'max_tokens': 512, 'ud': False}
data = '%s\n%s' % (json.dumps(command), tokenized)
log.info('submitting parse')
resp = requests.post(ALPINOAPI, data=data.encode('utf8'))
result = resp.json()
if result['code'] != 202:
log.error(resp.content)
return None
# log.info(resp.content)
rid = result['id']
interval = 1
maxinterval = result['interval']
parses = []
while True:
time.sleep(interval)
log.info('waited %d seconds; checking results', interval)
resp = requests.post(ALPINOAPI, json={'request': 'output', 'id': rid})
result = resp.json()
if result['code'] != 200:
log.error(resp.content)
return None
log.info('got %d parses; code=%s status=%s finished=%s',
len(result['batch']), result['code'],
result['status'], result['finished'])
# log.info(resp.content.decode('utf8'))
parses.extend((
parselabel(line['label']), line['alpino_ds'].encode('utf8'))
for line in result['batch']
if line['line_status'] == 'ok')
if result['finished']:
break
if interval < maxinterval:
interval += 1
return sorted(parses)
def simplifyunicodespacepunct(text):
"""Turn various unicode whitespace and punctuation characters into simple
ASCII equivalents where appropriate, and discard control characters.
NB: this discards some information (e.g., left vs right quotes, dash vs
hyphens), but given that such information is not consistently encoded
across languages and texts, it is more reliable to normalize to a common
denominator.
>>> simplifyunicodespacepunct('‘De verraders’, riep de sjah.')
"'De verraders', riep de sjah."
"""
# Some exotic control codes not handled:
# U+0085 NEL: Next Line
# U+2028 LINE SEPARATOR
# U+2029 PARAGRAPH SEPARATOR
# Normalize spaces
# U+00A0 NO-BREAK SPACE
# U+2000 EN QUAD
# U+2001 EM QUAD
# U+2002 EN SPACE
# U+2003 EM SPACE
# U+2004 THREE-PER-EM SPACE
# U+2005 FOUR-PER-EM SPACE
# U+2006 SIX-PER-EM SPACE
# U+2007 FIGURE SPACE
# U+2008 PUNCTUATION SPACE
# U+2009 THIN SPACE
# U+200A HAIR SPACE
text = re.sub('[\u00a0\u2000-\u200a]', ' ', text)
# remove discretionary hyphen, soft space
# special case: treat soft hyphen at end of line as a regular hyphen,
# to ensure that it will be dehyphenated properly.
text = re.sub('\u00ad+\n', '-\n', text)
# 8 BACKSPACE
# U+00AD SOFT HYPHEN
# U+200B ZERO WIDTH SPACE
# U+2027 HYPHENATION POINT
text = re.sub('[\b\u00ad\u200b\u2027]', '', text)
# hyphens
# U+00B7 MIDDLE DOT
# U+2010 HYPHEN
# U+2011 NON-BREAKING HYPHEN
# U+2212 MINUS SIGN
text = re.sub('[\u00b7\u2010\u2011\u2212]', '-', text)
# dashes/bullet points
# U+2012 FIGURE DASH
# U+2013 EN DASH
# U+2014 EM DASH
# U+2015 HORIZONTAL BAR
# U+2022 BULLET
# U+2043 HYPHEN BULLET
text = re.sub('[\u2012-\u2015\u2022\u2043]', ' - ', text)
# U+2044 FRACTION SLASH
# U+2215 DIVISION SLASH
text = text.replace('[\u2044\u2215]', '/') # e.g., 'he/she'
# single quotes:
# U+2018 left single quotation mark
# U+2019 right single quotation mark
# U+201A single low-9 quotation mark
# U+201B single high-reversed-9 quotation mark
# U+2039 single left-pointing angle quotation mark
# U+203A single right-pointing angle quotation mark
# U+02BC modifier letter apostrophe
text = re.sub('[\u2018-\u201b\u2039\u203a\u02bc]', "'", text)
# double quotes:
# U+201C left double quotation mark
# U+201D right double quotation mark
# U+201E double low-9 quotation mark
# U+201F double high-reversed-9 quotation mark
# U+00AB left-pointing double angle quotation mark
# U+00BB right-pointing double angle quotation mark
text = re.sub("[\u201c-\u201f\u00ab\u00bb]|''", '"', text)
return text
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)
log.handlers[0].setFormatter(logging.Formatter(
fmt='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
log.info('loading.')
ngdata, gadata = coref.readngdata()
try:
import bert
except Exception as err:
print(err)
log.info('done.')
if __name__ == '__main__':
from getopt import gnu_getopt, GetoptError
try:
opts, _args = gnu_getopt(sys.argv[1:], '',
['port=', 'ip=', 'alpinoapi=', 'debug'])
opts = dict(opts)
except GetoptError as err:
print('error: %r' % err, file=sys.stderr)
sys.exit(2)
DEBUG = '--debug' in opts
if '--alpinoapi' in opts:
ALPINOAPI = opts['--alpinoapi']
APP.run(use_reloader=True,
host=opts.get('--ip', '0.0.0.0'),
port=int(opts.get('--port', 5005)),
debug=DEBUG)