-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrun_preprocess.py
executable file
·178 lines (152 loc) · 5.5 KB
/
run_preprocess.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
#!/usr/bin/env python3
"""
File [ run_preprocess.py ]
Author [ Heng-Jui Chang (MIT CSAIL) ]
Synopsis [ Preprocesses corpus. ]
"""
import argparse
import json
import logging
import os
from os.path import getsize, join
from joblib import Parallel, delayed
from miniasr.preprocess.generate_vocab import (
generate_subword_vocab,
generate_word_char_vocab,
)
from miniasr.utils import base_args, logging_args
def parse_arguments():
"""Parses arguments from command line."""
parser = argparse.ArgumentParser("Corpus preprocessing.")
# General arguments
parser.add_argument("--corpus", "-c", type=str, help="Corpus name.")
parser.add_argument("--path", "-p", type=str, help="Path to corpus.")
parser.add_argument(
"--set", "-s", type=str, nargs="+", help="Which subsets to be processed."
)
parser.add_argument(
"--out", "-o", type=str, default="data/", help="Output directory."
)
# Vocabulary
parser.add_argument(
"--gen-vocab",
action="store_true",
help="Specify whether to generate vocabulary files.",
)
parser.add_argument(
"--source",
type=str,
default="text",
help="Source of text data in data_dict (key)",
)
parser.add_argument(
"--char-vocab-size", type=int, default=-1, help="Character vocabulary size."
)
parser.add_argument(
"--word-vocab-size", type=int, default=-1, help="Word vocabulary size."
)
parser.add_argument(
"--subword-vocab-size", type=int, default=-1, help="Subword vocabulary size."
)
# Subword units
parser.add_argument(
"--gen-subword",
action="store_true",
help="Specify whether to generate subword vocabulary.",
)
parser.add_argument(
"--subword-mode",
type=str,
default="unigram",
choices=["unigram", "bpe"],
help="Subword training mode.",
)
parser.add_argument(
"--char-coverage", type=float, default=1.0, help="Character coverage."
)
# Add basic arguments
parser = base_args(parser)
# Parse arguments
args = parser.parse_args()
logging_args(args)
return args
def main():
"""Main function of preprocessing"""
args = parse_arguments()
if args.corpus == "LibriSpeech":
from miniasr.preprocess.librispeech import find_data
if args.corpus == "TIMIT":
from miniasr.preprocess.timit import find_data
else:
# You may add new methods here.
raise NotImplementedError(f"Unknown corpus {args.corpus}.")
logging.info(f"Preprocessing {args.corpus} corpus.")
logging.info(f"Subsets = {args.set}")
os.makedirs(args.out, exist_ok=True)
logging.info(f"Results will be saved to {args.out}")
# Find all data
logging.info(f"Reading data from {args.path}")
data_dict_list = [find_data(args.path, s) for s in args.set]
data_dict, data_list = {}, []
for d in data_dict_list:
data_dict = {**data_dict, **d}
data_list += [v for k, v in d.items()]
logging.info(f"Found {len(data_list)} audio files.")
# Save dictionary of data
json_path = join(args.out, "data_dict.json")
logging.info(f"Saving unsorted data dict to {json_path}")
with open(json_path, "w") as fp:
json.dump(data_dict, fp, indent=4, ensure_ascii=False)
# Sort data by audio file length
logging.info("Sorting data by audio file length.")
file_len = Parallel(n_jobs=args.njobs)(
delayed(getsize)(d["file"]) for d in data_list
)
logging.info(f"Total audio size = {sum(file_len)} Bytes")
data_list = [
d
for d, l in sorted(zip(data_list, file_len), reverse=True, key=lambda x: x[1])
if l > 0 and len(d.get(args.source, "dummy")) > 0
]
# Save sorted data list
json_path = join(args.out, "data_list_sorted.json")
logging.info(f"Saving sorted data list to {json_path}")
with open(json_path, "w") as fp:
json.dump(data_list, fp, indent=4, ensure_ascii=False)
# Generate pure text file for LM training
if data_list[0].get(args.source, None):
logging.info("Generating LM file.")
text_list = [d[args.source] for d in data_list]
text_path = join(args.out, "text.txt")
with open(text_path, "w") as fp:
fp.write("\n".join(text_list))
# Generate vocabulary files.
if args.gen_vocab:
logging.info("Generating vocabularies.")
if args.char_vocab_size > 0:
logging.info("Generating characters.")
generate_word_char_vocab(
text_list,
join(args.out, "vocab_char.txt"),
args.char_vocab_size,
"char",
)
if args.word_vocab_size > 0:
logging.info("Generating words.")
generate_word_char_vocab(
text_list,
join(args.out, "vocab_word.txt"),
args.word_vocab_size,
"word",
)
if args.gen_subword and args.subword_vocab_size > 0:
logging.info("Generating subwords.")
generate_subword_vocab(
text_path,
join(args.out, f"{args.subword_mode}_{args.subword_vocab_size}"),
vocab_size=args.subword_vocab_size,
model_type=args.subword_mode,
character_coverage=args.char_coverage,
)
if __name__ == "__main__":
main()