update
Browse files- examples/cnn_vad_by_webrtcvad/step_1_prepare_data.py +1 -1
- examples/cnn_vad_by_webrtcvad/step_4_train_model.py +32 -8
- examples/cnn_vad_by_webrtcvad/yaml/config.yaml +30 -13
- examples/fsmn_vad_by_webrtcvad/step_4_train_model.py +1 -1
- examples/silero_vad_by_webrtcvad/step_4_train_model.py +1 -1
- toolbox/torch/utils/data/dataset/vad_padding_jsonl_dataset.py +1 -0
- toolbox/torchaudio/models/{vad/ten_vad/modeling_ten_vad.py → snr/__init__.py} +0 -0
- toolbox/torchaudio/models/vad/cnn_vad/configuration_cnn_vad.py +13 -2
- toolbox/torchaudio/models/vad/cnn_vad/modeling_cnn_vad.py +84 -10
- toolbox/torchaudio/models/vad/cnn_vad/yaml/config.yaml +7 -1
- toolbox/torchaudio/models/vad/fsmn_vad/inference_fsmn_vad.py +9 -2
- toolbox/torchaudio/models/vad/ten_vad/__init__.py +0 -12
- toolbox/torchaudio/modules/local_snr_target.py +151 -0
examples/cnn_vad_by_webrtcvad/step_1_prepare_data.py
CHANGED
|
@@ -210,7 +210,7 @@ def main():
|
|
| 210 |
"random1": random1,
|
| 211 |
}
|
| 212 |
row = json.dumps(row, ensure_ascii=False)
|
| 213 |
-
if random2 < (
|
| 214 |
fvalid.write(f"{row}\n")
|
| 215 |
else:
|
| 216 |
ftrain.write(f"{row}\n")
|
|
|
|
| 210 |
"random1": random1,
|
| 211 |
}
|
| 212 |
row = json.dumps(row, ensure_ascii=False)
|
| 213 |
+
if random2 < (2 / 300):
|
| 214 |
fvalid.write(f"{row}\n")
|
| 215 |
else:
|
| 216 |
ftrain.write(f"{row}\n")
|
examples/cnn_vad_by_webrtcvad/step_4_train_model.py
CHANGED
|
@@ -38,7 +38,7 @@ def get_args():
|
|
| 38 |
parser.add_argument("--valid_dataset", default="valid-vad.jsonl", type=str)
|
| 39 |
|
| 40 |
parser.add_argument("--num_serialized_models_to_keep", default=15, type=int)
|
| 41 |
-
parser.add_argument("--patience", default=
|
| 42 |
parser.add_argument("--serialization_dir", default="serialization_dir", type=str)
|
| 43 |
|
| 44 |
parser.add_argument("--config_file", default="yaml/config.yaml", type=str)
|
|
@@ -74,22 +74,28 @@ class CollateFunction(object):
|
|
| 74 |
|
| 75 |
def __call__(self, batch: List[dict]):
|
| 76 |
noisy_audios = list()
|
|
|
|
| 77 |
batch_vad_segments = list()
|
| 78 |
|
| 79 |
for sample in batch:
|
| 80 |
noisy_wave: torch.Tensor = sample["noisy_wave"]
|
|
|
|
| 81 |
vad_segments: List[Tuple[float, float]] = sample["vad_segments"]
|
| 82 |
|
| 83 |
noisy_audios.append(noisy_wave)
|
|
|
|
| 84 |
batch_vad_segments.append(vad_segments)
|
| 85 |
|
| 86 |
noisy_audios = torch.stack(noisy_audios)
|
|
|
|
| 87 |
|
| 88 |
# assert
|
| 89 |
if torch.any(torch.isnan(noisy_audios)) or torch.any(torch.isinf(noisy_audios)):
|
| 90 |
raise AssertionError("nan or inf in noisy_audios")
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
return noisy_audios, batch_vad_segments
|
| 93 |
|
| 94 |
|
| 95 |
collate_fn = CollateFunction()
|
|
@@ -214,6 +220,7 @@ def main():
|
|
| 214 |
average_loss = 1000000000
|
| 215 |
average_bce_loss = 1000000000
|
| 216 |
average_dice_loss = 1000000000
|
|
|
|
| 217 |
|
| 218 |
accuracy = -1
|
| 219 |
f1 = -1
|
|
@@ -242,6 +249,7 @@ def main():
|
|
| 242 |
total_loss = 0.
|
| 243 |
total_bce_loss = 0.
|
| 244 |
total_dice_loss = 0.
|
|
|
|
| 245 |
total_batches = 0.
|
| 246 |
|
| 247 |
progress_bar_train = tqdm(
|
|
@@ -249,19 +257,21 @@ def main():
|
|
| 249 |
desc="Training; epoch-{}".format(epoch_idx),
|
| 250 |
)
|
| 251 |
for train_batch in train_data_loader:
|
| 252 |
-
noisy_audios, batch_vad_segments = train_batch
|
| 253 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
|
|
|
| 254 |
# noisy_audios shape: [b, num_samples]
|
| 255 |
num_samples = noisy_audios.shape[-1]
|
| 256 |
|
| 257 |
-
logits, probs = model.forward(noisy_audios)
|
| 258 |
|
| 259 |
targets = BaseVadLoss.get_targets(probs, batch_vad_segments, duration=num_samples / config.sample_rate)
|
| 260 |
|
| 261 |
bce_loss = bce_loss_fn.forward(probs, targets)
|
| 262 |
dice_loss = dice_loss_fn.forward(probs, targets)
|
|
|
|
| 263 |
|
| 264 |
-
loss = 1.0 * bce_loss + 1.0 * dice_loss
|
| 265 |
if torch.any(torch.isnan(loss)) or torch.any(torch.isinf(loss)):
|
| 266 |
logger.info(f"find nan or inf in loss. continue.")
|
| 267 |
continue
|
|
@@ -278,11 +288,13 @@ def main():
|
|
| 278 |
total_loss += loss.item()
|
| 279 |
total_bce_loss += bce_loss.item()
|
| 280 |
total_dice_loss += dice_loss.item()
|
|
|
|
| 281 |
total_batches += 1
|
| 282 |
|
| 283 |
average_loss = round(total_loss / total_batches, 4)
|
| 284 |
average_bce_loss = round(total_bce_loss / total_batches, 4)
|
| 285 |
average_dice_loss = round(total_dice_loss / total_batches, 4)
|
|
|
|
| 286 |
|
| 287 |
metrics = vad_accuracy_metrics_fn.get_metric()
|
| 288 |
accuracy = metrics["accuracy"]
|
|
@@ -297,6 +309,7 @@ def main():
|
|
| 297 |
"loss": average_loss,
|
| 298 |
"bce_loss": average_bce_loss,
|
| 299 |
"dice_loss": average_dice_loss,
|
|
|
|
| 300 |
"accuracy": accuracy,
|
| 301 |
"f1": f1,
|
| 302 |
"precision": precision,
|
|
@@ -316,6 +329,7 @@ def main():
|
|
| 316 |
total_loss = 0.
|
| 317 |
total_bce_loss = 0.
|
| 318 |
total_dice_loss = 0.
|
|
|
|
| 319 |
total_batches = 0.
|
| 320 |
|
| 321 |
progress_bar_train.close()
|
|
@@ -323,19 +337,21 @@ def main():
|
|
| 323 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 324 |
)
|
| 325 |
for eval_batch in valid_data_loader:
|
| 326 |
-
noisy_audios, batch_vad_segments =
|
| 327 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
|
|
|
| 328 |
# noisy_audios shape: [b, num_samples]
|
| 329 |
num_samples = noisy_audios.shape[-1]
|
| 330 |
|
| 331 |
-
logits, probs = model.forward(noisy_audios)
|
| 332 |
|
| 333 |
targets = BaseVadLoss.get_targets(probs, batch_vad_segments, duration=num_samples / config.sample_rate)
|
| 334 |
|
| 335 |
bce_loss = bce_loss_fn.forward(probs, targets)
|
| 336 |
dice_loss = dice_loss_fn.forward(probs, targets)
|
|
|
|
| 337 |
|
| 338 |
-
loss = 1.0 * bce_loss + 1.0 * dice_loss
|
| 339 |
if torch.any(torch.isnan(loss)) or torch.any(torch.isinf(loss)):
|
| 340 |
logger.info(f"find nan or inf in loss. continue.")
|
| 341 |
continue
|
|
@@ -346,11 +362,13 @@ def main():
|
|
| 346 |
total_loss += loss.item()
|
| 347 |
total_bce_loss += bce_loss.item()
|
| 348 |
total_dice_loss += dice_loss.item()
|
|
|
|
| 349 |
total_batches += 1
|
| 350 |
|
| 351 |
average_loss = round(total_loss / total_batches, 4)
|
| 352 |
average_bce_loss = round(total_bce_loss / total_batches, 4)
|
| 353 |
average_dice_loss = round(total_dice_loss / total_batches, 4)
|
|
|
|
| 354 |
|
| 355 |
metrics = vad_accuracy_metrics_fn.get_metric()
|
| 356 |
accuracy = metrics["accuracy"]
|
|
@@ -365,6 +383,7 @@ def main():
|
|
| 365 |
"loss": average_loss,
|
| 366 |
"bce_loss": average_bce_loss,
|
| 367 |
"dice_loss": average_dice_loss,
|
|
|
|
| 368 |
"accuracy": accuracy,
|
| 369 |
"f1": f1,
|
| 370 |
"precision": precision,
|
|
@@ -378,6 +397,7 @@ def main():
|
|
| 378 |
total_loss = 0.
|
| 379 |
total_bce_loss = 0.
|
| 380 |
total_dice_loss = 0.
|
|
|
|
| 381 |
total_batches = 0.
|
| 382 |
|
| 383 |
progress_bar_eval.close()
|
|
@@ -419,8 +439,12 @@ def main():
|
|
| 419 |
"loss": average_loss,
|
| 420 |
"bce_loss": average_bce_loss,
|
| 421 |
"dice_loss": average_dice_loss,
|
|
|
|
| 422 |
|
| 423 |
"accuracy": accuracy,
|
|
|
|
|
|
|
|
|
|
| 424 |
}
|
| 425 |
metrics_filename = save_dir / "metrics_epoch.json"
|
| 426 |
with open(metrics_filename, "w", encoding="utf-8") as f:
|
|
|
|
| 38 |
parser.add_argument("--valid_dataset", default="valid-vad.jsonl", type=str)
|
| 39 |
|
| 40 |
parser.add_argument("--num_serialized_models_to_keep", default=15, type=int)
|
| 41 |
+
parser.add_argument("--patience", default=10, type=int)
|
| 42 |
parser.add_argument("--serialization_dir", default="serialization_dir", type=str)
|
| 43 |
|
| 44 |
parser.add_argument("--config_file", default="yaml/config.yaml", type=str)
|
|
|
|
| 74 |
|
| 75 |
def __call__(self, batch: List[dict]):
|
| 76 |
noisy_audios = list()
|
| 77 |
+
clean_audios = list()
|
| 78 |
batch_vad_segments = list()
|
| 79 |
|
| 80 |
for sample in batch:
|
| 81 |
noisy_wave: torch.Tensor = sample["noisy_wave"]
|
| 82 |
+
speech_wave: torch.Tensor = sample["speech_wave"]
|
| 83 |
vad_segments: List[Tuple[float, float]] = sample["vad_segments"]
|
| 84 |
|
| 85 |
noisy_audios.append(noisy_wave)
|
| 86 |
+
clean_audios.append(speech_wave)
|
| 87 |
batch_vad_segments.append(vad_segments)
|
| 88 |
|
| 89 |
noisy_audios = torch.stack(noisy_audios)
|
| 90 |
+
clean_audios = torch.stack(clean_audios)
|
| 91 |
|
| 92 |
# assert
|
| 93 |
if torch.any(torch.isnan(noisy_audios)) or torch.any(torch.isinf(noisy_audios)):
|
| 94 |
raise AssertionError("nan or inf in noisy_audios")
|
| 95 |
+
if torch.any(torch.isnan(clean_audios)) or torch.any(torch.isinf(clean_audios)):
|
| 96 |
+
raise AssertionError("nan or inf in clean_audios")
|
| 97 |
|
| 98 |
+
return noisy_audios, clean_audios, batch_vad_segments
|
| 99 |
|
| 100 |
|
| 101 |
collate_fn = CollateFunction()
|
|
|
|
| 220 |
average_loss = 1000000000
|
| 221 |
average_bce_loss = 1000000000
|
| 222 |
average_dice_loss = 1000000000
|
| 223 |
+
average_lsnr_loss = 1000000000
|
| 224 |
|
| 225 |
accuracy = -1
|
| 226 |
f1 = -1
|
|
|
|
| 249 |
total_loss = 0.
|
| 250 |
total_bce_loss = 0.
|
| 251 |
total_dice_loss = 0.
|
| 252 |
+
total_lsnr_loss = 0.
|
| 253 |
total_batches = 0.
|
| 254 |
|
| 255 |
progress_bar_train = tqdm(
|
|
|
|
| 257 |
desc="Training; epoch-{}".format(epoch_idx),
|
| 258 |
)
|
| 259 |
for train_batch in train_data_loader:
|
| 260 |
+
noisy_audios, clean_audios, batch_vad_segments = train_batch
|
| 261 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 262 |
+
clean_audios: torch.Tensor = clean_audios.to(device)
|
| 263 |
# noisy_audios shape: [b, num_samples]
|
| 264 |
num_samples = noisy_audios.shape[-1]
|
| 265 |
|
| 266 |
+
logits, probs, lsnr = model.forward(noisy_audios)
|
| 267 |
|
| 268 |
targets = BaseVadLoss.get_targets(probs, batch_vad_segments, duration=num_samples / config.sample_rate)
|
| 269 |
|
| 270 |
bce_loss = bce_loss_fn.forward(probs, targets)
|
| 271 |
dice_loss = dice_loss_fn.forward(probs, targets)
|
| 272 |
+
lsnr_loss = model.lsnr_loss_fn(lsnr, clean_audios, noisy_audios)
|
| 273 |
|
| 274 |
+
loss = 1.0 * bce_loss + 1.0 * dice_loss + 0.3 * lsnr_loss
|
| 275 |
if torch.any(torch.isnan(loss)) or torch.any(torch.isinf(loss)):
|
| 276 |
logger.info(f"find nan or inf in loss. continue.")
|
| 277 |
continue
|
|
|
|
| 288 |
total_loss += loss.item()
|
| 289 |
total_bce_loss += bce_loss.item()
|
| 290 |
total_dice_loss += dice_loss.item()
|
| 291 |
+
total_lsnr_loss += lsnr_loss.item()
|
| 292 |
total_batches += 1
|
| 293 |
|
| 294 |
average_loss = round(total_loss / total_batches, 4)
|
| 295 |
average_bce_loss = round(total_bce_loss / total_batches, 4)
|
| 296 |
average_dice_loss = round(total_dice_loss / total_batches, 4)
|
| 297 |
+
average_lsnr_loss = round(total_lsnr_loss / total_batches, 4)
|
| 298 |
|
| 299 |
metrics = vad_accuracy_metrics_fn.get_metric()
|
| 300 |
accuracy = metrics["accuracy"]
|
|
|
|
| 309 |
"loss": average_loss,
|
| 310 |
"bce_loss": average_bce_loss,
|
| 311 |
"dice_loss": average_dice_loss,
|
| 312 |
+
"lsnr_loss": average_lsnr_loss,
|
| 313 |
"accuracy": accuracy,
|
| 314 |
"f1": f1,
|
| 315 |
"precision": precision,
|
|
|
|
| 329 |
total_loss = 0.
|
| 330 |
total_bce_loss = 0.
|
| 331 |
total_dice_loss = 0.
|
| 332 |
+
total_lsnr_loss = 0.
|
| 333 |
total_batches = 0.
|
| 334 |
|
| 335 |
progress_bar_train.close()
|
|
|
|
| 337 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 338 |
)
|
| 339 |
for eval_batch in valid_data_loader:
|
| 340 |
+
noisy_audios, clean_audios, batch_vad_segments = eval_batch
|
| 341 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 342 |
+
clean_audios: torch.Tensor = clean_audios.to(device)
|
| 343 |
# noisy_audios shape: [b, num_samples]
|
| 344 |
num_samples = noisy_audios.shape[-1]
|
| 345 |
|
| 346 |
+
logits, probs, lsnr = model.forward(noisy_audios)
|
| 347 |
|
| 348 |
targets = BaseVadLoss.get_targets(probs, batch_vad_segments, duration=num_samples / config.sample_rate)
|
| 349 |
|
| 350 |
bce_loss = bce_loss_fn.forward(probs, targets)
|
| 351 |
dice_loss = dice_loss_fn.forward(probs, targets)
|
| 352 |
+
lsnr_loss = model.lsnr_loss_fn(lsnr, clean_audios, noisy_audios)
|
| 353 |
|
| 354 |
+
loss = 1.0 * bce_loss + 1.0 * dice_loss + 0.3 * lsnr_loss
|
| 355 |
if torch.any(torch.isnan(loss)) or torch.any(torch.isinf(loss)):
|
| 356 |
logger.info(f"find nan or inf in loss. continue.")
|
| 357 |
continue
|
|
|
|
| 362 |
total_loss += loss.item()
|
| 363 |
total_bce_loss += bce_loss.item()
|
| 364 |
total_dice_loss += dice_loss.item()
|
| 365 |
+
total_lsnr_loss += lsnr_loss.item()
|
| 366 |
total_batches += 1
|
| 367 |
|
| 368 |
average_loss = round(total_loss / total_batches, 4)
|
| 369 |
average_bce_loss = round(total_bce_loss / total_batches, 4)
|
| 370 |
average_dice_loss = round(total_dice_loss / total_batches, 4)
|
| 371 |
+
average_lsnr_loss = round(total_lsnr_loss / total_batches, 4)
|
| 372 |
|
| 373 |
metrics = vad_accuracy_metrics_fn.get_metric()
|
| 374 |
accuracy = metrics["accuracy"]
|
|
|
|
| 383 |
"loss": average_loss,
|
| 384 |
"bce_loss": average_bce_loss,
|
| 385 |
"dice_loss": average_dice_loss,
|
| 386 |
+
"lsnr_loss": average_lsnr_loss,
|
| 387 |
"accuracy": accuracy,
|
| 388 |
"f1": f1,
|
| 389 |
"precision": precision,
|
|
|
|
| 397 |
total_loss = 0.
|
| 398 |
total_bce_loss = 0.
|
| 399 |
total_dice_loss = 0.
|
| 400 |
+
total_lsnr_loss = 0.
|
| 401 |
total_batches = 0.
|
| 402 |
|
| 403 |
progress_bar_eval.close()
|
|
|
|
| 439 |
"loss": average_loss,
|
| 440 |
"bce_loss": average_bce_loss,
|
| 441 |
"dice_loss": average_dice_loss,
|
| 442 |
+
"lsnr_loss": average_lsnr_loss,
|
| 443 |
|
| 444 |
"accuracy": accuracy,
|
| 445 |
+
"f1": f1,
|
| 446 |
+
"precision": precision,
|
| 447 |
+
"recall": recall,
|
| 448 |
}
|
| 449 |
metrics_filename = save_dir / "metrics_epoch.json"
|
| 450 |
with open(metrics_filename, "w", encoding="utf-8") as f:
|
examples/cnn_vad_by_webrtcvad/yaml/config.yaml
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
model_name: "
|
| 2 |
|
| 3 |
# spec
|
| 4 |
sample_rate: 8000
|
|
@@ -8,19 +8,36 @@ hop_size: 80
|
|
| 8 |
win_type: hann
|
| 9 |
|
| 10 |
# model
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# data
|
| 26 |
min_snr_db: -10
|
|
|
|
| 1 |
+
model_name: "cnn_vad"
|
| 2 |
|
| 3 |
# spec
|
| 4 |
sample_rate: 8000
|
|
|
|
| 8 |
win_type: hann
|
| 9 |
|
| 10 |
# model
|
| 11 |
+
conv2d_block_param_list:
|
| 12 |
+
- batch_norm: true
|
| 13 |
+
in_channels: 1
|
| 14 |
+
out_channels: 4
|
| 15 |
+
kernel_size: 3
|
| 16 |
+
padding: "same"
|
| 17 |
+
dilation: 3
|
| 18 |
+
activation: relu
|
| 19 |
+
dropout: 0.1
|
| 20 |
+
- in_channels: 4
|
| 21 |
+
out_channels: 4
|
| 22 |
+
kernel_size: 5
|
| 23 |
+
padding: "same"
|
| 24 |
+
dilation: 3
|
| 25 |
+
activation: relu
|
| 26 |
+
dropout: 0.1
|
| 27 |
+
- in_channels: 4
|
| 28 |
+
out_channels: 4
|
| 29 |
+
kernel_size: 3
|
| 30 |
+
padding: "same"
|
| 31 |
+
dilation: 2
|
| 32 |
+
activation: relu
|
| 33 |
+
dropout: 0.1
|
| 34 |
+
encoder_output_size: 1028
|
| 35 |
|
| 36 |
+
# lsnr
|
| 37 |
+
n_frame: 3
|
| 38 |
+
min_local_snr_db: -15
|
| 39 |
+
max_local_snr_db: 30
|
| 40 |
+
norm_tau: 1.
|
| 41 |
|
| 42 |
# data
|
| 43 |
min_snr_db: -10
|
examples/fsmn_vad_by_webrtcvad/step_4_train_model.py
CHANGED
|
@@ -323,7 +323,7 @@ def main():
|
|
| 323 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 324 |
)
|
| 325 |
for eval_batch in valid_data_loader:
|
| 326 |
-
noisy_audios, batch_vad_segments =
|
| 327 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 328 |
# noisy_audios shape: [b, num_samples]
|
| 329 |
num_samples = noisy_audios.shape[-1]
|
|
|
|
| 323 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 324 |
)
|
| 325 |
for eval_batch in valid_data_loader:
|
| 326 |
+
noisy_audios, batch_vad_segments = eval_batch
|
| 327 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 328 |
# noisy_audios shape: [b, num_samples]
|
| 329 |
num_samples = noisy_audios.shape[-1]
|
examples/silero_vad_by_webrtcvad/step_4_train_model.py
CHANGED
|
@@ -323,7 +323,7 @@ def main():
|
|
| 323 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 324 |
)
|
| 325 |
for eval_batch in valid_data_loader:
|
| 326 |
-
noisy_audios, batch_vad_segments =
|
| 327 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 328 |
# noisy_audios shape: [b, num_samples]
|
| 329 |
num_samples = noisy_audios.shape[-1]
|
|
|
|
| 323 |
desc="Evaluation; steps-{}k".format(int(step_idx/1000)),
|
| 324 |
)
|
| 325 |
for eval_batch in valid_data_loader:
|
| 326 |
+
noisy_audios, batch_vad_segments = eval_batch
|
| 327 |
noisy_audios: torch.Tensor = noisy_audios.to(device)
|
| 328 |
# noisy_audios shape: [b, num_samples]
|
| 329 |
num_samples = noisy_audios.shape[-1]
|
toolbox/torch/utils/data/dataset/vad_padding_jsonl_dataset.py
CHANGED
|
@@ -162,6 +162,7 @@ class VadPaddingJsonlDataset(IterableDataset):
|
|
| 162 |
|
| 163 |
result = {
|
| 164 |
"noisy_wave": noisy_wave,
|
|
|
|
| 165 |
"vad_segments": vad_segments,
|
| 166 |
}
|
| 167 |
return result
|
|
|
|
| 162 |
|
| 163 |
result = {
|
| 164 |
"noisy_wave": noisy_wave,
|
| 165 |
+
"speech_wave": speech_wave,
|
| 166 |
"vad_segments": vad_segments,
|
| 167 |
}
|
| 168 |
return result
|
toolbox/torchaudio/models/{vad/ten_vad/modeling_ten_vad.py → snr/__init__.py}
RENAMED
|
File without changes
|
toolbox/torchaudio/models/vad/cnn_vad/configuration_cnn_vad.py
CHANGED
|
@@ -46,7 +46,12 @@ class CNNVadConfig(PretrainedConfig):
|
|
| 46 |
win_type: str = "hann",
|
| 47 |
|
| 48 |
conv2d_block_param_list: list = None,
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
min_snr_db: float = -10,
|
| 52 |
max_snr_db: float = 20,
|
|
@@ -75,7 +80,13 @@ class CNNVadConfig(PretrainedConfig):
|
|
| 75 |
|
| 76 |
# encoder
|
| 77 |
self.conv2d_block_param_list = conv2d_block_param_list or DEFAULT_CONV2D_BLOCK_PARAM_LIST
|
| 78 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
# data snr
|
| 81 |
self.min_snr_db = min_snr_db
|
|
|
|
| 46 |
win_type: str = "hann",
|
| 47 |
|
| 48 |
conv2d_block_param_list: list = None,
|
| 49 |
+
encoder_output_size: int = 1028,
|
| 50 |
+
|
| 51 |
+
n_frame: int = 3,
|
| 52 |
+
min_local_snr_db: float = -15,
|
| 53 |
+
max_local_snr_db: float = 30,
|
| 54 |
+
norm_tau: float = 1.,
|
| 55 |
|
| 56 |
min_snr_db: float = -10,
|
| 57 |
max_snr_db: float = 20,
|
|
|
|
| 80 |
|
| 81 |
# encoder
|
| 82 |
self.conv2d_block_param_list = conv2d_block_param_list or DEFAULT_CONV2D_BLOCK_PARAM_LIST
|
| 83 |
+
self.encoder_output_size = encoder_output_size
|
| 84 |
+
|
| 85 |
+
# lsnr
|
| 86 |
+
self.n_frame = n_frame
|
| 87 |
+
self.min_local_snr_db = min_local_snr_db
|
| 88 |
+
self.max_local_snr_db = max_local_snr_db
|
| 89 |
+
self.norm_tau = norm_tau
|
| 90 |
|
| 91 |
# data snr
|
| 92 |
self.min_snr_db = min_snr_db
|
toolbox/torchaudio/models/vad/cnn_vad/modeling_cnn_vad.py
CHANGED
|
@@ -5,10 +5,12 @@ from typing import Dict, List, Optional, Tuple, Union
|
|
| 5 |
|
| 6 |
import torch
|
| 7 |
import torch.nn as nn
|
|
|
|
| 8 |
|
| 9 |
from toolbox.torchaudio.configuration_utils import CONFIG_FILE
|
| 10 |
from toolbox.torchaudio.models.vad.cnn_vad.configuration_cnn_vad import CNNVadConfig
|
| 11 |
from toolbox.torchaudio.modules.conv_stft import ConvSTFT
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
MODEL_FILE = "model.pt"
|
|
@@ -77,20 +79,26 @@ class Conv2dBlock(nn.Module):
|
|
| 77 |
|
| 78 |
class CNNVadModel(nn.Module):
|
| 79 |
def __init__(self,
|
|
|
|
| 80 |
nfft: int,
|
| 81 |
win_size: int,
|
| 82 |
hop_size: int,
|
| 83 |
win_type: str,
|
| 84 |
conv2d_block_param_list: List[dict],
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
):
|
| 87 |
super(CNNVadModel, self).__init__()
|
|
|
|
| 88 |
self.nfft = nfft
|
| 89 |
self.win_size = win_size
|
| 90 |
self.hop_size = hop_size
|
| 91 |
self.win_type = win_type
|
| 92 |
self.conv2d_block_param_list = conv2d_block_param_list
|
| 93 |
-
self.
|
|
|
|
|
|
|
| 94 |
|
| 95 |
self.eps = 1e-12
|
| 96 |
|
|
@@ -102,6 +110,14 @@ class CNNVadModel(nn.Module):
|
|
| 102 |
power=1,
|
| 103 |
requires_grad=False
|
| 104 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
self.cnn_encoder_list = nn.ModuleList(modules=[
|
| 107 |
Conv2dBlock(
|
|
@@ -117,14 +133,34 @@ class CNNVadModel(nn.Module):
|
|
| 117 |
for param in conv2d_block_param_list
|
| 118 |
])
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
|
|
|
| 122 |
nn.ReLU(),
|
| 123 |
nn.Linear(32, 1),
|
| 124 |
)
|
| 125 |
-
|
| 126 |
self.sigmoid = nn.Sigmoid()
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
def forward(self, signal: torch.Tensor):
|
| 129 |
if signal.dim() == 2:
|
| 130 |
signal = torch.unsqueeze(signal, dim=1)
|
|
@@ -148,11 +184,46 @@ class CNNVadModel(nn.Module):
|
|
| 148 |
x = torch.reshape(x, shape=(b, t, c*d))
|
| 149 |
# x: [b, t, c*d]
|
| 150 |
|
| 151 |
-
logits = self.
|
| 152 |
# logits shape: [b, t, 1]
|
| 153 |
probs = self.sigmoid.forward(logits)
|
| 154 |
# probs shape: [b, t, 1]
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
|
| 158 |
class CNNVadPretrainedModel(CNNVadModel):
|
|
@@ -165,7 +236,9 @@ class CNNVadPretrainedModel(CNNVadModel):
|
|
| 165 |
hop_size=config.hop_size,
|
| 166 |
win_type=config.win_type,
|
| 167 |
conv2d_block_param_list=config.conv2d_block_param_list,
|
| 168 |
-
|
|
|
|
|
|
|
| 169 |
)
|
| 170 |
self.config = config
|
| 171 |
|
|
@@ -214,9 +287,10 @@ def main():
|
|
| 214 |
|
| 215 |
noisy = torch.randn(size=(1, 16000), dtype=torch.float32)
|
| 216 |
|
| 217 |
-
logits, probs = model.forward(noisy)
|
| 218 |
-
print(f"
|
| 219 |
print(f"probs.shape: {probs.shape}")
|
|
|
|
| 220 |
|
| 221 |
return
|
| 222 |
|
|
|
|
| 5 |
|
| 6 |
import torch
|
| 7 |
import torch.nn as nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
|
| 10 |
from toolbox.torchaudio.configuration_utils import CONFIG_FILE
|
| 11 |
from toolbox.torchaudio.models.vad.cnn_vad.configuration_cnn_vad import CNNVadConfig
|
| 12 |
from toolbox.torchaudio.modules.conv_stft import ConvSTFT
|
| 13 |
+
from toolbox.torchaudio.modules.local_snr_target import LocalSnrTarget
|
| 14 |
|
| 15 |
|
| 16 |
MODEL_FILE = "model.pt"
|
|
|
|
| 79 |
|
| 80 |
class CNNVadModel(nn.Module):
|
| 81 |
def __init__(self,
|
| 82 |
+
sample_rate: int,
|
| 83 |
nfft: int,
|
| 84 |
win_size: int,
|
| 85 |
hop_size: int,
|
| 86 |
win_type: str,
|
| 87 |
conv2d_block_param_list: List[dict],
|
| 88 |
+
encoder_output_size: int,
|
| 89 |
+
min_local_snr: float = -15,
|
| 90 |
+
max_local_snr: float = 30,
|
| 91 |
):
|
| 92 |
super(CNNVadModel, self).__init__()
|
| 93 |
+
self.sample_rate = sample_rate
|
| 94 |
self.nfft = nfft
|
| 95 |
self.win_size = win_size
|
| 96 |
self.hop_size = hop_size
|
| 97 |
self.win_type = win_type
|
| 98 |
self.conv2d_block_param_list = conv2d_block_param_list
|
| 99 |
+
self.encoder_output_size = encoder_output_size
|
| 100 |
+
self.min_local_snr = min_local_snr
|
| 101 |
+
self.max_local_snr = max_local_snr
|
| 102 |
|
| 103 |
self.eps = 1e-12
|
| 104 |
|
|
|
|
| 110 |
power=1,
|
| 111 |
requires_grad=False
|
| 112 |
)
|
| 113 |
+
self.complex_stft = ConvSTFT(
|
| 114 |
+
nfft=nfft,
|
| 115 |
+
win_size=win_size,
|
| 116 |
+
hop_size=hop_size,
|
| 117 |
+
win_type=win_type,
|
| 118 |
+
power=None,
|
| 119 |
+
requires_grad=False
|
| 120 |
+
)
|
| 121 |
|
| 122 |
self.cnn_encoder_list = nn.ModuleList(modules=[
|
| 123 |
Conv2dBlock(
|
|
|
|
| 133 |
for param in conv2d_block_param_list
|
| 134 |
])
|
| 135 |
|
| 136 |
+
# vad
|
| 137 |
+
self.vad_fc = nn.Sequential(
|
| 138 |
+
nn.Linear(encoder_output_size, 32),
|
| 139 |
nn.ReLU(),
|
| 140 |
nn.Linear(32, 1),
|
| 141 |
)
|
|
|
|
| 142 |
self.sigmoid = nn.Sigmoid()
|
| 143 |
|
| 144 |
+
# lsnr
|
| 145 |
+
self.lsnr_fc = nn.Sequential(
|
| 146 |
+
nn.Linear(encoder_output_size, 1),
|
| 147 |
+
nn.Sigmoid()
|
| 148 |
+
)
|
| 149 |
+
self.lsnr_scale = self.max_local_snr - self.min_local_snr
|
| 150 |
+
self.lsnr_offset = self.min_local_snr
|
| 151 |
+
|
| 152 |
+
# lsnr
|
| 153 |
+
self.lsnr_fn = LocalSnrTarget(
|
| 154 |
+
sample_rate=self.sample_rate,
|
| 155 |
+
nfft=self.nfft,
|
| 156 |
+
win_size=self.win_size,
|
| 157 |
+
hop_size=self.hop_size,
|
| 158 |
+
n_frame=self.n_frame,
|
| 159 |
+
min_local_snr=self.min_local_snr,
|
| 160 |
+
max_local_snr=self.max_local_snr,
|
| 161 |
+
db=True,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
def forward(self, signal: torch.Tensor):
|
| 165 |
if signal.dim() == 2:
|
| 166 |
signal = torch.unsqueeze(signal, dim=1)
|
|
|
|
| 184 |
x = torch.reshape(x, shape=(b, t, c*d))
|
| 185 |
# x: [b, t, c*d]
|
| 186 |
|
| 187 |
+
logits = self.vad_fc.forward(x)
|
| 188 |
# logits shape: [b, t, 1]
|
| 189 |
probs = self.sigmoid.forward(logits)
|
| 190 |
# probs shape: [b, t, 1]
|
| 191 |
+
|
| 192 |
+
lsnr = self.lsnr_fc.forward(x) * self.lsnr_scale + self.lsnr_offset
|
| 193 |
+
# lsnr shape: [b, t, 1]
|
| 194 |
+
|
| 195 |
+
return logits, probs, lsnr
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def lsnr_loss_fn(self, lsnr: torch.Tensor, clean: torch.Tensor, noisy: torch.Tensor):
|
| 199 |
+
if noisy.shape != clean.shape:
|
| 200 |
+
raise AssertionError("Input signals must have the same shape")
|
| 201 |
+
noise = noisy - clean
|
| 202 |
+
|
| 203 |
+
if clean.dim() == 2:
|
| 204 |
+
clean = torch.unsqueeze(clean, dim=1)
|
| 205 |
+
if noise.dim() == 2:
|
| 206 |
+
noise = torch.unsqueeze(noise, dim=1)
|
| 207 |
+
|
| 208 |
+
stft_clean = self.complex_stft.forward(clean)
|
| 209 |
+
stft_noise = self.complex_stft.forward(noise)
|
| 210 |
+
# shape: [b, f, t]
|
| 211 |
+
stft_clean = torch.transpose(stft_clean, dim0=1, dim1=2)
|
| 212 |
+
stft_noise = torch.transpose(stft_noise, dim0=1, dim1=2)
|
| 213 |
+
# shape: [b, t, f]
|
| 214 |
+
stft_clean = torch.unsqueeze(stft_clean, dim=1)
|
| 215 |
+
stft_noise = torch.unsqueeze(stft_noise, dim=1)
|
| 216 |
+
# shape: [b, 1, t, f]
|
| 217 |
+
|
| 218 |
+
# lsnr shape: [b, 1, t]
|
| 219 |
+
lsnr = lsnr.squeeze(1)
|
| 220 |
+
# lsnr shape: [b, t]
|
| 221 |
+
|
| 222 |
+
lsnr_gth = self.lsnr_fn.forward(stft_clean, stft_noise)
|
| 223 |
+
# lsnr_gth shape: [b, t]
|
| 224 |
+
|
| 225 |
+
loss = F.mse_loss(lsnr, lsnr_gth)
|
| 226 |
+
return loss
|
| 227 |
|
| 228 |
|
| 229 |
class CNNVadPretrainedModel(CNNVadModel):
|
|
|
|
| 236 |
hop_size=config.hop_size,
|
| 237 |
win_type=config.win_type,
|
| 238 |
conv2d_block_param_list=config.conv2d_block_param_list,
|
| 239 |
+
encoder_output_size=config.encoder_output_size,
|
| 240 |
+
min_local_snr=config.min_local_snr,
|
| 241 |
+
max_local_snr=config.max_local_snr,
|
| 242 |
)
|
| 243 |
self.config = config
|
| 244 |
|
|
|
|
| 287 |
|
| 288 |
noisy = torch.randn(size=(1, 16000), dtype=torch.float32)
|
| 289 |
|
| 290 |
+
logits, probs, lsnr = model.forward(noisy)
|
| 291 |
+
print(f"logits.shape: {logits.shape}")
|
| 292 |
print(f"probs.shape: {probs.shape}")
|
| 293 |
+
print(f"lsnr.shape: {lsnr.shape}")
|
| 294 |
|
| 295 |
return
|
| 296 |
|
toolbox/torchaudio/models/vad/cnn_vad/yaml/config.yaml
CHANGED
|
@@ -31,7 +31,13 @@ conv2d_block_param_list:
|
|
| 31 |
dilation: 2
|
| 32 |
activation: relu
|
| 33 |
dropout: 0.1
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
# data
|
| 37 |
min_snr_db: -10
|
|
|
|
| 31 |
dilation: 2
|
| 32 |
activation: relu
|
| 33 |
dropout: 0.1
|
| 34 |
+
encoder_output_size: 1028
|
| 35 |
+
|
| 36 |
+
# lsnr
|
| 37 |
+
n_frame: 3
|
| 38 |
+
min_local_snr_db: -15
|
| 39 |
+
max_local_snr_db: 30
|
| 40 |
+
norm_tau: 1.
|
| 41 |
|
| 42 |
# data
|
| 43 |
min_snr_db: -10
|
toolbox/torchaudio/models/vad/fsmn_vad/inference_fsmn_vad.py
CHANGED
|
@@ -92,8 +92,15 @@ def get_args():
|
|
| 92 |
# default=(project_path / "data/examples/hado/b556437e-c68b-4f6d-9eed-2977c29db887.wav").as_posix(),
|
| 93 |
# default=(project_path / "data/examples/hado/eae93a33-8ee0-4d86-8f85-cac5116ae6ef.wav").as_posix(),
|
| 94 |
# default=(project_path / "data/examples/speech/active_media_r_0ba69730-66a4-4ecd-8929-ef58f18f4612_2.wav").as_posix(),
|
| 95 |
-
default=(project_path / "data/examples/speech/active_media_r_2a2f472b-a0b8-4fd5-b1c4-1aedc5d2ce57_0.wav").as_posix(),
|
| 96 |
-
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
type=str,
|
| 98 |
)
|
| 99 |
args = parser.parse_args()
|
|
|
|
| 92 |
# default=(project_path / "data/examples/hado/b556437e-c68b-4f6d-9eed-2977c29db887.wav").as_posix(),
|
| 93 |
# default=(project_path / "data/examples/hado/eae93a33-8ee0-4d86-8f85-cac5116ae6ef.wav").as_posix(),
|
| 94 |
# default=(project_path / "data/examples/speech/active_media_r_0ba69730-66a4-4ecd-8929-ef58f18f4612_2.wav").as_posix(),
|
| 95 |
+
# default=(project_path / "data/examples/speech/active_media_r_2a2f472b-a0b8-4fd5-b1c4-1aedc5d2ce57_0.wav").as_posix(),
|
| 96 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_1d4edd08-c6db-41a1-a349-7a22ac36f684_6.wav",
|
| 97 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_04f6d842-488e-4e34-967b-2980fdd877c7_5.wav",
|
| 98 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_7f6670aa-5600-44c0-9bce-77c1d2b739c7_8.wav",
|
| 99 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_1187ff81-3a38-4b0b-846f-b81ad6540ce9_5.wav",
|
| 100 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_e44bbfaa-f332-4c02-90a3-cc98505d9a1b_3.wav",
|
| 101 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_f89cf1af-f556-42fd-9a42-6c9431002a12_11.wav",
|
| 102 |
+
# default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_r_f89cf1af-f556-42fd-9a42-6c9431002a12_15.wav",
|
| 103 |
+
default=r"D:\Users\tianx\HuggingDatasets\nx_noise\data\speech\nx-speech\en-SG\2025-05-29\active_media_w_8b6e28e2-a238-4c8c-b2e3-426b1fca149b_6.wav",
|
| 104 |
type=str,
|
| 105 |
)
|
| 106 |
args = parser.parse_args()
|
toolbox/torchaudio/models/vad/ten_vad/__init__.py
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/python3
|
| 2 |
-
# -*- coding: utf-8 -*-
|
| 3 |
-
"""
|
| 4 |
-
https://huggingface.co/TEN-framework/ten-vad
|
| 5 |
-
https://zhuanlan.zhihu.com/p/1906832842756976909
|
| 6 |
-
https://github.com/TEN-framework/ten-vad
|
| 7 |
-
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
if __name__ == "__main__":
|
| 12 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
toolbox/torchaudio/modules/local_snr_target.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
https://github.com/Rikorose/DeepFilterNet/blob/main/DeepFilterNet/df/modules.py#L816
|
| 5 |
+
"""
|
| 6 |
+
from typing import Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
import torchaudio
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def local_energy(spec: torch.Tensor, n_frame: int, device: torch.device) -> torch.Tensor:
|
| 15 |
+
if n_frame % 2 == 0:
|
| 16 |
+
n_frame += 1
|
| 17 |
+
n_frame_half = n_frame // 2
|
| 18 |
+
|
| 19 |
+
# spec shape: [b, c, t, f, 2]
|
| 20 |
+
spec = spec.pow(2).sum(-1).sum(-1)
|
| 21 |
+
# spec shape: [b, c, t]
|
| 22 |
+
spec = F.pad(spec, (n_frame_half, n_frame_half, 0, 0))
|
| 23 |
+
# spec shape: [b, c, t-pad]
|
| 24 |
+
|
| 25 |
+
weight = torch.hann_window(n_frame, device=device, dtype=spec.dtype)
|
| 26 |
+
# w shape: [n_frame]
|
| 27 |
+
|
| 28 |
+
spec = spec.unfold(-1, size=n_frame, step=1) * weight
|
| 29 |
+
# x shape: [b, c, t, n_frame]
|
| 30 |
+
|
| 31 |
+
result = torch.sum(spec, dim=-1).div(n_frame)
|
| 32 |
+
# result shape: [b, c, t]
|
| 33 |
+
return result
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def local_snr(spec_clean: torch.Tensor,
|
| 37 |
+
spec_noise: torch.Tensor,
|
| 38 |
+
n_frame: int = 5,
|
| 39 |
+
db: bool = False,
|
| 40 |
+
eps: float = 1e-12,
|
| 41 |
+
):
|
| 42 |
+
# [b, c, t, f]
|
| 43 |
+
spec_clean = torch.view_as_real(spec_clean)
|
| 44 |
+
spec_noise = torch.view_as_real(spec_noise)
|
| 45 |
+
# [b, c, t, f, 2]
|
| 46 |
+
|
| 47 |
+
energy_clean = local_energy(spec_clean, n_frame=n_frame, device=spec_clean.device)
|
| 48 |
+
energy_noise = local_energy(spec_noise, n_frame=n_frame, device=spec_noise.device)
|
| 49 |
+
# [b, c, t]
|
| 50 |
+
|
| 51 |
+
snr = energy_clean / energy_noise.clamp_min(eps)
|
| 52 |
+
# snr shape: [b, c, t]
|
| 53 |
+
|
| 54 |
+
if db:
|
| 55 |
+
snr = snr.clamp_min(eps).log10().mul(10)
|
| 56 |
+
return snr, energy_clean, energy_noise
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class LocalSnrTarget(nn.Module):
|
| 60 |
+
def __init__(self,
|
| 61 |
+
sample_rate: int = 8000,
|
| 62 |
+
nfft: int = 512,
|
| 63 |
+
win_size: int = 512,
|
| 64 |
+
hop_size: int = 256,
|
| 65 |
+
|
| 66 |
+
n_frame: int = 3,
|
| 67 |
+
|
| 68 |
+
min_local_snr: int = -15,
|
| 69 |
+
max_local_snr: int = 30,
|
| 70 |
+
|
| 71 |
+
db: bool = True,
|
| 72 |
+
):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.sample_rate = sample_rate
|
| 75 |
+
self.nfft = nfft
|
| 76 |
+
self.win_size = win_size
|
| 77 |
+
self.hop_size = hop_size
|
| 78 |
+
|
| 79 |
+
self.n_frame = n_frame
|
| 80 |
+
|
| 81 |
+
self.min_local_snr = min_local_snr
|
| 82 |
+
self.max_local_snr = max_local_snr
|
| 83 |
+
|
| 84 |
+
self.db = db
|
| 85 |
+
|
| 86 |
+
def forward(self,
|
| 87 |
+
spec_clean: torch.Tensor,
|
| 88 |
+
spec_noise: torch.Tensor,
|
| 89 |
+
) -> torch.Tensor:
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
:param spec_clean: torch.complex, shape: [b, c, t, f]
|
| 93 |
+
:param spec_noise: torch.complex, shape: [b, c, t, f]
|
| 94 |
+
:return: lsnr, shape: [b, t]
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
lsnr, _, _ = local_snr(
|
| 98 |
+
spec_clean=spec_clean,
|
| 99 |
+
spec_noise=spec_noise,
|
| 100 |
+
n_frame=self.n_frame,
|
| 101 |
+
db=self.db,
|
| 102 |
+
)
|
| 103 |
+
# lsnr shape: [b, c, t]
|
| 104 |
+
lsnr = lsnr.clamp(self.min_local_snr, self.max_local_snr).squeeze(1)
|
| 105 |
+
# lsnr shape: [b, t]
|
| 106 |
+
return lsnr
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
sample_rate = 8000
|
| 111 |
+
nfft = 512
|
| 112 |
+
win_size = 512
|
| 113 |
+
hop_size = 256
|
| 114 |
+
window_fn = "hamming"
|
| 115 |
+
|
| 116 |
+
transform = torchaudio.transforms.Spectrogram(
|
| 117 |
+
n_fft=nfft,
|
| 118 |
+
win_length=win_size,
|
| 119 |
+
hop_length=hop_size,
|
| 120 |
+
power=None,
|
| 121 |
+
window_fn=torch.hamming_window if window_fn == "hamming" else torch.hann_window,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
noisy = torch.randn(size=(1, 16000), dtype=torch.float32)
|
| 125 |
+
|
| 126 |
+
spec = transform.forward(noisy)
|
| 127 |
+
spec = spec.permute(0, 2, 1)
|
| 128 |
+
spec = torch.unsqueeze(spec, dim=1)
|
| 129 |
+
print(f"spec.shape: {spec.shape}, spec.dtype: {spec.dtype}")
|
| 130 |
+
|
| 131 |
+
# [b, c, t, f]
|
| 132 |
+
# spec = torch.view_as_real(spec)
|
| 133 |
+
# [b, c, t, f, 2]
|
| 134 |
+
|
| 135 |
+
local = LocalSnrTarget(
|
| 136 |
+
sample_rate=sample_rate,
|
| 137 |
+
nfft=nfft,
|
| 138 |
+
win_size=win_size,
|
| 139 |
+
hop_size=hop_size,
|
| 140 |
+
n_frame=5,
|
| 141 |
+
min_local_snr=-15,
|
| 142 |
+
max_local_snr=30,
|
| 143 |
+
db=True,
|
| 144 |
+
)
|
| 145 |
+
lsnr_target = local.forward(spec, spec)
|
| 146 |
+
print(f"lsnr_target.shape: {lsnr_target.shape}")
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|