-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcoref.py
More file actions
2647 lines (2468 loc) · 99.2 KB
/
coref.py
File metadata and controls
2647 lines (2468 loc) · 99.2 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Dutch coreference resolution & dialogue analysis using deterministic rules.
Usage: python3 coref.py [options] <directory>
where directory contains .xml files with sentences parsed by Alpino.
Filenames and sentence IDs are expected to be of the form `n.xml` or `m-n.xml`,
where `n` is a sentence number and `m` a paragraph number.
Output is sent to STDOUT unless --outputprefix is used.
Options:
--help this message
--slice=N:M restrict input with a Python slice of sentence numbers
--verbose debug output instead of coreference output
--gold=<file> CoNLL file with document matching basename of input dir;
with --verbose, show error analysis against this file.
--goldmentions instead of predicting mentions, use mentions in --gold file
--goldclusters instead of predicting clusters, use clusters in --gold file
--maxprondist=n the maximum distance in sentences between pronoun and
antecedent; only affects rule-based resolver (default: 15)
--fmt=<conll2012|semeval2010|booknlp|html|htmlp>
output format:
:conll2012: tabular format (default)
:booknlp: tabular format with universal dependencies and dialogue
information in addition to coreference.
:html: interactive visualization of coreference and dialogue.
:htmlp: include parse trees (click on sentence to toggle).
--outputprefix=<prefix>
write conll/mention/cluster/link info to files
prefix.{mentions,clusters,links,quotes}.tsv (tabular format)
prefix.conll (--fmt), and prefix.icarus (ICARUS allocation format)
--neural=<span,feat,pron,quote>
enable one or more neural components:
:span: see mentionspanclassifier.py
:feat: see mentionfeatureclassifier.py
:pron: see pronounresolution.py
:quote: see qaclassifier.py
--exclude=<item1,item2,...>
exclude given types of mentions from output:
:singletons: mentions without any coreference links
:npsingletons: non-name mentions without any coreference links
:relpronouns: relative pronouns
:reflexives: obligatory reflexive pronouns
:reciprocals: reciprocal pronouns
:appositives: appositives NPs
:predicatives: nominal predicatives
:relpronounsplit: relative clause boundary includes whole clause
--excludelinks=<item1,item2,...>
similar to --excludementions, but only removes links to given mentions.
Instead of specifying a directory and gold file, can use the following presets:
--clin=<dev|test> run evaluation on CLIN26 shared task data
--semeval=<dev|test> run evaluation on SemEval 2010 data
--sonar=<dev|test> run evaluation on SoNaR data
--test run unit tests"""
import io
import os
import re
import sys
import getopt
import subprocess
from collections import defaultdict
from itertools import islice
from bisect import bisect
from datetime import datetime
from glob import glob
from lxml import etree
import pandas
import jinja2
import colorama
import ansi2html
TITLES = (
'dr drs ing ir mr lic prof mevr mw bacc kand dr.h.c ds bc '
'bsc msc ma ba bv nv b.v n.v mevrouw meneer heer doctor professor'
).split()
STOPWORDS = (
# List of Dutch Stop words (http://www.ranks.nl/stopwords/dutch)
'aan af al als bij dan dat de die dit een en er had heb hem het hij '
'hoe ik in is je kan me men met mij nog nu of ons ook te tot uit '
'van was wat we wel wij zal ze zei zij zo zou ').split() + TITLES
# Reported speech verbs as they appear in the "root" attribute.
SPEECHVERBS = frozenset((
'begin onthul loof kondig_aan beweer breng_in deel_mee merk_op zeg_op '
'spreek breng_uit druk_uit uit spreek_uit verklaar verkondig vermeld '
'vertel verwoord duid_aan benoem tendeer_in meen noem oordeel stel '
'vind beduid behels beteken bewijs beveel gebied draag_op neem_aan '
'veronderstel merk_aan verwijt beloof zeg_toe schrijf_voor geef_aan '
'stip_aan kondig_af maak_bekend bericht beschrijf declareer gewaag '
'meld geef_op neem_op teken_op relateer proclameer publiceer sus '
'rapporteer leg_vast vernoem versla zeg betoon betuig manifesteer '
'openbaar peer_op slaak spui sla_uit stort_uit stoot_uit vertolk '
'ventileer deponeer expliciteer getuig ontvouw pretendeer doe_uiteen '
'zet_uiteen verzeker kleed_in lucht breng_over toon vervat geef_weer '
'betoog claim suggereer houd_vol geef_voor wend_voor verdedig vraag '
'spreek_aan bestempel betitel kwalificeer som_op draai_af debiteer '
'deel_mede dis_op kraam_uit verhaal poneer postuleer leg_voor beval '
'fluister voorspel roep antwoord voeg reageer merk benadruk herhaal '
'vervolg verzucht klaag protesteer stotter sis grom brom brul snauw '
'schreeuw begin opper mompel loog onderbreek interrumpeer smeek gil '
'mopper constateer beaam besluit concludeeer vul_aan informeer zucht '
'waarschuw verduidelijk stamel beken hijg kreun jammer bulder krijs '
'snik prevel bevestig grinnik verontschuldig grap murmel bries '
'piep kir ').split())
# Weather verbs as they appear in the "lemma" attribute;
# e.g. het dooit; het kan morgen dooien; etc.
WEATHERVERBS = ('dooien gieten hagelen miezeren misten motregenen onweren '
'plenzen regenen sneeuwen stormen stortregenen ijzelen vriezen '
'weerlichten winteren zomeren').split()
VERBOSE = False
DEBUGFILE = sys.stdout
BASEDIR = os.path.dirname(os.path.abspath(__file__))
PARENTDIR = os.path.dirname(BASEDIR)
class Mention:
"""A span referring to an entity.
:ivar clusterid: cluster (entity) ID this mention is in.
:ivar prohibit: do not link this mention to these mention IDs.
:ivar filter: if True, do not include this mention in output.
:ivar relaxedtokens: list of tokens without postnominal modifiers.
:ivar head: node corresponding to head word.
:ivar type: one of ('name', 'noun', 'pronoun')
:ivar mainmod: list of string tokens that modify the head noun
:ivar features: dict with following keys and possible values:
:number: ('sg', 'pl', 'both', None); None means unknown.
:gender: ('m', 'f', 'n', 'fm', 'mn', 'fn', None)
:human: (0, 1, None)
:person: ('1', '2', '3', None); only for pronouns.
:ivar antecedent: mention ID of antecedent of this mention, or None.
:ivar sieve: name of sieve responsible for linking this mention, or None.
"""
def __init__(self, mentionid, sentno, parno, tree, node, begin, end,
headidx, tokens, ngdata, gadata):
"""Create a new mention.
:param mentionid: unique integer for this mention.
:param sentno: global sentence index (ignoring paragraphs, 0-indexed)
this mention occurs in.
:param tree: lxml.ElementTree with Alpino XML parse tree of sentence
:param node: node in tree covering this mention
(although begin and end may describe a smaller span)
:param begin: start index in sentence of mention (0-indexed)
:param end: end index in sentence of mention (exclusive)
:param headidx: index in sentence of head word of mention
:param tokens: list of tokens in mention as strings
:param ngdata: look up table with number and gender data
:param gadata:: look up table with gender and animacy data
"""
self.id = mentionid
self.sentno = sentno
self.parno = parno
self.node = node
self.begin = begin
self.end = end
self.tokens = tokens
self.clusterid = mentionid
self.prohibit = set()
self.filter = False
self.antecedent = self.sieve = None
self.parentheadword = self.parentheadwordidx = None
removeids = {n for rng in
(range(int(child.get('begin')), int(child.get('end')))
for child in node.findall('.//node[@rel="app"]')
+ node.findall('.//node[@rel="mod"]'))
for n in rng if n > headidx}
# without mod/app constituents after head
self.relaxedtokens = [token.get('word') for token
in sorted((token for token in tree.findall('.//node[@word]')
if begin <= int(token.get('begin')) < end
and int(token.get('begin')) not in removeids),
key=lambda x: int(x.get('begin')))]
if not self.relaxedtokens:
self.relaxedtokens = self.tokens
self.head = (tree.find('.//node[@begin="%d"][@word]' % headidx)
if len(node) else node)
if node.get('pdtype') == 'pron' or node.get('vwtype') == 'bez':
self.type = 'pronoun'
elif (self.head.get('ntype') == 'eigen'
or self.head.get('pt') == 'spec'):
self.type = 'name'
else:
self.type = 'noun'
# main modifiers: nouns, adjectives. we also add possessive pronouns.
self.mainmod = [a.get('word') for a
in (node.findall('.//node[@word]') if len(node) else (node, ))
if (a.get('rel') == 'mod' or a.get('pt') in ('adj', 'n')
or a.get('vwtype') == 'bez')
and begin <= int(a.get('begin')) < end]
self.features = {
'human': None, 'gender': None,
'number': None, 'person': None}
parentheadword = getparentheadword(node)
if parentheadword is not None:
self.parentheadword = parentheadword.get('root')
self.parentheadwordidx = int(parentheadword.get('begin'))
self._detectfeatures(ngdata, gadata)
def _detectfeatures(self, ngdata, gadata):
"""Set features for this mention based on linguistic features or
external dataset."""
firsttoken = self.node.find('.//node[@word][@begin="%d"]' % self.begin)
self.features['number'] = self.head.get(
'rnum', self.head.get('num'))
if self.features['number'] is None and 'getal' in self.head.keys():
self.features['number'] = {
'ev': 'sg', 'mv': 'pl', 'getal': 'both'
}[self.head.get('getal')]
if len(self.node) > 1 and self.node[0].get('rel') == 'cnj':
self.features['number'] = 'pl'
if self.head.get('genus') in ('masc', 'fem'):
self.features['gender'] = self.head.get('genus')[0]
self.features['human'] = 1
elif (self.head.get('genus') == 'onz'
or self.head.get('gen') == 'het'):
self.features['gender'] = 'n'
self.features['human'] = 0
if self.type == 'pronoun': # pronouns: rules
if self.head.get('persoon')[0] in '123':
self.features['person'] = self.head.get('persoon')[0]
if self.features['person'] in ('1', '2'):
self.features['gender'] = 'fm'
self.features['human'] = 1
elif self.head.get('persoon') == '3p':
self.features['gender'] = 'fm'
self.features['human'] = 1
elif self.head.get('persoon') == '3o':
self.features['gender'] = 'n'
self.features['human'] = 0
if self.head.get('lemma') == 'haar':
self.features['gender'] = 'fn'
elif self.head.get('lemma') == 'zijn':
self.features['gender'] = 'mn'
elif (self.head.get('lemma') in ('hun', 'hen')
and self.head.get('vwtype') == 'pers'):
self.features['human'] = 1
# nouns: use lexical resource (also includes first names list)
elif self.head.get('lemma', '').replace('_', '') in gadata:
self.features.update(galookup(self.head.get('lemma', ''), gadata))
elif (len(self.tokens) > 1 and firsttoken is not None
and firsttoken.get('neclass') is None
and self.tokens[0].lower() in gadata): # e.g. "meneer Grey"
self.features.update(galookup(self.tokens[0].lower(), gadata))
else: # names: dict
if self.head.get('neclass') == 'PER':
self.features['human'] = 1
self.features['gender'] = 'fm'
elif self.head.get('neclass') is not None:
self.features['human'] = 0
self.features['gender'] = 'n'
result = nglookup(' '.join(self.tokens), ngdata)
if result:
self.features.update(result)
elif (self.head.get('neclass') == 'PER'
and self.tokens[0].lower().strip('.') not in STOPWORDS):
# Assume first token is first name.
self.features.update(nglookup(self.tokens[0], ngdata))
def featrepr(self, extended=False):
"""String representations of features."""
result = ' '.join('%s=%s' % (a[0], '?' if b is None else b)
for a, b in self.features.items())
result += ' q=%d' % int(self.head.get('quotelabel') == 'I')
if extended:
result += ' ne=%s hd=%s' % (
self.head.get('neclass'), self.head.get('word'))
return result
def __str__(self):
return '%s' % color(' '.join(self.tokens), 'green')
def __repr__(self):
return "Mention('%s', ...)" % ' '.join(self.tokens)
def __getstate__(self):
"""Strip lxml objects since they can't be pickled."""
return {a: b for a, b in self.__dict__.items()
if a not in ('node', 'head')}
class Quotation:
"""A span of direct speech.
:ivar speaker: detected speaker Mention object.
:ivar addressee: detected addressee Mention object.
:ivar mentions: list of Mention objects occurring in this quote.
"""
def __init__(self, start, end, sentno, endsentno, parno, text, sentbounds):
"""
:param start: global token start index.
:param end: global token end index.
:param sentno: global sentence index (ignoring paragraphs).
:param endsentno: relevant for multi-sentence quotes.
:param parno: paragraph number.
:param text: text of quote as string (including quote marks).
:param sentbounds: bool, whether quote starts+ends at sent boundaries.
"""
self.start, self.end = start, end
self.sentno = sentno
self.endsentno = endsentno
self.parno = parno
self.sentbounds = sentbounds
self.speaker = None
self.addressee = None
self.mentions = []
self.text = text
def __repr__(self):
return '%d %d %r' % (self.parno, self.sentno, self.text)
def getmentioncandidates(tree, conj=False):
"""Extract mention candidates for a given sentence."""
candidates = []
# Order is significant.
candidates.extend(tree.xpath(
'.//node[@pdtype="pron" or @vwtype="bez"]'))
candidates.extend(tree.xpath('.//node[@cat="np"]'))
if conj:
candidates.extend(tree.xpath(
'.//node[@cat="conj"]/node[@cat="np" or @pt="n"]/..'))
candidates.extend(tree.xpath(
'.//node[@cat="mwu"]/node[@pt="spec" or @ntype="eigen"]/..'))
candidates.extend(tree.xpath('.//node[@pt="n"]'
'[@ntype="eigen" or @rel="su" or @rel="obj1" or @rel="body" '
'or @rel="cnj" or @special="er_loc"]'))
candidates.extend(tree.xpath(
'.//node[@pt="num" and @rel!="det" and @rel!="mod"]'))
candidates.extend(tree.xpath('.//node[@pt="det" and @rel!="det"]'))
return candidates
def getmentions(trees, ngdata, gadata, relpronounsplit):
"""Collect and filter mentions."""
mentions = []
for sentno, ((parno, _), tree) in enumerate(trees):
candidates = getmentioncandidates(tree)
covered = set()
for candidate in candidates:
considermention(candidate, tree, sentno, parno, mentions, covered,
ngdata, gadata, relpronounsplit)
# sort by sentence and start token, then from longest to shortest span
mentions.sort(key=lambda x: (x.sentno, x.begin, x.begin - x.end))
for n, mention in enumerate(mentions):
mention.id = mention.clusterid = n # fix mention IDs after sorting
return mentions
def adjustmentionspan(node, tree, relpronounsplit):
"""Find suitable mention span for given node."""
headidx = getheadidx(node)
indices = sorted(int(token.get('begin')) for token
in (node.findall('.//node[@word]') if len(node) else [node]))
a, b = min(indices), max(indices) + 1
# allow comma when preceded by conjunct, adjective, or location.
for punct in tree.getroot().findall('./node/node[@pt="let"]'):
i = int(punct.get('begin'))
if (a <= i < b
and (node.find('.//node[@begin="%d"][@rel="cnj"]' % (i - 1))
is not None
or node.find('.//node[@begin="%d"][@pt="adj"]' % (i - 1))
is not None
or node.find('.//node[@begin="%d"][@neclass="LOC"]' % (i - 1))
is not None)):
indices.append(i)
indices.sort()
# if span is interrupted by a discontinuity from other words or
# punctuation, cut off mention before it; avoids weird long mentions.
if indices != list(range(a, b)):
b = min(n for n in range(a, b) if n not in indices)
if headidx > b:
headidx = max(int(token.get('begin')) for token
in node.findall('.//node[@word]')
if int(token.get('begin')) < b)
# remove "vc" clause from NP:
# [Behrmans voorstel] om samen te eten
# [het feit] dat ...
vc = node.find('./node[@rel="vc"]')
if relpronounsplit and vc is not None:
# get actual token indices, because span of vc may be incorrect
vcindices = sorted(int(token.get('begin')) for token
in (vc.findall('.//node[@word]') if len(vc) else [vc]))
if min(vcindices) < b:
b = min(vcindices)
if a == b: # vc in first position
return a, b, headidx, []
if headidx > b:
headidx = max(int(token.get('begin')) for token
in node.findall('.//node[@word]')
if int(token.get('begin')) < b)
# Relative clauses: [de man] [die] ik eerder had gezien.
# [een buurt] [waar] volgens hem ondanks de Wende niets veranderd was.
relpronoun = node.find('./node[@cat="rel"]/node[@rel="rhd"]')
if (relpronounsplit and relpronoun is not None
and int(relpronoun.get('begin')) < b):
b = int(relpronoun.get('begin'))
if a == b:
return a, b, headidx, []
if headidx > b:
headidx = max(int(token.get('begin')) for token
in node.findall('.//node[@word]')
if int(token.get('begin')) < b)
# Appositives: "[Jan], [de schilder]"
if len(node) > 1 and node[-1].get('rel') == 'app':
if (len(node) == 2
and node[1].get('ntype') != 'eigen'
and node[1].get('pt') != 'spec'
and (node[1].get('cat') != 'mwu'
or node[1][0].get('pt') != 'spec')):
node = node[0]
b = int(node.get('end'))
else: # but: "[acteur John Cleese]"; head: Cleese.
h1 = getheadidx(node[-1])
if h1 < b:
headidx = h1
# mevrouw [Steele] => [mevrouw Steele]
if (node.get('rel') == 'nucl' and a
and gettokens(tree, a - 1, a)[0].lower().strip('.') in TITLES):
a -= 1
headidx = a
# [ook Perry] => [Perry]
x = node.find('.//node[@word][@begin="%d"]' % a)
if x is not None and x.get('pt') == 'bw':
a += 1
tokens = gettokens(tree, a, b)
# Trim punctuation
if tokens and tokens[0] in ',\'"()':
tokens = tokens[1:]
a += 1
if tokens and tokens[-1] in ',\'"()':
tokens = tokens[:-1]
b -= 1
return a, b, headidx, tokens
def considermention(node, tree, sentno, parno, mentions, covered,
ngdata, gadata, relpronounsplit):
"""Decide whether a candidate mention should be added."""
if len(node) == 0 and 'word' not in node.keys():
return
a, b, headidx, tokens = adjustmentionspan(node, tree, relpronounsplit)
if not tokens: # mention cannot be only punctuation
return
head = (tree.find('.//node[@begin="%d"][@word]' % headidx)
if len(node) else node)
# various
if head.get('lemma') in ('aantal', 'keer', 'toekomst', 'manier'):
return
if pleonasticpronoun(node):
return
x = node.find('./node[@pt="tw"]')
if x is not None and x.get('word').isnumeric():
return
if (headidx not in covered
# discard measure phrases
# and node.find('.//node[@num="meas"]') is None
and node.get('num') != "meas"
# and node.find('./node[@pt="tw"]') is None
# and not tokens[0].isnumeric()
# "a few" ...
and (node.get('cat') != 'np' or node.get('rel') != 'det')
# "welk" in "Ik ga niet zeggen welk restaurant"
and node.find('.//node[@begin="%d"][@vwtype="onbep"]' % a) is None
and node.find('.//node[@begin="%d"][@vwtype="vb"]' % a) is None
# "iets"
and node.get('vwtype') not in ('onbep', 'vb')
# temporal expressions
and head.get('special') != 'tmp' and node.get('special') != 'tmp'
# partitive / quantifier
# ongeveer 12 dollar
and node.find('./node[@sc="noun_prep"]') is None
# and (node.get('cat') != 'np'
# or node[0].get('pos') not in ('adj', 'noun'))
# het fietsen
and head.get('pt') != 'ww'
# tien kilometer joggen
and node.find('./node[@pt="ww"][@wvorm="inf"]') is None
):
mentions.append(Mention(
len(mentions), sentno, parno, tree, node, a, b, headidx,
tokens, ngdata, gadata))
covered.add(headidx)
# California in "San Jose, California"
if (node.get('cat') == 'mwu' and head.get('neclass') == 'LOC'
and ',' in tokens):
headidx = b - 1
if headidx not in covered:
mentions.append(Mention(
len(mentions), sentno, parno, tree, node,
a + tokens.index(',') + 1, b, b - 1,
tokens[tokens.index(',') + 1:],
ngdata, gadata))
covered.add(headidx)
elif len(node) > 1 and node[0].get('rel') == 'cnj':
for cnj in node.findall('./node[@rel="cnj"]'):
a, b = int(cnj.get('begin')), int(cnj.get('end'))
headidx = getheadidx(cnj)
if headidx not in covered:
mentions.append(Mention(
len(mentions), sentno, parno, tree, cnj,
a, b, headidx,
gettokens(tree, a, b), ngdata, gadata))
covered.add(headidx)
def pleonasticpronoun(node):
"""Return True if node is a pleonastic (non-referential) pronoun."""
# Examples from Lassy syntactic annotation manual.
if node.get('rel') in ('sup', 'pobj1'):
return True
if node.get('lemma') == 'dat' and node.get('vwtype') == 'aanw':
return True
if node.get('lemma') == 'het' and node.get('rel') == 'su':
head = node.find('../node[@rel="hd"]')
# het regent. / hoe gaat het?
if head.get('lemma') in WEATHERVERBS or head.get('lemma') == 'gaan':
return True
if (head.get('lemma') == 'ontbreken'
and node.find('../node[@rel="pc"]'
'/node[@rel="hd"][@lemma="aan"]') is not None):
return True
# het kan voorkomen dat ...
if (node.get('index') and node.get('index')
in node.xpath('../node//node[@rel="sup"]/@index')):
return True
# FIXME: add rules to detect non-pleonastic use
# e.g.: add rule: "Het is [NP-mention]" is ok
# but not "Het is ADJ", "Het is alsof ..."
return True # assume pleonastic ...
if node.get('lemma') == 'het' and node.get('rel') == 'obj1':
head = node.find('../node[@rel="hd"]')
head = '' if head is None else head.get('lemma')
# (60) de presidente had het warm
if head == 'hebben' and node.find('../node[@rel="predc"]') is not None:
return True
# (61) samen zullen we het wel rooien.
if head == 'rooien':
return True
# (62) hij zette het op een lopen
if (head == 'zetten' and node.find('../node[@rel="svp"]/'
'node[@word="lopen"]') is not None):
return True
# (63) had het op mij gemunt.
if head == 'munten' and node.find('..//node[@word="op"]') is not None:
return True
# (64) het erover hebben
if (head == 'hebben'
and (node.find('../node[@word="erover"]') is not None
or (node.find('..//node[@word="er"]') is not None
and node.find('..//node[@word="over"]') is not None))):
return True
# FIXME: add rules to detect non-pleonastic use
return True # assume pleonastic ...
return False
def getquotations(trees):
"""Detect quoted speech spans and speaker / addressee if possible.
Marks tokens in quoted speech with B, I, O labels.
- Quoted speech within other quoted speech is not marked.
- Quoted speech ends at end of paragraph even if no marker is found.
- Quoted speech can be introduced by ASCII single '/` or double quotes "/``
or by a dash '-' at the start of a paragraph. Unicode quotes should be
normalized to ASCII quotes in preprocessing.
"""
# dictionary mapping open quote char to closing quote char
quotechar = {
"'": "'",
'"': '"',
'`': "'",
'``': "''",
}
# convert to flat list of tokens
doc = [] # list of tokens as XML nodes by global token index
parbreak = [] # True if new paragraph starts at token index
idx = {} # map (sentno, tokenno) to global token index
sentnos = [] # map global token index to sentno
parnos = [] # map global token index to parno
i = 0
for sentno, ((parno, psentno), tree) in enumerate(trees):
for n, token in enumerate(sorted(
tree.iterfind('.//node[@word]'),
key=lambda x: int(x.get('begin')))):
doc.append(token)
parbreak.append(psentno == 1 and n == 0)
idx[sentno, n] = i
sentnos.append(sentno)
parnos.append(parno)
i += 1
quotations = []
inquote = start = None
for i, token in enumerate(doc):
n = int(token.get('begin'))
if inquote and parbreak[i]:
inquote = None
end = i
quotations.append(Quotation(start, end,
sentnos[start], sentnos[end - 1], parnos[start],
' '.join(doc[i].get('word') for i
in range(start, end)),
True))
if inquote is None and parbreak[i] and token.get('word') == '-':
# detect implied end of quote:
# - I like cats, he said
token.set('quotelabel', 'B')
start = i
_, tree = trees[sentnos[i]]
verb = tree.getroot().find('./node/node[@cat="du"]/node[@cat="sv1"]'
'[@rel="tag"]/node[@rel="hd"]')
if verb is not None and verb.get('root') in SPEECHVERBS:
node = tree.getroot().find(
'./node/node[@cat="du"]/node[@rel="nucl"]')
end = idx[sentnos[i], int(node.get('end'))]
quotations.append(Quotation(start, end,
sentnos[start], sentnos[end - 1], parnos[start],
' '.join(doc[i].get('word') for i
in range(start, end)),
False))
for x in range(start + 1, end):
doc[x].set('quotelabel', 'I')
else:
inquote = '\n'
elif inquote is None and token.get('word') in quotechar:
token.set('quotelabel', 'B')
inquote = quotechar[token.get('word')]
start = i
elif token.get('word') == inquote:
token.set('quotelabel', 'I')
inquote = None
end = i + 1
quotations.append(Quotation(start, end,
sentnos[start], sentnos[end - 1], parnos[start],
' '.join(doc[i].get('word') for i
in range(start, end)),
int(doc[start].get('begin')) == 0
and (i + 2 >= len(doc)
or int(doc[i + 1].get('begin')) == 0
or int(doc[i + 2].get('begin')) == 0)))
elif token.get('quotelabel') is None:
token.set('quotelabel', 'I' if inquote else 'O')
return quotations, idx, doc
def isspeaker(mention):
"""Test whether mention is subject of a reported speech verb."""
if (mention.node.get('rel') != 'su'
or mention.head.get('quotelabel') == 'I'):
return False
head1 = mention.node.find('../node[@cat="ppart"]/node[@rel="hd"]')
head2 = mention.node.find('../node[@rel="hd"]')
head = head2 if head1 is None else head1
return head is not None and head.get('root') in SPEECHVERBS
def speakeridentification(mentions, quotations, idx, doc):
"""Identify speakers and addressees for quotations."""
debug(color(
'speaker identification (%d quotations)' % len(quotations),
'yellow'))
if not quotations:
return
tokenidx2quotation = {i: quotation
for quotation in quotations
for i in range(quotation.start, quotation.end)}
# collect mentions within each quote
for mention in mentions:
if idx[mention.sentno, mention.begin] in tokenidx2quotation:
i = idx[mention.sentno, mention.begin]
tokenidx2quotation[i].mentions.append(mention)
# collect mentions within each paragraph
par2mention = defaultdict(list)
for mention in mentions:
# Only consider human mentions that are not possessive pronouns.
if (mention.features['human']
and mention.head.get('quotelabel') != 'I'
and mention.head.get('vwtype') != 'bez'):
par2mention[mention.parno].append(mention)
# quote attribution sieves; cf. https://aclweb.org/anthology/E17-1044
vocative(quotations, doc, idx, tokenidx2quotation)
reportedspeech(mentions, quotations, doc, idx)
singularmentionspeaker(quotations, par2mention)
splitquotes(quotations)
previoussubject(quotations, par2mention, idx)
turntaking(quotations)
turntaking(quotations, strict=False)
speakerconstraints(quotations, doc)
def vocative(quotations, doc, idx, tokenidx2quotation):
"""Vocative => addressee; e.g. 'John, do the dishes.'"""
# vocative patterns from https://aclweb.org/anthology/E17-1044
for quotation in quotations:
for mention in quotation.mentions:
if mention.features['human']:
try:
w1 = doc[idx[mention.sentno, mention.begin] - 1].get('word')
w2 = doc[idx[mention.sentno, mention.end]].get('word')
except (KeyError, IndexError):
continue
if ((w1 == ',' and w2 in '!?.,;')
or (w1 in '\'"' and w2 == ',')
or (w1 == ',' and w2 in '\'"')
or (w1.lower() == 'o' and w2 == '!')
or (w1.lower() in ('beste', 'lieve'))):
quotation.addressee = mention
debug('detected vocative %s\n\taddressee %s' % (
color(quotation.text, 'green'), mention))
break
def reportedspeech(mentions, quotations, doc, idx):
"""Link each subject of a reported speech verb to the closest quotation."""
qstarts = [q.start for q in quotations]
qends = [q.end for q in quotations]
for mention in mentions:
if isspeaker(mention):
i = idx[mention.sentno, mention.begin]
i1 = idx[mention.sentno, 0]
i2 = idx.get((mention.sentno + 1, 0), len(doc))
# first quote to left of mention
q1 = quotations[bisect(qends, i) - 1]
if i1 < q1.end <= i2 and i - q1.end <= 5 and q1.speaker is None:
q1.speaker = mention
debug('%s\n\tis before reported speech verb; speaker: %s'
% (color(q1.text, 'green'), q1.speaker))
else:
# first quote to right of mention
x = bisect(qstarts, i)
q2 = quotations[x if x < len(quotations) else x - 1]
if (i1 <= q2.start < i2 and q2.start - i <= 5
and q2.speaker is None):
q2.speaker = mention
debug('%s\n\tis after reported speech verb; speaker: %s'
% (color(q2.text, 'green'), q2.speaker))
def singularmentionspeaker(quotations, par2mention):
"""Attribute quote if there is a single human mention in paragraph."""
for quotation in quotations:
if (quotation.speaker is None
and len(par2mention[quotation.parno]) == 1):
quotation.speaker = par2mention[quotation.parno][0]
debug('attributed %s\n\tto singular non-quoted human mention '
'in paragraph: %s' % (color(quotation.text, 'green'),
quotation.speaker))
def splitquotes(quotations):
"""Assume same speaker for consecutive quotations in same paragraph.
Example: "I don't know", he said. "It seems a bad idea."
Only applies when there is material outside quotes."""
for prev, quotation in zip(quotations, quotations[1:]):
if (quotation.parno == prev.parno
and quotation.sentno <= prev.sentno + 1
and not prev.sentbounds):
if quotation.speaker is None and prev.speaker is not None:
quotation.speaker = prev.speaker
debug('%s\n\tis directly after previous quote; '
'assuming same speaker %s'
% (color(quotation.text, 'green'), prev.speaker))
if quotation.addressee is None and prev.addressee is not None:
quotation.addressee = prev.addressee
debug('%s\n\tis directly after previous quote; '
'assuming same addressee %s'
% (color(quotation.text, 'green'), prev.speaker))
def previoussubject(quotations, par2mention, idx):
# For unattributed quotes without material before or after quote in the
# sentence, assign closest human mention in same paragraph.
# When there is material before or after the quote, it may not be a
# dialogue turn, e.g.
# 'Every happy family is alike,' according to Tolstoy's Anna Karenina.
for prev, quotation in zip([None] + quotations, quotations):
if quotation.speaker is None and quotation.sentbounds:
# Find mention in sentence before quote
candidates = [mention for mention in par2mention[quotation.parno]
if (quotation.sentno - 1 == mention.sentno
and (prev is None
or prev.end <= idx[mention.sentno, mention.begin])
and quotation.addressee != mention
and mention.node.get('rel') == 'su')]
for mention in sorted(
candidates,
key=lambda m: quotation.start - m.end
if quotation.start >= idx[m.sentno, m.end]
else idx[m.sentno, m.begin] - quotation.end):
quotation.speaker = mention
debug('assuming bare quotation %s\n'
'\tspoken by subject of previous sentence: %s' % (
color(quotation.text, 'green'), quotation.speaker))
break
def turntaking(quotations, strict=True):
"""Heuristics for consecutive quotations.
:param strict: if True, only consider quotations without intervening
sentences; if False, also consider consecutive paragraphs with
non-quoted sentences."""
# Consecutive quotations in different paragraphs are turn taking;
# or when first quotation has no material outside quotation marks
# "How are you?" "I'm fine."
# By propagating speakers and addressees,
# we capture 2n and 2n+1 turntaking patterns (ABABAB...)
# FIXME: how to detect multiple consecutive turns (AAAB)
for prev, quotation in zip(quotations, quotations[1:]):
if ((strict and quotation.sentno == prev.endsentno + 1
and quotation.parno == prev.parno + 1)
or (not strict and quotation.parno == prev.parno + 1)
or (quotation.parno == prev.parno
and quotation.sentno == prev.sentno + 1
and quotation.sentbounds and prev.sentbounds)):
if (quotation.speaker is None
and prev.addressee is not None
and prev.addressee != quotation.addressee
and (quotation.addressee is None
or prev.addressee.tokens != quotation.addressee.tokens)
):
quotation.speaker = prev.addressee
debug('assuming %s\n\tis spoken by previous addressee %s' % (
color(quotation.text, 'green'), prev.addressee))
if (prev.speaker is None
and quotation.addressee is not None
and quotation.addressee != prev.addressee
and (prev.addressee is None
or quotation.addressee.tokens != prev.addressee.tokens)
):
prev.speaker = quotation.addressee
debug('assuming %s\n\tis spoken by addressee %s of next quote'
% (color(prev.text, 'green'), quotation.addressee))
if (quotation.addressee is None
and prev.speaker is not None
and prev.speaker != quotation.speaker
and (quotation.speaker is None
or prev.speaker.tokens != quotation.speaker.tokens)
):
quotation.addressee = prev.speaker
debug('assuming %s\n\tis addressed to previous speaker %s' % (
color(quotation.text, 'green'), prev.speaker))
if (prev.addressee is None
and quotation.speaker is not None
and quotation.speaker != prev.speaker
and (prev.speaker is None
or quotation.speaker.tokens != prev.speaker.tokens)
):
prev.addressee = quotation.speaker
debug('assuming %s\n\tis addressed to speaker %s of next quote'
% (color(prev.text, 'green'), quotation.speaker))
def speakerconstraints(quotations, doc):
"""Add speaker constraints."""
for prev, quotation in zip([None] + quotations, quotations):
if quotation.speaker is None:
debug('no speaker: %s' % color(quotation.text, 'green'))
for i in range(quotation.start, quotation.end):
if quotation.speaker is not None:
doc[i].set('speaker', str(quotation.speaker.clusterid))
if quotation.addressee is not None:
doc[i].set('addressee', str(quotation.addressee.clusterid))
nominalmentions = [mention for mention in quotation.mentions
if mention.type == 'noun']
for mention in quotation.mentions:
if (mention.type == 'pronoun'
and mention.features['person'] in ('1', '2')):
# Nominal mentions cannot be coreferent with
# I, you, or we in the same turn or quotation.
mention.prohibit.update(
mention.id for mention in nominalmentions)
if (quotation.speaker is not None
and (mention.type != 'pronoun'
or mention.features['person'] != '1'
or mention.features['number'] != 'sg')):
# speaker and not-I-mentions in quote cannot be coreferent
mention.prohibit.add(quotation.speaker.id)
if (quotation.addressee is not None
and (mention.type != 'pronoun'
or mention.features['person'] != '2'
or mention.features['number'] != 'sg')):
# addressee and not-you-mentions in quote cannot be coreferent
mention.prohibit.add(quotation.addressee.id)
for person in ('1', '2'):
for number in ('sg', 'pl'):
pronouns = [a for a in quotation.mentions
if a.features['person'] == person
and a.features['number'] == number]
# two pronouns with different person/number cannot corefer
for a in pronouns:
for b in quotation.mentions:
if (b.type == 'pronoun'
and (b.features['person'] != person
or b.features['number'] != number)):
a.prohibit.add(b.id)
b.prohibit.add(a.id)
# 1/2nd person mentions from different speaker cannot corefer
# block selectively for adjacent quotes by different speakers
if (prev is not None and number == 'sg'
and prev.speaker is not quotation.speaker):
for a in pronouns:
for b in prev.mentions:
if b.features['person'] == person:
a.prohibit.add(b.id)
b.prohibit.add(a.id)
# end of dialogue related functions
def stringmatch(mentions, clusters, relaxed=False):
"""Link mentions with matching strings;
if relaxed, ignore modifiers/appositives."""
debug(color('string match (relaxed=%s)' % relaxed, 'yellow'))
sieve = 'stringmatch:relaxed' if relaxed else 'stringmatch'
foundentities = {}
for _, mention in representativementions(mentions, clusters):
if mention.type != 'pronoun':
if (len(clusters[mention.clusterid]) == 1
and mention.node.get('ntype') == 'soort'
and mention.features['number'] == 'pl'):
continue
mstr = ' '.join(mention.relaxedtokens
if relaxed else mention.tokens).lower()
if mstr in foundentities:
merge(foundentities[mstr], mention, sieve, mentions, clusters)
else:
foundentities[mstr] = mention
def preciseconstructs(mentions, clusters):
"""Link syntactically related mentions:
appositives, predicatives, relative pronouns."""
debug(color('precise constructs', 'yellow'))
appositives = {}
predicatives = {}
relpronouns = {}
reflpronouns = {}
recippronouns = {}
acronyms = {}
# Pass 1: collect antecedents
for mention in mentions:
if (mention.node.get('rel') != 'app'
and len(mention.node.getparent()) > 1
and mention.node.getparent()[1].get('rel') == 'app'):
node = mention.node.getparent()[1]
appositives[mention.sentno,
int(node.get('begin')), int(node.get('end'))
] = mention
if (mention.node.get('rel') == 'su'
and mention.node.find('../node[@rel="predc"]') is not None):
node = mention.node.find('../node[@rel="predc"]')
predicatives[mention.sentno,
node.get('begin'), node.get('end')] = mention
if mention.node.find(
"./node[@cat='rel']/node[@vwtype='betr']") is not None:
node = mention.node.find(
"./node[@cat='rel']/node[@vwtype='betr']")
relpronouns[mention.sentno,
int(node.get('begin')), int(node.get('end'))
] = mention
if mention.node.get('vwtype') != 'refl':
# Check if this mention is an antecedent to a reflexive pronoun.
# Assume reflexive pronoun should be linked to closest
# candidate antecedent.
# det applies in genitive case: John in John's car.
node = None
if mention.node.getparent().get('rel') == 'su':
node = mention.node.find('../..//node[@vwtype="refl"]')
elif mention.node.get('rel') in ('su', 'det'):
node = mention.node.find('..//node[@vwtype="refl"]')
if node is not None:
reflpronouns[mention.sentno,
int(node.get('begin')), int(node.get('end'))
] = mention
if (mention.node.get('vwtype') != 'recip'
and mention.head.get('num') == 'pl'):
node = mention.node.find('..//node[@vwtype="recip"]')
if node is not None:
recippronouns[mention.sentno,
int(node.get('begin')), int(node.get('end'))
] = mention
if (mention.head.get('neclass') is not None
and len(mention.tokens) > 1):
# FIXME: detect and avoid ambiguous acronyms
# FIXME: prefer explicit cases: "Full NP (acronym)"
# De Partij van de Arbeid => PvdA
acronyms[''.join(token[0] for n, token in enumerate(mention.tokens)
if token.lower() not in STOPWORDS or n > 0)] = mention
# De Koninklijke Nederlandse Akademie van Wetenschappen => KNAW
acronyms[''.join(token[0] for token in mention.tokens
if token.lower() not in STOPWORDS)] = mention
# Pass 2: find mentions to link to collected antecedents