forked from interactive-cookbook/tagger-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_to_conll.py
321 lines (287 loc) · 11 KB
/
json_to_conll.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
# Original Author: Theresa Schmidt, 2021 <[email protected]>
# Revised: Siyu Tao, 2022
# Last Edit: 2022/07/06
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Creates CoNLL-U formatted tsv files from our tagger's or parser's output files.
1. tagger prediction2conllu: takes a tagging prediction file (json format) and
writes a CoNLL-U file with the given columns.
2. parser prediction2conllu: takes a parsing prediction file (json format) and
writes a CoNLL-U file with the given columns.
Tested with Python 3.7
References:
- Lin et al. (2020).
A recipe for creating multimodal aligned datasets for sequential tasks.
In Proceedings of the58th Annual Meeting of the Association for Computational Linguistics, pages 4871–4884, Online.
Association for Computational Linguistics.
- CoNLL-U: https://universaldependencies.org/format.html
"""
import argparse
import json
from ast import literal_eval
import logging
def read_prediction_tokens(pred_file):
"""
Reads in the tokens from the tagger's output file.
Returns: a String list
"""
tokens = []
with open(pred_file, encoding="utf-8") as f:
for line in f:
j = json.loads(line)
tokens.extend(j["words"])
return tokens
def read_prediction_tags(pred_file):
"""
Reads in the predicted tags from the tagger's output file. Or the
tags used as part of the input for the parser.
Also determines the source of the data, i.e. whether it was
generated by the tagger or the parser.
Returns: a String list with the predicted tags.
"""
model_type = None
tags = []
with open(pred_file, encoding="utf-8") as f:
for line in f:
j = json.loads(line)
try:
tags.extend(j["tags"])
model_type = "tagger"
except KeyError:
tags.extend(j["pos"])
model_type = "parser"
return tags, model_type
def read_prediction_dependencies(pred_file):
"""
Reads in the predictions from the parser's output file.
Returns: two String list with the predicted heads and dependency names, respectively.
"""
heads = []
deps = []
with open(pred_file, encoding="utf-8") as f:
for line in f:
j = json.loads(line)
heads.extend(j["predicted_heads"])
deps.extend(j["predicted_dependencies"])
heads = list(map(str, heads))
return heads, deps
def taggingcolumns2conllu(outfile, tokens, tags, pos_tags=None, filemode="w"):
"""
Takes tokens and tags and writes them into a tsv file in CoNLL-U format.
Domain-specific tags are required, POS tags are optional.
CoNLL-U columns: ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
All tokens are annotated with HEAD = 0 and DEPREL = root, so the parser's
dataset reader can read in the file without errors.
"""
# double-check input
if len(tokens) != len(tags):
raise ValueError(
"Will not zip tokens and tags: number of tokens in tokens and "
"number of tags in tags must be the same. Got ",
len(tokens),
"and",
len(tags),
)
# write file: one token per line
with open(outfile, filemode, encoding="utf-8") as o:
if pos_tags:
for (i, (_token, _pos, _tag)) in enumerate(zip(tokens, pos_tags, tags)):
# need to start counting from 1 bc 0 is used for None-node
o.write(
str(i + 1)
+ "\t"
+ _token
+ "\t_\t"
+ _pos
+ "\t"
+ _tag
+ "\t_\t0\troot\t_\t_"
)
o.write("\n")
o.write("\n")
else:
for (i, (_token, _tag)) in enumerate(zip(tokens, tags)):
# need to start counting from 1 bc 0 is used for None-node
o.write(
str(i + 1)
+ "\t"
+ _token
+ "\t_\t_\t"
+ _tag
+ "\t_\t0\troot\t_\t_"
)
o.write("\n")
o.write("\n")
def parsercolumns2conllu(outfile, tokens, tags, heads, deps, pos_tags=None, filemode="w"):
"""
Takes tokens, tags and dependency relations and writes them into a tsv file in CoNLL-U format.
Domain-specific tags are required, POS tags are optional.
CoNLL-U columns: ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
"""
# double-check input
if len(tokens) != len(tags):
raise ValueError(
f"Will not zip tokens, tags, heads and deps: number of tokens "
f"in tokens and number of tags in tags must be the same. "
f"Got {len(tokens)}, {len(tags)}, {len(heads)} and {len(deps)}."
)
# write file: one token per line
with open(outfile, filemode, encoding="utf-8") as o:
if pos_tags:
for (i, (_token, _pos, _tag, _head, _dep)) in enumerate(
zip(tokens, pos_tags, tags, heads, deps)
):
# need to start counting from 1 bc 0 is used for None-node
o.write(
str(i + 1)
+ "\t"
+ _token
+ "\t_\t"
+ _pos
+ "\t"
+ _tag
+ "\t_\t"
+ _head
+ "\t"
+ _dep
+ "\t_\t_"
)
o.write("\n")
else:
for (i, (_token, _tag, _head, _dep)) in enumerate(
zip(tokens, tags, heads, deps)
):
# need to start counting from 1 bc 0 is used for None-node
o.write(
str(i + 1)
+ "\t"
+ _token
+ "\t_\t_\t"
+ _tag
+ "\t_\t"
+ _head
+ "\t"
+ _dep
+ "\t_\t_"
)
o.write("\n")
o.write("\n")
def execute_tagger2c(args):
"""
Takes a prediction file generated by our tagger (i.e. json file) and writes a tsv file in CoNLL-U format.
CoNLL-U columns: ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
Realised columns (all other columns contain dummy values): ID FORM _ (UPOS) XPOS _ _ _ _ _
"""
if args.multi_mode:
lineflag = False
with open(args.pred_file, encoding="utf-8") as f:
for line in f:
lineflag = True
j = json.loads(line)
tokens = j["words"]
tags = j["tags"]
taggingcolumns2conllu(args.out, tokens, tags, filemode="a")
if not lineflag:
raise IOError(
"Empty file"
) # Due to formatting and other errors in Lin et al. (2020)'s data,
# some recipes do not contain text, leaving us with empty files.
# Empty files could cause further errors; therefore, we want to delete them from the dataset.
else:
tokens = read_prediction_tokens(args.pred_file)
tags, _ = read_prediction_tags(args.pred_file)
taggingcolumns2conllu(args.out, tokens, tags)
def execute_parse2c(args):
"""
Takes a prediction file generated by our parser (i.e. json file) and writes a tsv file in CoNLL-U format.
CoNLL-U columns: ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
Realised columns (all other columns contain dummy values): ID FORM _ (UPOS) XPOS _ HEAD DEPREL DEPS _
"""
if args.multi_mode:
# WIP - not yet tested
lineflag = False
with open(args.pred_file, encoding="utf-8") as f:
for line in f:
lineflag = True
j = json.loads(line)
tokens = j["words"]
tags = j["pos"]
heads = j["predicted_heads"]
heads = list(map(str, heads))
deps = j["predicted_dependencies"]
parsercolumns2conllu(args.out, tokens, tags, heads, deps, filemode="a")
if not lineflag:
raise IOError(
"Empty file"
) # we want to detect and subsequently delete empty files from the dataset.
else:
tokens = read_prediction_tokens(args.pred_file)
tags, _ = read_prediction_tags(args.pred_file)
heads, deps = read_prediction_dependencies(args.pred_file)
parsercolumns2conllu(args.out, tokens, tags, heads, deps)
if __name__ == "__main__":
# parser for command line arguments
arg_parser = argparse.ArgumentParser(
description="""Select whether it is tagger or parser output that will be converted to CoNLL-U format.\n
1. tagger json2conllu: takes a tagger prediction file (json format) and writes a
CoNLL-U file with the given columns.\n
2. parser json2conllu: takes a parser prediction file (json format) and writes a
CoNLL-U file with the given columns."""
)
arg_parser.add_argument(
"-m",
"--mode",
dest="mode",
choices=['tagger', 'parser'],
required=True,
help="""Specify mode as described above. Choose one of the following: {tagger, parser}.""",
)
arg_parser.add_argument(
"-p",
"--prediction",
metavar="PRED_FILE",
dest="pred_file",
required=True,
help="""Prediction file in json format. Output of AllenNLP tagger or parser.""",
)
arg_parser.add_argument(
"-o",
"--output_file",
dest="out",
metavar="OUTPUT_FILE",
help="""Path of the output file. Default is <prediction_file>.conllu if not specified""",
)
arg_parser.add_argument(
"--multi",
dest="multi_mode",
const=True,
default=False,
action="store_const",
help="""When specified, read multiple recipes in one document.""",
)
args = arg_parser.parse_args()
args.debug = False
# default output file name
if args.out == None:
args.out = str(args.pred_file)[:-4] + "conllu"
#########################
#### Start execution ####
#########################
if args.mode == "tagger":
execute_tagger2c(args)
elif args.mode == "parser":
execute_parse2c(args)
else:
raise RuntimeError(
"Unexpected mode. Valid options are {tagger, parser}."
)