forked from nschmidtg/Podcastmix
-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_real.py
250 lines (222 loc) · 8.03 KB
/
test_real.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
import os
import random
import soundfile as sf
import torch
import yaml
import json
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from torch.utils.data.dataset import Dataset
import torchaudio
import sys
from utils.my_import import my_import
from asteroid.metrics import get_metrics
from pytorch_lightning import seed_everything
from asteroid.metrics import MockWERTracker
seed_everything(1)
class PodcastLoader(Dataset):
dataset_name = "PodcastMix"
def __init__(self, csv_dir, sample_rate=44100, segment=2):
self.csv_dir = csv_dir
self.segment = segment
self.sample_rate = sample_rate
self.mix_csv_path = os.path.join(self.csv_dir, 'metadata.csv')
self.df_mix = pd.read_csv(self.mix_csv_path, engine='python', delimiter=';')
torchaudio.set_audio_backend(backend='soundfile')
def __len__(self):
return len(self.df_mix)
def __getitem__(self, index):
row = self.df_mix.iloc[index]
podcast_path = row['mix_path']
speech_path = row['speech_path']
music_path = row['music_path']
sources_list = []
start_second = 1
mixture, _ = torchaudio.load(
podcast_path,
frame_offset=start_second * self.sample_rate,
num_frames=self.segment * self.sample_rate
)
speech, _ = torchaudio.load(
speech_path,
frame_offset=start_second * self.sample_rate,
num_frames=self.segment * self.sample_rate
)
music, _ = torchaudio.load(
music_path,
frame_offset=start_second * self.sample_rate,
num_frames=self.segment * self.sample_rate
)
sources_list.append(speech[0])
sources_list.append(music[0])
sources = np.vstack(sources_list)
sources = torch.from_numpy(sources)
return mixture[0], sources
parser = argparse.ArgumentParser()
parser.add_argument(
"--test_dir",
type=str,
required=True,
help="Test directory including the csv files"
)
parser.add_argument(
"--target_model",
type=str,
required=True,
help="Asteroid model to use"
)
parser.add_argument(
"--out_dir",
type=str,
default='ConvTasNet/eval/tmp',
required=True,
help="Directory where the eval results" " will be stored",
)
parser.add_argument(
"--use_gpu",
type=int,
default=0,
help="Whether to use the GPU for model execution"
)
parser.add_argument("--exp_dir",
default="exp/tmp",
help="Best serialized model path")
parser.add_argument(
"--n_save_ex",
type=int,
default=10,
help="Number of audio examples to save, -1 means all"
)
parser.add_argument(
"--compute_wer",
type=int,
default=0,
help="Compute WER using ESPNet's pretrained model"
)
COMPUTE_METRICS = ["si_sdr", "sdr", "sir", "sar", "stoi"]
def main(conf):
compute_metrics = COMPUTE_METRICS
wer_tracker = (
MockWERTracker()
)
model_path = os.path.join(conf["exp_dir"], "best_model.pth")
if conf["target_model"] == "UNet":
sys.path.append('UNet_model')
AsteroidModelModule = my_import("unet_model.UNet")
else:
sys.path.append('ConvTasNet_model')
AsteroidModelModule = my_import("conv_tasnet_norm.ConvTasNetNorm")
model = AsteroidModelModule.from_pretrained(model_path, sample_rate=conf["sample_rate"])
print("model_path", model_path)
# model = ConvTasNet
# Handle device placement
if conf["use_gpu"]:
model.cuda()
test_set = PodcastLoader(
conf["test_dir"],
sample_rate=44100,
segment=18
)
# Used to reorder sources only
# Randomly choose the indexes of sentences to save.
eval_save_dir = os.path.join(conf["exp_dir"], conf["out_dir"])
ex_save_dir = os.path.join(eval_save_dir, "examples/")
if conf["n_save_ex"] == -1:
conf["n_save_ex"] = len(test_set)
save_idx = random.sample(range(len(test_set)), conf["n_save_ex"])
series_list = []
torch.no_grad().__enter__()
for idx in tqdm(range(len(test_set))):
# Forward the network on the mixture.
mix, sources = test_set[idx]
if conf["target_model"] == "UNet":
mix = mix.unsqueeze(0)
# get audio representations, pass the mix to the unet, it will normalize
# it, create the masks, pass them to audio, unnormalize them and return
est_sources = model(mix)
mix_np = mix.cpu().data.numpy()
if conf["target_model"] == "UNet":
mix_np = mix_np.squeeze(0)
sources_np = sources.cpu().data.numpy()
est_sources_np = est_sources.squeeze(0).cpu().data.numpy()
# For each utterance, we get a dictionary with the mixture path,
# the input and output metrics
utt_metrics = get_metrics(
mix_np,
sources_np,
est_sources_np,
sample_rate=conf["sample_rate"],
metrics_list=COMPUTE_METRICS,
average=False
)
series_list.append(pd.Series(utt_metrics))
# Save some examples in a folder. Wav files and metrics as text.
if idx in save_idx:
local_save_dir = os.path.join(ex_save_dir, "ex_{}/".format(idx + 1))
os.makedirs(local_save_dir, exist_ok=True)
sf.write(
local_save_dir + "mixture.wav",
mix_np,
conf["sample_rate"]
)
# Loop over the sources and estimates
for src_idx, src in enumerate(sources_np):
sf.write(
local_save_dir + "s{}.wav".format(src_idx),
src,
conf["sample_rate"]
)
for src_idx, est_src in enumerate(est_sources_np):
est_src *= np.max(np.abs(mix_np)) / np.max(np.abs(est_src))
sf.write(
local_save_dir + "s{}_estimate.wav".format(src_idx),
est_src,
conf["sample_rate"],
)
# Write local metrics to the example folder.
with open(local_save_dir + "metrics.json", "w") as f:
json.dump({k:v.tolist() for k,v in utt_metrics.items()}, f, indent=0)
# Save all metrics to the experiment folder.
all_metrics_df = pd.DataFrame(series_list)
all_metrics_df.to_csv(os.path.join(eval_save_dir, "all_metrics.csv"))
# Print and save summary metrics
final_results = {}
for metric_name in compute_metrics:
input_metric_name = "input_" + metric_name
ldf = all_metrics_df[metric_name] - all_metrics_df[input_metric_name]
final_results[metric_name] = all_metrics_df[metric_name].mean()
final_results[metric_name + "_imp"] = ldf.mean()
print("Overall metrics :")
print(final_results)
if conf["compute_wer"]:
print("\nWER report")
wer_card = wer_tracker.final_report_as_markdown()
print(wer_card)
# Save the report
with open(os.path.join(eval_save_dir, "final_wer.md"), "w") as f:
f.write(wer_card)
with open(os.path.join(eval_save_dir, "final_metrics.json"), "w") as f:
json.dump({k:v.tolist() for k,v in final_results.items()}, f, indent=0)
# for publishing the model:
# model_dict = torch.load(model_path, map_location="cpu")
# os.makedirs(os.path.join(conf["exp_dir"], "publish_dir"), exist_ok=True)
# publishable = save_publishable(
# os.path.join(conf["exp_dir"], "publish_dir"),
# model_dict,
# metrics=final_results,
# train_conf=train_conf,
# )
if __name__ == "__main__":
args = parser.parse_args()
arg_dic = dict(vars(args))
# Load training config
conf_path = os.path.join(args.exp_dir, "conf.yml")
with open(conf_path) as f:
train_conf = yaml.safe_load(f)
arg_dic["sample_rate"] = train_conf["data"]["sample_rate"]
arg_dic["segment"] = train_conf["data"]["segment"]
arg_dic["multi_speakers"] = train_conf["training"]["multi_speakers"]
arg_dic["train_conf"] = train_conf
main(arg_dic)