forked from PaddlePaddle/PaddleNLP
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoccano.py
More file actions
Latest commit
171 lines (149 loc) Β· 7.12 KB
/
Copy pathdoccano.py
File metadata and controls
171 lines (149 loc) Β· 7.12 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
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
importargparse
importjson
importos
importrandom
importtime
fromdecimalimportDecimal
importnumpyasnp
importpaddle
fromtqdmimporttqdm
frompaddlenlp.utils.logimportlogger
# yapf: disable
parser=argparse.ArgumentParser()
parser.add_argument("--doccano_file", default="doccano.jsonl", type=str, help="The doccano file exported from doccano platform.")
parser.add_argument("--save_dir", default="./data", type=str, help="The path of data that you wanna save.")
parser.add_argument("--splits", default=[0.8, 0.2], type=float, nargs="*", help="The ratio of samples in datasets. [0.8, 0.2] means 80% samples used for training, 20% for evaluation.")
parser.add_argument("--task_type", choices=['multi_class', 'multi_label', 'hierarchical'], default="multi_label", type=str, help="Select task type, multi_class for multi classification task, multi_label for multi label classification task and hierarchical for hierarchical classification, defaults to multi_label.")
parser.add_argument("--is_shuffle", default=True, type=bool, help="Whether to shuffle the labeled dataset, defaults to True.")
parser.add_argument("--seed", type=int, default=3, help="Random seed for initialization")
parser.add_argument("--separator", type=str, default="##", help="Separator for hierarchical classification")
parser.add_argument("--valid", action='store_true', help="Whether annotate valid data(extracted from sparse strategy)")
parser.add_argument("--dirty", action='store_true', help="Whether annotate dirty data(extracted from dirty data cleaning strategy)")
args=parser.parse_args()
# yapf: enable
defset_seed(seed):
"""
Set random seed
"""
paddle.seed(seed)
random.seed(seed)
np.random.seed(seed)
defdo_convert():
"""
Convert doccano jsonl to fixed format
"""
set_seed(args.seed)
tic_time=time.time()
ifnotos.path.exists(args.doccano_file):
raiseValueError("Please input the correct path of doccano file.")
ifnotos.path.exists(args.save_dir):
os.makedirs(args.save_dir)
iflen(args.splits) !=1andlen(args.splits) !=2andlen(args.splits) !=3:
raiseValueError("Only len(splits)==1 /len(splits)==2 / len(splits)==3 accepted for splits.")
def_check_sum(splits):
iflen(splits) ==2:
returnDecimal(str(splits[0])) +Decimal(str(splits[1])) ==Decimal("1")
iflen(splits) ==3:
returnDecimal(str(splits[0])) +Decimal(str(splits[1])) +Decimal(str(splits[2])) ==Decimal("1")
ifnot_check_sum(args.splits):
raiseValueError("Please set correct splits, sum of elements in splits should be equal to 1.")
withopen(args.doccano_file, "r", encoding="utf-8") asf:
raw_examples=f.readlines()
f.close()
examples= []
label_list= []
withtqdm(total=len(raw_examples)):
forlineinraw_examples:
items=json.loads(line)
# Compatible with doccano >= 1.6.2
if"data"initems.keys():
text, labels=items["data"], items["label"]
else:
text, labels=items["text"], items["label"]
labels=list(set(labels))
forlinlabels:
if","inl:
raiseValueError("There exists comma ',' in {}".format(l))
ifargs.task_type=="multi_label"orargs.task_type=="multi_class":
ifargs.dirty:
text=" ".join(text.strip().split("\t")[:-1])
else:
text=" ".join(text.strip().split("\t"))
example=text+"\t"+",".join(labels) +"\n"
forlinlabels:
iflnotinlabel_list:
label_list.append(l)
ifargs.task_type=="hierarchical":
label_dict= []
forlabelinlabels:
level_labels=label.split(args.separator)
foriinrange(len(level_labels)):
l=args.separator.join(level_labels[: i+1])
iflnotinlabel_dict:
label_dict.append(l)
iflnotinlabel_list:
label_list.append(l)
ifargs.dirty:
text=" ".join(text.strip().split("\t")[:-1])
else:
text=" ".join(text.strip().split("\t"))
example=text+"\t"+",".join(label_dict) +"\n"
examples.append(example)
ifnotargs.dirtyandnotargs.valid:
save_path=os.path.join(args.save_dir, "label.txt")
withopen(save_path, "w", encoding="utf-8") asf:
label_list=sorted(label_list)
forlinlabel_list:
f.write(l+"\n")
def_save_examples(save_dir, file_name, examples, is_data=False):
count=0
save_path=os.path.join(save_dir, file_name)
withopen(save_path, "w", encoding="utf-8") asf:
forexampleinexamples:
ifis_data:
f.write(example.split("\t")[0] +"\n")
else:
f.write(example)
count+=1
logger.info("Save %d examples to %s."% (count, save_path))
ifargs.is_shuffle:
indexes=np.random.permutation(len(raw_examples))
raw_examples= [raw_examples[i] foriinindexes]
iflen(args.splits) ==1:
ifargs.valid:
_save_examples(args.save_dir, "valid.txt", examples)
elifargs.dirty:
_save_examples(args.save_dir, "train_dirty.txt", examples)
else:
_save_examples(args.save_dir, "train.txt", examples)
_save_examples(args.save_dir, "data.txt", examples, True)
eliflen(args.splits) ==2:
i1, _=args.splits
p1=int(len(raw_examples) *i1)
_save_examples(args.save_dir, "train.txt", examples[:p1])
_save_examples(args.save_dir, "dev.txt", examples[p1:])
_save_examples(args.save_dir, "data.txt", examples[p1:], True)
eliflen(args.splits) ==3:
i1, i2, _=args.splits
p1=int(len(raw_examples) *i1)
p2=int(len(raw_examples) * (i1+i2))
_save_examples(args.save_dir, "train.txt", examples[:p1])
_save_examples(args.save_dir, "dev.txt", examples[p1:p2])
_save_examples(args.save_dir, "test.txt", examples[p2:])
_save_examples(args.save_dir, "data.txt", examples[p2:], True)
logger.info("Finished! It takes %.2f seconds"% (time.time() -tic_time))
if__name__=="__main__":
do_convert()