-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_phoneme_recognition.py
169 lines (150 loc) · 4.88 KB
/
test_phoneme_recognition.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
####################################################################################################
#
# Test the phoneme recognizer with acoustic or articulatory features
#
####################################################################################################
import argparse
import logging
import os
import shutil
import tempfile
import torch
import torch.nn as nn
import yaml
import ujson
from functools import partial
from torch.utils.data import DataLoader
from torchaudio.models.decoder import ctc_decoder
from helpers import set_seeds, sequences_from_dict
from phoneme_recognition import (
run_test,
Criterion,
Feature,
Target,
)
from phoneme_recognition.datasets import PhonemeRecognitionDataset, collate_fn
from phoneme_recognition.decoders import TopKDecoder
from phoneme_recognition.deepspeech2 import DeepSpeech2
from phoneme_recognition.metrics import EditDistance, WordInfoLost, Accuracy, AUROC
from phoneme_recognition.synthetic_shapes import SyntheticPhonemeRecognitionDataset
from settings import (
BASE_DIR,
SIL,
BLANK,
UNKNOWN
)
TMPFILES = os.path.join(BASE_DIR, "tmp")
TMP_DIR = tempfile.mkdtemp(dir=TMPFILES)
RESULTS_DIR = os.path.join(TMP_DIR, "results")
if not os.path.exists(RESULTS_DIR):
os.makedirs(RESULTS_DIR)
def main(
database_name,
datadir,
batch_size,
seq_dict,
vocab_filepath,
pretrained,
feature,
loss,
model_params,
target,
state_dict_filepath,
plot_target=None,
voicing_filepath=None,
num_workers=0,
save_dir=None,
):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logging.info(f"Running on '{device.type}'")
feature = Feature(feature)
target = Target(target)
plot_target = Target(plot_target) if plot_target else target
criterion = Criterion[loss]
default_tokens = [BLANK, UNKNOWN] if criterion == Criterion.CTC else [UNKNOWN]
vocabulary = {token: i for i, token in enumerate(default_tokens)}
with open(vocab_filepath) as f:
tokens = ujson.load(f)
for i, token in enumerate(tokens, start=len(vocabulary)):
vocabulary[token] = i
if voicing_filepath is not None:
with open(voicing_filepath) as f:
voiced_tokens = ujson.load(f)
else:
voiced_tokens = None
tokens = [k for k, v in sorted(vocabulary.items(), key=lambda t: t[1])]
decoder_fn = ctc_decoder if criterion == Criterion.CTC else TopKDecoder
decoder = decoder_fn(
lexicon=None,
tokens=tokens,
sil_token=SIL,
blank_token=BLANK if criterion == Criterion.CTC else None,
unk_word=UNKNOWN,
)
if pretrained:
model = DeepSpeech2.load_librispeech_model(
model_params["num_features"],
adapter_out_features=model_params.get("adapter_out_features")
)
hidden_size = model_params["rnn_hidden_size"]
model.classifier = nn.Linear(hidden_size, len(vocabulary))
else:
model = DeepSpeech2(num_classes=len(vocabulary), **model_params)
state_dict = torch.load(state_dict_filepath, map_location=torch.device("cpu"))
model.load_state_dict(state_dict)
model.to(device)
print(f"""
DeepSpeech2 -- {model.total_parameters} parameters
""")
sequences = sequences_from_dict(datadir, seq_dict)
# dataset = SyntheticPhonemeRecognitionDataset(
dataset = PhonemeRecognitionDataset(
datadir=datadir,
database_name=database_name,
sequences=sequences,
vocabulary=vocabulary,
features=[feature],
tmp_dir=TMP_DIR,
voiced_tokens=voiced_tokens,
)
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
worker_init_fn=set_seeds,
collate_fn=partial(collate_fn, features_names=[feature]),
)
metrics = {
"edit_distance": EditDistance(decoder),
"word_info_lost": WordInfoLost(decoder),
# "accuracy": Accuracy(len(vocabulary)),
# "accuracy_per_class": Accuracy(len(vocabulary), average=None),
# "auroc": AUROC(len(vocabulary))
}
info_test = run_test(
model=model,
dataloader=dataloader,
fn_metrics=metrics,
decoder=decoder,
device=device,
feature=feature,
target=target,
plot_target=plot_target,
use_voicing=(voicing_filepath is not None),
save_dir=save_dir,
)
if save_dir is not None:
info_test_filepath = os.path.join(save_dir, "info_test.json")
with open(info_test_filepath, "w") as f:
ujson.dump(info_test, f)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--config", dest="config_filepath")
args = parser.parse_args()
with open(args.config_filepath) as f:
cfg = yaml.safe_load(f)
try:
main(**cfg)
finally:
shutil.rmtree(TMP_DIR)