-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
233 lines (191 loc) · 7.23 KB
/
test.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
import argparse
import json
import os
from pathlib import Path
import torch
from tqdm import tqdm
import src.model as module_model
from src.trainer import Trainer
from src.utils import ROOT_PATH
from src.utils.object_loading import get_dataloaders
from src.utils.parse_config import ConfigParser
DEFAULT_CHECKPOINT_PATH = Path('defaul_test_model/checkpoint-epoch96.pth')
from pyctcdecode import build_ctcdecoder
from string import ascii_lowercase
import numpy as np
from src.metric.utils import calc_wer, calc_cer
import kenlm
import multiprocessing
def eval_results_and_update_lm_preds(results, text_encoder):
def get_wer(target, predicted):
wers = [calc_wer(target_text, pred_text) for target_text, pred_text in zip(target, predicted)]
return sum(wers) / len(wers)
def get_cer(target, predicted):
cers = [calc_cer(target_text, pred_text) for target_text, pred_text in zip(target, predicted)]
return sum(cers) / len(cers)
argmax_preds_list = [res['pred_text_argmax'] for res in results]
logits_list = [res['logits'] for i, res in enumerate(results)]
gt_text_list = [res['ground_truth_text'] for res in results]
LM_BEST_PARAMS = (0.9, 2.0)
LM_PATH = str(ROOT_PATH / 'lm/lowercase_3-gram.arpa')
print(LM_PATH)
BEAM_WIDTH = 300
EMPTY_TOK = "<pad>"
lm_alphabet = [EMPTY_TOK] + text_encoder.alphabet
decoder = build_ctcdecoder(
lm_alphabet,
kenlm_model_path = LM_PATH,
alpha=LM_BEST_PARAMS[0],
beta=LM_BEST_PARAMS[1]
)
with multiprocessing.get_context("fork").Pool() as pool:
lm_preds_list = decoder.decode_batch(pool, logits_list, beam_width=BEAM_WIDTH)
print('Argmax WER', get_wer(gt_text_list, argmax_preds_list))
print('Argmax CER', get_cer(gt_text_list, argmax_preds_list))
print('LM WER', get_wer(gt_text_list, lm_preds_list))
print('LM CER', get_cer(gt_text_list, lm_preds_list))
for i, lm_pred in enumerate(lm_preds_list):
results[i]['pred_text_lm'] = lm_pred
return results
def main(config, out_file):
logger = config.get_logger("test")
# define cpu or gpu if possible
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# text_encoder
text_encoder = config.get_text_encoder()
# setup data_loader instances
dataloaders = get_dataloaders(config, text_encoder)
# build model architecture
model = config.init_obj(config["arch"], module_model, n_class=len(text_encoder))
logger.info(model)
logger.info("Loading checkpoint: {} ...".format(config.resume))
checkpoint = torch.load(config.resume, map_location=device)
state_dict = checkpoint["state_dict"]
if config["n_gpu"] > 1:
model = torch.nn.DataParallel(model)
model.load_state_dict(state_dict)
# prepare model for testing
model = model.to(device)
model.eval()
results = []
with torch.no_grad():
for batch_num, batch in enumerate(tqdm(dataloaders["test"])):
batch = Trainer.move_batch_to_device(batch, device)
output = model(**batch)
if type(output) is dict:
batch.update(output)
else:
batch["logits"] = output
batch["log_probs"] = torch.log_softmax(batch["logits"], dim=-1)
batch["log_probs_length"] = model.transform_input_lengths(
batch["spectrogram_length"]
)
batch["probs"] = batch["log_probs"].exp().cpu()
batch["argmax"] = batch["probs"].argmax(-1)
log_probs = batch["log_probs"].cpu()
argmaxes = batch["argmax"].cpu()
for i in range(len(batch["text"])):
argmax = argmaxes[i][: int(batch["log_probs_length"][i])]
logits = log_probs[i][: int(batch["log_probs_length"][i])]
results.append(
{
"ground_truth_text": batch["text"][i],
"pred_text_argmax": text_encoder.ctc_decode(argmax.numpy()),
'logits': logits.numpy(),
'logits_length': batch["log_probs_length"]
}
)
results = eval_results_and_update_lm_preds(results, text_encoder)
save_keys_list = ['ground_truth_text', 'pred_text_argmax', 'pred_text_lm']
save_results = [res[key] for key in save_keys_list for res in results]
with Path(out_file).open("w") as f:
json.dump(save_results, f, indent=2)
if __name__ == "__main__":
args = argparse.ArgumentParser(description="PyTorch Template")
args.add_argument(
"-c",
"--config",
default=None,
type=str,
help="config file path (default: None)",
)
args.add_argument(
"-r",
"--resume",
default=str(DEFAULT_CHECKPOINT_PATH.absolute().resolve()),
type=str,
help="path to latest checkpoint (default: None)",
)
args.add_argument(
"-d",
"--device",
default=None,
type=str,
help="indices of GPUs to enable (default: all)",
)
args.add_argument(
"-o",
"--output",
default="output.json",
type=str,
help="File to write results (.json)",
)
args.add_argument(
"-t",
"--test-data-folder",
default=None,
type=str,
help="Path to dataset",
)
args.add_argument(
"-b",
"--batch-size",
default=20,
type=int,
help="Test dataset batch size",
)
args.add_argument(
"-j",
"--jobs",
default=1,
type=int,
help="Number of workers for test dataloader",
)
args = args.parse_args()
# set GPUs
if args.device is not None:
os.environ["CUDA_VISIBLE_DEVICES"] = args.device
# first, we need to obtain config with model parameters
# we assume it is located with checkpoint in the same folder
model_config = Path(args.resume).parent / "config.json"
with model_config.open() as f:
config = ConfigParser(json.load(f), resume=args.resume)
# update with addition configs from `args.config` if provided
if args.config is not None:
with Path(args.config).open() as f:
config.config.update(json.load(f))
# if `--test-data-folder` was provided, set it as a default test set
if args.test_data_folder is not None:
test_data_folder = Path(args.test_data_folder).absolute().resolve()
assert test_data_folder.exists()
config.config["data"] = {
"test": {
"batch_size": args.batch_size,
"num_workers": args.jobs,
"datasets": [
{
"type": "CustomDirAudioDataset",
"args": {
"audio_dir": str(test_data_folder / "audio"),
"transcription_dir": str(
test_data_folder / "transcriptions"
),
},
}
],
}
}
assert config.config.get("data", {}).get("test", None) is not None
config["data"]["test"]["batch_size"] = args.batch_size
config["data"]["test"]["n_jobs"] = args.jobs
main(config, args.output)