-
Notifications
You must be signed in to change notification settings - Fork 1
/
conll_utils.py
404 lines (335 loc) · 13.3 KB
/
conll_utils.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
'''
A set of classes to handle input and output of CoNLL-U files
http://universaldependencies.org/docs/format.html
The Parsed* classes are useful to store extra properties needed during
the parsing process that are external to the Conll instances themselves
'''
import logging
import well_formed_filter
def encodeNoneAsUnderscore(s):
if s == None:
return '_'
else:
return s
def encodeNoneAsUnderscore_Int(i):
if i == None:
return '_'
else:
return str(i)
'''
Represents a CoNLL token and all its properties (except index)
'''
class ConllToken(object):
def __init__(self):
self.FORM = None
self.LEMMA = None
self.UPOSTAG = None
self.XPOSTAG = None
self.FEATS = []
'''
Make sure to subtract one from the HEAD value in the file
Root becomes -1
HEAD then becomes n, which refers to the n'th 0-based index entry
in the parent ConllSentence
Our parser also requires this to start at -1
'''
self.HEAD = None
self.DEPREL = None
self.DEPS = None
self.MISC = None
def __str__(self):
return self.toFileOutput('_')
def __repr__(self):
return self.__str__()
def toFileOutput(self, ID):
def checkTab(s):
assert '\t' not in s, 'field must not contain a tab: ' + s
return s
def checkPipe(s):
assert '|' not in s, 'field must not contain a pipe: ' + s
return s
assert self.FORM != None
assert type(self.FEATS) is list
cols = [str(ID),
checkTab(self.FORM),
checkTab(encodeNoneAsUnderscore(self.LEMMA)),
checkTab(encodeNoneAsUnderscore(self.UPOSTAG)),
checkTab(encodeNoneAsUnderscore(self.XPOSTAG)),
'|'.join(checkPipe(checkTab(f)) for f in self.FEATS),
encodeNoneAsUnderscore_Int(self.HEAD+1), # +1 when writing as file
checkTab(encodeNoneAsUnderscore(self.DEPREL)),
checkTab(encodeNoneAsUnderscore(self.DEPS)), # TODO
checkTab(encodeNoneAsUnderscore(self.MISC))]
return '\t'.join(cols)
'''
Represents a ConllToken, as parsed
'''
class ParsedConllToken(ConllToken):
def __init__(self):
super().__init__()
self.parsedLabel = None
self.parsedHead = None
self.HEAD = -1 # match default value in sentence.proto
def setParsedLabel(self, label):
self.parsedLabel = label
def setParsedHead(self, head):
self.parsedHead = head
def clearParsedHead(self):
self.parsedHead = -1 # match ParserState: always use -1 as <ROOT>
'''
Stores an ordered list of CoNLL tokens
'''
class ConllSentence(object):
def __init__(self):
self.tokens = []
'''
Convert to file output representation
'''
def toFileOutput(self):
return '\n'.join(self.tokens[ID-1].toFileOutput(ID) \
for ID in range(1, len(self.tokens)+1))
def genSyntaxNetJson(self, token, break_level=None, start_index=0):
break_contents = ''
if break_level:
break_contents = \
'''
break_level : %s''' % break_level
return \
'''token: {
word : "%s"
start : %d
end : %d
head : %d
tag : "%s"
category: "%s"
label : "%s"%s
}''' % (token.FORM, start_index, start_index+len(token.FORM)-1, token.HEAD, token.XPOSTAG, token.UPOSTAG, token.DEPREL, break_contents)
def genSyntaxNetTextHeader(self):
return 'text : "%s"' % (' '.join(t.FORM for t in self.tokens))
'''
Convert to SyntaxNet JSON format
'''
def toSyntaxNetJson(self):
out = []
start_index = 0
out.append(self.genSyntaxNetTextHeader())
for i in range(len(self.tokens)):
if i == 0:
out.append(self.genSyntaxNetJson(self.tokens[i], break_level='SENTENCE_BREAK', start_index=start_index))
else:
out.append(self.genSyntaxNetJson(self.tokens[i], start_index=start_index))
start_index += len(self.tokens[i].FORM) + 1 # assume space
return '\n'.join(out)
'''
Output the token separated by spaces
'''
def toSimpleRepresentation(self):
return ' '.join(t.FORM for t in self.tokens)
class ParsedConllSentence(ConllSentence):
def __init__(self, docid):
super().__init__()
self.docid_ = docid
def docid(self):
return self.docid_
## checked accessor
def mutableToken(self, i):
assert i >= 0
assert i < len(self.tokens)
return self.tokens[i]
def tokenSize(self):
return len(self.tokens)
'''
Stores an ordered list of sentences within a CoNLL file
keepMalformed:
Whether to retain non-projective and invalid examples
projectivize:
Whether to retain non-projective examples by projectivizing them
logStats:
Log statistics about the corpus
'''
class ConllFile(object):
def __init__(self, parsed=False, keepMalformed=False, projectivize=False,
logStats=False):
#self.sentenceIndex = None
self.sentences = []
# use parsed variant of structures
self.parsed = parsed
self.logger = logging.getLogger('ConllUtils')
self.keepMalformed = keepMalformed
self.projectivize = projectivize
self.logStats = logStats
'''
Read CoNLL-U from the given string
excludeCols: CoNLL column indices to exclude from reading
sometimes we just want to get rid of certain
attributes of a token
1-based index
'''
def read(self, s, excludeCols=[]):
assert 1 not in excludeCols, 'cannot exclude reading of ID'
assert 2 not in excludeCols, 'cannot exclude reading of FORM'
well_formed_inst = well_formed_filter.WellFormedFilter()
# arbitrary ID that can be used with parser
if self.parsed:
docid = 0
ln_num = 0
current_sentence = None
# if we encounter an error during processing a sentence
invalid_sentence = False
# set up iterator
# if there is no iterator, set one up
# if there was an iterator, leave it at its current position
#if self.sentenceIndex == None:
# self.sentenceIndex = len(self.sentences)
def commit(s):
# if we're even getting rid of malformed sentences in the first
# place...
if not self.keepMalformed:
if not well_formed_inst.isWellFormed(s,
projectivize=self.projectivize):
# if the sentence is non-projective and projectivize
# is enabled, the sentence will be fixed and not discarded
self.logger.debug('line %d: discarding malformed or non' \
'-projective sentence: "%s"' % \
(ln_num, s.toSimpleRepresentation()))
# as long as we discard the sentence here,
# discarded sentences' words, tags, and labels
# won't be added to the lexicon, which is exactly the
# behavior we want.
return
self.sentences.append(s)
def processUnderscore(s):
if s == '_':
return None
else:
return s
# token index (to check that it's in order)
current_ID = 0
lines = s.split('\n')
for ln in lines:
ln_num += 1
ln = ln.strip()
if not ln:
# a completely blank line indicates we need to commit the
# current sentence
if current_sentence != None:
if not invalid_sentence:
commit(current_sentence)
current_sentence = None
current_ID = 0
invalid_sentence = False
continue
if ln[0] == '#': # ignore comments completely
continue
if invalid_sentence: # don't process invalid sentences
continue
cols = [x.strip() for x in ln.split('\t')]
assert len(cols) >= 2, \
'line %d: must have at least ID and FORM: ' % ln_num + str(cols)
if '-' in cols[0] or '.' in cols[0]:
self.logger.warning('line %d: not implemented: ID=%s, ' \
'invalidating sentence' % (ln_num, cols[0]))
invalid_sentence = True
continue
else:
ID = int(cols[0])
assert ID==current_ID+1, 'line %d: token IDs must be in order' \
' and increment by one' % ln_num
current_ID = ID
if current_ID == 1:
if self.parsed:
current_sentence = ParsedConllSentence(docid)
docid += 1
else:
current_sentence = ConllSentence()
if self.parsed:
current_token = ParsedConllToken()
else:
current_token = ConllToken()
#if self.parsed:
# current_token.FORM = normalizeDigits(cols[1])
#else:
# current_token.FORM = cols[1]
# for SyntaxNet,
# normalization ONLY happens in lexicon builder
# yet numbers and up as <UNKNOWN> during training
# interesting...
# let this be underscore if needed (don't call processUnderscore())
current_token.FORM = cols[1]
if len(cols) > 2 and (3 not in excludeCols):
# let this be underscore if needed
# (don't call processUnderscore())
current_token.LEMMA = cols[2]
if len(cols) > 3 and (4 not in excludeCols):
current_token.UPOSTAG = processUnderscore(cols[3])
if len(cols) > 4 and (5 not in excludeCols):
current_token.XPOSTAG = processUnderscore(cols[4])
if len(cols) > 5 and (6 not in excludeCols):
if processUnderscore(cols[5]):
current_token.FEATS = \
[x.strip() for x in cols[5].split('|')]
else:
current_token.FEATS = []
if len(cols) > 6 and (7 not in excludeCols):
current_token.HEAD = processUnderscore(cols[6])
if current_token.HEAD != None:
if '-' in current_token.HEAD or '.' in current_token.HEAD:
self.logger.warning('line %d: not implemented: HEAD=%s,'
' invalidating sentence' % (ln_num, \
current_token.HEAD))
invalid_sentence = True
continue
else:
# it's important for parsing that HEAD start at -1
current_token.HEAD = int(current_token.HEAD)-1
if len(cols) > 7 and (8 not in excludeCols):
current_token.DEPREL = processUnderscore(cols[7])
if len(cols) > 8 and (9 not in excludeCols):
# TODO
current_token.DEPS = processUnderscore(cols[8])
if len(cols) > 9 and (10 not in excludeCols):
current_token.MISC = processUnderscore(cols[9])
current_sentence.tokens.append(current_token)
# an EOF indicates we need to commit the current sentence
if current_sentence != None:
if not invalid_sentence:
commit(current_sentence)
current_sentence = None
current_ID = 0
invalid_sentence = False
if self.logStats:
self.logger.info('Projectivized %d/%d non-projective sentences' \
' (%.2f%% of set)' % \
(well_formed_inst.projectivizedCount, \
well_formed_inst.nonProjectiveCount,
100.0 * float(well_formed_inst.projectivizedCount) \
/ float(len(self.sentences))
))
# if we're even getting rid of malformed sentences in the first place...
if not self.keepMalformed:
if self.projectivize:
# the definition of this variable changes when projectivize is on
self.logger.info('Discarded %d non-well-formed sentences' % \
(well_formed_inst.nonWellFormedCount))
else:
self.logger.info('Discarded %d non-well-formed and ' \
' non-projective sentences' % \
(well_formed_inst.nonWellFormedCount))
self.logger.info('%d valid sentences processed in total' % \
len(self.sentences))
'''
Write the current CoNLL-U data to the specified file descriptor
'''
def write(self, fd):
data = [s.toFileOutput() for s in self.sentences]
fd.write('\n\n'.join(data))
fd.flush()
def __iter__(self):
index = 0
while index < len(self.sentences):
yield self.sentences[index]
index += 1
class ParsedConllFile(ConllFile):
def __init__(self, keepMalformed=False, projectivize=False, logStats=False):
super().__init__(parsed=True, keepMalformed=keepMalformed,
projectivize=projectivize, logStats=logStats)