mark_potential_errors.py
18.9 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#-*- coding:utf-8 -*-
import re
import sys
import time
import jsonpickle
import natsort
from operator import itemgetter
from django.core.management.base import BaseCommand
from multiservice.facade import Multiservice
from multiservice.facade.ttypes import *
from multiservice.types.ttypes import *
from thrift.transport import TSocket
from webapp.models import Meaning, MeaningStatus, Segment
PORT = 20000
HOST = 'test.multiservice.nlp.ipipan.waw.pl'
NOUN_TAGS = ['subst', 'ger', 'depr']
VERB_TAGS = ['pred', 'fin', 'praet', 'bedzie', 'inf', 'imps',
'impt', 'winien', 'aglt']
class Command(BaseCommand):
help = 'Mark potential errors in the database.'
def handle(self, *args, **options):
mark_potential_errors()
def mark_potential_errors():
for meaning in Meaning.objects.filter(status=None):
expressions = meaning.expressions.all()
for expression in expressions:
if not missing_head(meaning, expression):
# head_is_not_nominal(meaning, expression)
remove_kolega(meaning, expression)
multiservice_checks(meaning, expression)
first_word_is_prep(meaning, expression)
# first_word_is_verb(meaning, expression)
contains_interp(meaning, expression)
contains_owczesny(meaning, expression)
contains_nazwisko(meaning, expression)
contains_lub(meaning, expression)
contains_itp(meaning, expression)
contains_suspension_point(meaning, expression)
contains_skrot(meaning, expression)
contains_np(meaning, expression)
starts_with_interp(meaning, expression)
ends_with_interp(meaning, expression)
def missing_head(meaning, expression):
is_missing = False
try:
expression.segments.get(is_head=True)
except Segment.DoesNotExist:
print (u'Missing head:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Brak głowy: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='modify')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nBrak głowy: %s' % (meaning.comment, expression.text)
meaning.save()
is_missing = True
return is_missing
def head_is_not_nominal(meaning, expression):
head = expression.segments.get(is_head=True)
if head.ctag not in NOUN_TAGS:
print (u'Head is not nominal:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Głowa nie jest nominalna: %s --> %s' % (expression.text, head.orth)
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nGłowa nie jest nominalna: %s --> %s' % (meaning.comment,
expression.text,
head.orth)
meaning.save()
def remove_kolega(meaning, expression):
if expression.segments.get(is_head=True).base == 'kolega':
print (u'Kolega:', meaning)
if not meaning.status:
meaning.comment = u'Głowa to "kolega": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nGłowa to "kolega": %s' % (meaning.comment, expression.text)
meaning.save()
def first_word_is_prep(meaning, expression):
if expression.segments.order_by('position_in_expr')[0].ctag == 'prep':
print (u'First word is prep:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Pierwsze słowo to przyimek: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nPierwsze słowo to przyimek: %s' % (meaning.comment, expression.text)
meaning.save()
def first_word_is_verb(meaning, expression):
if expression.segments.order_by('position_in_expr')[0].ctag in VERB_TAGS:
print (u'First word is verb:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Pierwsze słowo to czasownik: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nPierwsze słowo to czasownik: %s' % (meaning.comment, expression.text)
meaning.save()
def contains_interp(meaning, expression):
if expression.segments.filter(ctag='interp').exclude(orth=',').exists():
print (u'Contains interp:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Zawiera znak interpunkcyjny, nie przecinek: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera znak interpunkcyjny, nie przecinek: %s' % (meaning.comment, expression.text)
meaning.save()
# zamienic na "zawiera date"
# def contains_digit(meaning, expression):
# _digits = re.compile('\d')
# if _digits.search(expression.orth_text):
# print (u'Contains digits:', meaning, '---->', expression)
# if not meaning.status:
# meaning.comment = u'Zawiera cyfrę: %s' % expression.text
# meaning.status = MeaningStatus.objects.get(key='check')
# meaning.save()
# elif meaning.status.key != 'ok':
# meaning.comment = u'%s\n\nZawiera cyfrę: %s' % (meaning.comment, expression.text)
# meaning.save()
def contains_owczesny(meaning, expression):
if expression.segments.filter(base='ówczesny').exists():
print (u'Contains ówczesny:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "ówczesny": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "ówczesny": %s' % (meaning.comment, expression.text)
meaning.save()
def contains_nazwisko(meaning, expression):
if expression.segments.filter(base='nazwisko').exists():
print (u'Contains nazwisko:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "nazwisko": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "nazwisko": %s' % (meaning.comment, expression.text)
meaning.save()
def contains_lub(meaning, expression):
if expression.segments.filter(orth='lub').exists():
print (u'Contains lub:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "lub": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "lub": %s' % (meaning.comment, expression.text)
meaning.save()
def contains_itp(meaning, expression):
if expression.segments.filter(orth='itp').exists():
print (u'Contains itp:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "itp": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "itp": %s' % (meaning.comment, expression.text)
meaning.save()
def contains_suspension_point(meaning, expression):
if '..' in expression.orth_text:
print (u'Contains ...:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera wielokropek: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera wielokropek: %s' % (meaning.comment, expression.text)
meaning.save()
def contains_skrot(meaning, expression):
if expression.segments.filter(base='skrót').exists():
print (u'Contains skrót:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "skrót": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "skrót": %s' % (meaning.comment, expression.text)
meaning.save()
def contains_np(meaning, expression):
if (expression.segments.filter(orth='np').exists() or
expression.segments.filter(orth='Np').exists() or
expression.segments.filter(orth='NP').exists()):
print (u'Contains np:', meaning)
if not meaning.status:
meaning.comment = u'Zawiera słowo "np": %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nZawiera słowo "np": %s' % (meaning.comment, expression.text)
meaning.save()
def starts_with_interp(meaning, expression):
if expression.segments.order_by('position_in_expr')[0].ctag == 'interp':
print (u'Interp at start:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Rozpoczyna się od znaku interpunkcyjnego: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nRozpoczyna się od znaku interpunkcyjnego: %s' % (meaning.comment, expression.text)
meaning.save()
def ends_with_interp(meaning, expression):
if list(expression.segments.order_by('position_in_expr'))[-1].ctag == 'interp':
print (u'Ends with interp:', meaning, '---->', expression)
if not meaning.status:
meaning.comment = u'Kończy się na znaku interpunkcyjnym: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nKończy się na znaku interpunkcyjnym: %s' % (meaning.comment, expression.text)
meaning.save()
def multiservice_checks(meaning, expression):
process_chain = ['Concraft', 'Nerf', 'DependencyParser']
expression_orth = expression.orth_text
json_response = get_json_response(expression_orth, process_chain)
forename_only(meaning, expression, json_response)
head_marked_properly(meaning, expression, json_response)
if expression.is_catchword:
definition_structure(meaning, expression)
def get_json_response(expression, process_chain):
transport, client = getThriftTransportAndClient(HOST, PORT)
request = createRequest(expression, process_chain)
jsonObj = None
try:
token = client.putObjectRequest(request)
status = None
while status not in [RequestStatus.DONE, RequestStatus.FAILED]:
status = client.getRequestStatus(token)
time.sleep(0.1)
if status == RequestStatus.DONE:
result = client.getResultObject(token)
jsonStr = jsonpickle.encode(result, unpicklable=False)
jsonObj = jsonpickle.decode(jsonStr)
else:
print (client.getException(token))
sys.exit("Stopped loading data!")
finally:
transport.close()
return jsonObj
def getThriftTransportAndClient(host, port):
transport = TSocket.TSocket(host, port)
try:
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Multiservice.Client(protocol)
transport.open()
return (transport, client)
except:
transport.close()
raise
def createRequest(text, serviceNames):
ttext = TText(paragraphs=[TParagraph(text=chunk)
for chunk in re.split(r'\n\n+', text)])
chain = [RequestPart(serviceName=name) for name in serviceNames]
request = ObjectRequest(ttext, chain)
return request
def forename_only(meaning, expression, json_response):
if is_forename(expression, json_response):
print (u'Is forename:', meaning)
if not meaning.status:
meaning.comment = u'Jest imieniem: %s' % expression.text
meaning.status = MeaningStatus.objects.get(key='delete')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nJest imieniem: %s' % (meaning.comment, expression.text)
meaning.save()
def is_forename(expression, json_response):
for para in json_response['paragraphs']:
for sent in para['sentences']:
for ne in sent['names']:
if (ne['subtype'] == 'forename' and
expression.orth_text.lower() == ne['orth'].lower()):
return True
return False
def head_marked_properly(meaning, expression, json_response):
tokens = get_tokens(json_response)
root = get_root(tokens, json_response)
if root['tok']['orth'].lower() != expression.segments.get(is_head=True).orth.lower():
print (u'Head is not same as in dependency tree:', expression,
u'dependency parser --> %s' % root['tok']['orth'],
u'database --> %s' % expression.segments.get(is_head=True).orth)
if not meaning.status:
meaning.comment = u'Brak zgodności głów w wyrażeniu %s: ' \
u'parser zależnościowy --> %s, ' \
u'baza --> %s' % (expression.text,
root['tok']['orth'],
expression.segments.get(is_head=True).orth)
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\n' \
u'Brak zgodności głów w wyrażeniu %s: ' \
u'parser zależnościowy --> %s, ' \
u'baza --> %s' % (meaning.comment,
expression.text,
root['tok']['orth'],
expression.segments.get(is_head=True).orth)
meaning.save()
def get_root(tokens, json_response):
root = None
for para in json_response['paragraphs']:
for sent in para['sentences']:
for link in sent['dependencyParse']:
if link['label'] == 'root':
root = tokens[link['endTokenId']]
break
return root
def definition_structure(meaning, catchword):
process_chain = ['Concraft', 'DependencyParser']
for definition in meaning.expressions.exclude(pk=catchword.pk):
sentence = u'%s to %s.' % (definition.orth_text.capitalize(), catchword.orth_text)
json_response = get_json_response(sentence, process_chain)
if not is_definition(catchword, definition, json_response):
print (u'Not a definition:', catchword, '-->', definition)
if not meaning.status:
meaning.comment = u'Nie jest definicją: %s' % sentence
meaning.status = MeaningStatus.objects.get(key='check')
meaning.save()
elif meaning.status.key != 'ok':
meaning.comment = u'%s\n\nNie jest definicją: %s' % (meaning.comment, sentence)
meaning.save()
def is_definition(catchword, definition, json_response):
tokens = get_tokens(json_response)
root = get_root_and_add_links(tokens, json_response)
if root['tok']['chosenInterpretation']['base'] != 'to' or root['tok']['chosenInterpretation']['ctag'] != 'pred':
return False
pd_head = get_pd_head(root)
subj_head = get_subj_head(root)
if not pd_head or not subj_head:
return False
pd_expr = get_subtree_expression(pd_head)
subj_expr = get_subtree_expression(subj_head)
pd_is_catchword = False
pd_is_definition = False
if (pd_expr.lower() == definition.orth_text.lower()):
pd_is_definition = True
elif (pd_expr.lower() == catchword.orth_text.lower()):
pd_is_catchword = True
subj_is_catchword = False
subj_is_definition = False
if (subj_expr.lower() == catchword.orth_text.lower()):
subj_is_catchword = True
if (subj_expr.lower() == definition.orth_text.lower()):
subj_is_definition = True
return ((pd_is_definition and subj_is_catchword) or
(pd_is_catchword and subj_is_definition))
def get_tokens(json_response):
tokens = {}
for para in json_response['paragraphs']:
for sent in para['sentences']:
for tok in sent['tokens']:
tokens[tok['id']] = {'tok': tok,
'links': [],
'root': False,
'id': tok['id']}
return tokens
def get_root_and_add_links(tokens, json_response):
root = None
for para in json_response['paragraphs']:
for sent in para['sentences']:
for link in sent['dependencyParse']:
if link['label'] == 'root':
root = tokens[link['endTokenId']]
else:
from_tok = tokens[link['startTokenId']]
from_tok['links'].append({'to': tokens[link['endTokenId']],
'label': link['label']})
return root
def get_pd_head(root):
for link in root['links']:
if link['label'] == 'pd':
return link['to']
return None
def get_subj_head(root):
for link in root['links']:
if link['label'] == 'subj':
return link['to']
return None
def get_subtree_expression(token):
subtree_expression = ''
subtree_tokens = get_subtree_tokens(token)
subtree_tokens = natsort.natsorted(subtree_tokens, key=itemgetter('id'))
for i, tok in enumerate(subtree_tokens):
if i == 0 or tok['tok']['noPrecedingSpace'] == 'true':
subtree_expression += tok['tok']['orth']
else:
subtree_expression += ' %s' % tok['tok']['orth']
return subtree_expression
def get_subtree_tokens(token):
subtree_tokens = []
subtree_tokens.append(token)
for link in token['links']:
subtree_tokens.extend(get_subtree_tokens(link['to']))
return subtree_tokens