-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrees.py
executable file
·598 lines (569 loc) · 22.1 KB
/
trees.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
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
#!/usr/bin/env python3
import sys, re
import category, rule
class Tree:
def __init__(self, text):
self.text = text
self.subtrees = []
self.word = None
def get_words(self):
if self.word is not None:
return [self.word]
words = []
for tree in self.subtrees:
words += tree.get_words()
return words
# switching back to PTB scheme
word_to_word_mapping = {
'{': '-LCB-',
'}': '-RCB-'
}
word_to_POS_mapping = {
'--': ':',
'-': ':',
';': ':',
':': ':',
'-LRB-': '-LRB-',
'-RRB-': '-RRB-',
'-LCB-': '-LRB-',
'-RCB-': '-RRB-',
'{': '-LRB-',
'}': '-RRB-',
'Wa': 'NNP'
}
def get_PTB_word(word):
global word_to_word_mapping
if word in word_to_word_mapping:
word = word_to_word_mapping[word]
return word
def get_PTB_label(label, word):
global word_to_POS_mapping
if word in word_to_POS_mapping:
label = word_to_POS_mapping[word]
return label
class CCG_Tree(Tree):
# Convert line of CCGBank to a tree. This is an example line:
# (<T S[dcl] 0 2> (<T S[dcl] 1 2> (<T NP 0 1> (<T N 1 2> (<L N/N NNP NNP Ms. N_254/N_254>) (<L N NNP NNP Haag N>) ) ) (<T S[dcl]\NP 0 2> (<L (S[dcl]\NP)/NP VBZ VBZ plays (S[dcl]\NP_241)/NP_242>) (<T NP 0 1> (<L N NNP NNP Elianti N>) ) ) ) (<L . . . . .>) )
# This expands to:
# (<T S[dcl] 0 2>
# (<T S[dcl] 1 2>
# (<T NP 0 1>
# (<T N 1 2>
# (<L N/N NNP NNP Ms. N_254/N_254>)
# (<L N NNP NNP Haag N>) ) )
# (<T S[dcl]\NP 0 2>
# (<L (S[dcl]\NP)/NP VBZ VBZ plays (S[dcl]\NP_241)/NP_242>)
# (<T NP 0 1>
# (<L N NNP NNP Elianti N>) ) ) )
# (<L . . . . .>) )
def __init__(self, text='', pos=0):
Tree.__init__(self, text)
self.label = ''
self.category = None
self.orig_category = None
self.pos = None
self.word = None
self.head = None
self.rule = None
if text == '':
return
if '<L' in text:
depth = 0
for i in range(pos + 1, len(text)):
char = text[i]
# update the depth (note that brackets in categories only muck things up
# for the category that is the root of this subtree)
if char == '(':
depth += 1
if self.label != '' and depth == 1:
self.subtrees.append(CCG_Tree(text, i))
elif char == ')':
depth -= 1
# we've reached the end of the category that is the root of this subtree
if char == '>' and self.label == '':
self.label = text[pos + 2:i]
# we've reached the end of the scope for this bracket
if depth < 0:
break
parts = self.label.split()
self.category = ''.join(parts[1].split('[X]'))
self.orig_category = self.category
# Fix a sentence with two broken categories in CCGBank (0595.15)
if self.category[-1] in '\\/':
self.category = self.category + 'NP'
self.rule = rule.determine_combinator(self.subtrees, self.category)
if 'conj' in self.rule:
if not self.category.endswith('[conj]') and not category.compare(self.category, self.subtrees[1].category):
if self.subtrees[1].category.endswith('[conj]'):
self.category = self.subtrees[1].category
else:
self.category = self.subtrees[1].category + '[conj]'
if len(parts) == 4:
if len(self.subtrees) > 0:
self.head = self.subtrees[0]
if parts[2] == '1' and len(self.subtrees) == 2:
self.head = self.subtrees[1]
elif len(parts) == 6:
self.pos = parts[3]
self.word = parts[4]
else:
# Handle fowler input
self.label = text[pos:].split()[0][1:]
self.category = ')'.join('('.join(self.label.split('{')).split('}'))
self.orig_category = self.category
depth = 0
for i in range(pos + 1, len(text)):
if depth < 0:
break
char = text[i]
# update the depth
if char == '(':
depth += 1
if depth == 1:
self.subtrees.append(CCG_Tree(text, i))
elif char == ')':
depth -= 1
if len(self.subtrees) == 0:
pos = i
for j in range(i, 0, -1):
if text[j] == ' ':
pos = j
break
self.word = text[pos + 1:i]
break
self.rule = rule.determine_combinator(self.subtrees, self.category)
if 'conj' in self.rule:
if not self.category.endswith('[conj]') and not category.compare(self.category, self.subtrees[1].category):
if self.subtrees[1].category.endswith('[conj]'):
self.category = self.subtrees[1].category
else:
self.category = self.subtrees[1].category + '[conj]'
if self.word is not None:
self.pos = "UNK"
if self.word == '.':
self.pos = '.'
if self.word == ',':
self.pos = ','
if self.word == '...':
self.pos = ':'
if self.word == '?':
self.pos = '.'
if self.word == '!':
self.pos = '.'
def get_node(self, span, pos=None, min_enclosing=False):
return_ans_only = False
if pos is None:
pos = 0
return_ans_only = True
start = pos
ans = None
if self.word is not None:
labels_to_ignore = set(["-NONE-","TOP"])
words_to_ignore = set(["'","`","''","``",".","--",":",";","-",",","..."])
if self.word not in words_to_ignore and self.label not in labels_to_ignore:
pos += 1
else:
for subtree in self.subtrees:
pos, sub_ans = subtree.get_node(span, pos, min_enclosing)
if sub_ans is not None:
ans = sub_ans
end = pos
if min_enclosing:
if ans is None and start <= span[0] and end >= span[1]:
ans = self
else:
if start == span[0] and end == span[1]:
ans = self
if return_ans_only:
return ans
else:
return end, ans
def contains_rule(self, text):
if text in self.rule:
return True
for subtree in self.subtrees:
if subtree.contains_rule(text):
return True
return False
def all_word_yield(self, span=None, pos=0):
if self.word is not None:
if span is None or span[0] <= pos < span[1]:
return (pos + 1, self.word)
else:
return (pos + 1, '')
else:
text = []
for subtree in self.subtrees:
pos, words = subtree.all_word_yield(span, pos)
if words != '':
text.append(words)
return (pos, ' '.join(text))
def __repr__(self, depth=0):
ans = '\n' + depth * '\t'
ans += '('
if self.category is None:
ans += 'EMPTY EMPTY)'
return ans
if self.rule is not None:
ans += self.rule + ' '
ans += self.category
if self.pos is not None:
pos = get_PTB_label(self.pos, self.word)
ans += ' ' + pos
if self.word is not None:
ans += ' ' + get_PTB_word(self.word)
for subtree in self.subtrees:
ans += subtree.__repr__(depth + 1)
ans += ')'
return ans
class PTB_Tree(Tree):
# Convert text from the PTB to a tree. For example:
# ( (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))
# This is a compressed form of:
# ( (S
# (NP-SBJ (NNP Ms.) (NNP Haag) )
# (VP (VBZ plays)
# (NP (NNP Elianti) ))
# (. .) ))
def __init__(self, text='', pos=0):
Tree.__init__(self, text)
self.label = ''
self.pos = None
depth = 0
for i in range(pos + 1, len(text)):
char = text[i]
# update the depth
if char == '(':
depth += 1
if depth == 1:
self.subtrees.append(PTB_Tree(text, i))
elif char == ')':
depth -= 1
if len(self.subtrees) == 0:
pos = i
for j in range(i, 0, -1):
if text[j] == ' ':
pos = j
break
self.word = text[pos + 1:i]
# we've reached the end of the category that is the root of this subtree
if depth == 0 and char == ' ' and self.label == '':
self.label = text[pos + 1:i]
# we've reached the end of the scope for this bracket
if depth < 0:
break
if self.word is not None:
self.pos = self.label
def word_yield(self, span=None, pos=0):
labels_to_ignore = set([",", "-NONE-", "TOP", ":", "."])
words_to_ignore = set(["'","`","''","``"])
# ignore quotes as they won't always be present
if self.label in labels_to_ignore:
return (pos, '')
if self.word is not None:
if self.word in words_to_ignore:
return (pos, '')
if span is None or span[0] <= pos < span[1]:
return (pos + 1, self.word)
else:
return (pos + 1, '')
else:
text = []
for subtree in self.subtrees:
pos, words = subtree.word_yield(span, pos)
if words != '':
text.append(words)
return (pos, ' '.join(text))
def __repr__(self, depth=0):
ans = ''
if depth > 0:
ans += '\n'
ans += depth * '\t'
ans += '(' + get_PTB_label(self.label, self.word)
if self.word is not None:
ans += ' ' + get_PTB_word(self.word)
for subtree in self.subtrees:
ans += subtree.__repr__(depth + 1)
ans += ')'
return ans
def one_line_repr(self):
ans = '(' + get_PTB_label(self.label, self.word)
if self.word is not None:
return ans + ' ' + get_PTB_word(self.word) + ')'
for subtree in self.subtrees:
ans += ' ' + subtree.one_line_repr()
ans += ')'
return ans
def repr_with_corrections(self, gold_spans, depth=0, pos=0,parent=None):
return_str = False
if type(gold_spans) != type({}):
return_str = True
span_dict = {}
gold_spans.get_spans(span_dict)
gold_spans = span_dict
# note - does not print missing spans that cover parts of present spans
start_missing = "\033[01;36m"
start_extra = "\033[01;31m"
start_wrong_label = "\033[01;33m"
end_colour = "\033[00m"
start = ''
if depth > 0:
start += '\n'
start += depth * '\t'
# Handle the POS-word case
labels_to_ignore = set(["-NONE-", "TOP", ":", "."])
words_to_ignore = set(["'","`","''", "``", "--",":",";","-",","])
if self.word is not None:
text = ''
if self.label not in labels_to_ignore and (self.word is None or self.word not in words_to_ignore):
if self.label not in gold_spans[(pos, pos+1)] and self.word not in gold_spans[(pos, pos+1)]:
text = '%s(%s%s %s%s)' % (start, start_extra, self.label, self.word, end_colour)
text += ' BROKEN WORD'
elif len(gold_spans[(pos, pos+1)]) > 1 and parent is not None and len(parent.subtrees) > 1:
punc_count = 0
for subtree in parent.subtrees:
if subtree.label in labels_to_ignore:
punc_count += 1
if punc_count != len(parent.subtrees) - 1:
to_cover = gold_spans[(pos, pos+1)]
covered = set()
covered.add(self.word)
missed = to_cover.difference(covered)
text = '%s%s(%s%s' % (start, start_missing, ' '.join(missed), end_colour)
text += '%s(%s %s)' % (start + '\t', self.label, self.word)
text += '%s)%s' % (start_missing, end_colour)
pos += 1
if text == '':
text = '%s(%s %s)' % (start, self.label, self.word)
if return_str:
return text
else:
return (pos, text)
# Handle when constituents are present
init = pos
children = [(pos, '')]
for subtree in self.subtrees:
pos, text = subtree.repr_with_corrections(gold_spans, depth + 1, pos, self)
children.append((pos, text))
final = pos
text = start
extra = (init, final) not in gold_spans
wrong_label = False
if extra:
text += start_extra + '(' + self.label + end_colour
elif self.label not in gold_spans[(init, final)]:
if len(gold_spans[(init, final)]) == 1 and final - init == 1:
# actually an extra bracket, just confused by POS
text += start_extra + '(' + self.label + end_colour
extra = True
elif parent is not None and len(parent.subtrees) > 1:
# check if all but one subtree is punctuation
punc_count = 0
for subtree in parent.subtrees:
if subtree.label in labels_to_ignore:
punc_count += 1
if punc_count != len(parent.subtrees) - 1:
to_cover = gold_spans[(init, final)]
covered = set()
covered.add(self.label)
subtree = self
while len(subtree.subtrees) == 1:
subtree = subtree.subtrees[0]
covered.add(subtree.label)
covered.add(subtree.word)
missed = to_cover.difference(covered)
text += start_wrong_label + '(' + self.label + end_colour
wrong_label = True
text += ' ' + start_missing + '_'.join(missed) + end_colour
else:
text += start_wrong_label + '(' + self.label + end_colour
wrong_label = True
else:
text += start_wrong_label + '(' + self.label + end_colour
wrong_label = True
elif len(gold_spans[(init, final)]) > 1 and (parent is None or len(parent.subtrees) > 1):
# check if all but one subtree is punctuation
punc_count = 0
if parent is not None:
for subtree in parent.subtrees:
if subtree.label in labels_to_ignore:
punc_count += 1
if parent is None or punc_count != len(parent.subtrees) - 1:
# this is right, but there are other that should be here too
to_cover = gold_spans[(init, final)]
covered = set()
covered.add(self.label)
subtrees = self.subtrees
punc_count = 0
for subtree in subtrees:
if subtree.label in labels_to_ignore:
punc_count += 1
while len(subtrees) - punc_count == 1:
cur = subtrees[0]
for subtree in subtrees:
if subtree.label not in labels_to_ignore:
cur = subtree
break
covered.add(cur.label)
subtrees = cur.subtrees
if len(subtrees) == 0:
covered.add(cur.word)
punc_count = 0
for subtree in subtrees:
if subtree.label in labels_to_ignore:
punc_count += 1
missed = to_cover.difference(covered)
text += '(' + self.label
if len(missed) > 0:
text += ' ' + start_missing + '_'.join(missed) + end_colour
else:
text += '(' + self.label
else:
# it's correct
text += '(' + self.label
# now consider groupings of the children
for length in range(2, len(children) - 1):
for i in range(len(children)):
if i + length >= len(children):
continue
if children[i][0] == children[i+1][0]:
continue
if children[i+length][0] == children[i + length-1][0]:
continue
if length == len(children) - 2 and i == 1 and children[0][0] == children[1][0]:
continue
if length == len(children) - 2 and i == 0 and children[-1][0] == children[-2][0]:
continue
if (children[i][0], children[i + length][0]) in gold_spans:
# this is a missing span
# 1 - indent
for k in range(i+1, i+length+1):
cpos, ctext = children[k]
ctext = '\n\t'.join(ctext.split('\n'))
children[k] = (cpos, ctext)
# 2 - add open bracket and label(s) to first entry
cpos, ctext = children[i+1]
pretext = '\n'
pretext += (depth + 1) * '\t' + start_missing + '('
pretext += '/'.join(gold_spans[(children[i][0], children[i + length][0])])
pretext += end_colour
children[i+1] = (cpos, pretext + ctext)
# 3 - add end bracket to last entry
cpos, ctext = children[i+length]
ctext += start_missing + ')' + end_colour
children[i+length] = (cpos, ctext)
for child in children:
text += child[1]
if extra:
text += start_extra + ')' + end_colour
elif wrong_label:
text += start_wrong_label + ')' + end_colour
else:
text += ')'
if return_str:
return text
else:
return (final, text)
def get_spans(self, span_dict, pos=0):
labels_to_ignore = set(["-NONE-", "TOP", ":", "."])
words_to_ignore = set(["'","`","''", "``", "--",":",";","-",",","."])
label = self.label
# ignore quotes as they won't always be present
if label in labels_to_ignore or self.word in words_to_ignore:
return pos
init = pos
if len(self.subtrees) == 0:
pos += 1
else:
for subtree in self.subtrees:
pos = subtree.get_spans(span_dict, pos)
if init != pos:
if (init, pos) not in span_dict:
span_dict[(init, pos)] = set()
if not label[0] == '-':
label = label.split('-')[0]
label = label.split('=')[0]
if label == 'PRT':
label = 'ADVP' # another collins change
if self.word is not None:
label = self.word
span_dict[(init, pos)].add(label)
return pos
def read_PTB_tree(source):
cur_text = ''
depth = 0
while True:
line = source.readline()
if line == '':
return None
line = line.strip()
if line == '':
continue
if cur_text != '':
cur_text += ' '
cur_text += line
for char in line:
if char == '(':
depth += 1
elif char == ')':
depth -= 1
if depth == 0:
return PTB_Tree(cur_text)
return trees
def read_PTB_trees(source, max_sents=-1):
if type(source) == type(''):
source = open(source)
trees = []
while True:
tree = read_PTB_tree(source)
if tree is None:
break
trees.append(tree)
if len(trees) >= max_sents > 0:
break
return trees
def read_CCG_tree(source):
while True:
line = source.readline()
if line == '':
return None
else:
line = line.strip()
if line != '' and not line.startswith("ID"):
line = '-LRB- -LCB-'.join(line.split('LRB {'))
line = '-RRB- -RCB-'.join(line.split('RRB }'))
line = '-LRB- -LRB-'.join(line.split('LRB ('))
line = '-RRB- -RRB-'.join(line.split('RRB )'))
tree = None
if '<L' in line:
tree = CCG_Tree(line)
else:
tree = CCG_Tree(line.strip()[1:-1].strip())
if len(tree.subtrees) == 0 and tree.word is None:
tree.category = None
return tree
def read_CCG_trees(source, max_sents=-1):
if type(source) == type(''):
source = open(source)
trees = []
while True:
tree = read_CCG_tree(source)
if tree is None:
break
trees.append(tree)
if len(trees) >= max_sents > 0:
break
return trees
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage:\n%s [PTB,CCG] <filename>" % sys.argv[0])
sys.exit(1)
filename = sys.argv[2]
trees = None
if sys.argv[1] == 'PTB':
trees = read_PTB_trees(filename)
elif sys.argv[1] == 'CCG':
trees = read_CCG_trees(filename)
print(len(trees), "trees read")
for tree in trees:
print(tree)