Spaces:
Sleeping
Sleeping
File size: 12,222 Bytes
957e2dc |
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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
import math
import torch
import pandas as pd
import numpy as np
from typing import List, Union
from pesq import pesq
from pystoi import stoi
from tqdm import tqdm
from src.data import DataProperties
from src.utils.plotting import tensor_to_np
from src.models.speech import Wav2Vec2, GreedyCTCDecoder
################################################################################
# Utilities for analyzing attack results
################################################################################
@torch.no_grad()
def run_perceptual_evaluation(x: torch.Tensor,
x_adv: torch.Tensor,
batch_size: int = 1,
device: Union[str, torch.cuda.device] = 'cpu',
tag: str = None,
**kwargs
):
"""
Compute perceptual quality metrics on pairs of clean and adversarial audio
Parameters
----------
x (Tensor): shape
x_adv (Tensor): shape
batch_size (int):
device (str):
Returns
-------
"""
# check for compatible audio dimensions
assert x.ndim == x_adv.ndim
# require batch dimension
assert x.ndim >= 2
n_batch = x.shape[0]
# store results
results = {}
# name results
tag = '' if tag is None else f'{tag}-'
############################################################################
# WAVEFORM P-NORM DISTANCE
############################################################################
# if dimensions match, measure L-2 and L-inf distance between waveforms
if x.shape == x_adv.shape:
reduce_dims = tuple(range(1, x.ndim))
l2 = (x - x_adv).norm(
p=2, dim=reduce_dims).flatten().tolist()
linf = (x - x_adv).norm(
p=float('inf'), dim=reduce_dims).flatten().tolist()
results = {
**results,
tag + 'L2-Waveform': l2,
tag + 'Linf-Waveform': linf
}
############################################################################
# PESQ OBJECTIVE MEASURE (DEPRECATED)
############################################################################
assert DataProperties.get('sample_rate') in [16000, 8000], \
f"Cannot perform PESQ evaluation with sample rate " \
f"{DataProperties.get('sample_rate')}Hz; must be 8000Hz or 16000Hz"
wb_scores, nb_scores = [], []
for i in tqdm(range(n_batch), desc='computing PESQ scores'):
wb_scores.append(
pesq(DataProperties.get('sample_rate'),
tensor_to_np(x[i]).flatten(),
tensor_to_np(x_adv[i]).flatten(),
'wb')
)
nb_scores.append(
pesq(DataProperties.get('sample_rate'),
tensor_to_np(x[i]).flatten(),
tensor_to_np(x_adv[i]).flatten(),
'nb')
)
results = {
**results,
tag + 'PESQ-Wideband': wb_scores,
tag + 'PESQ-Narrowband': nb_scores,
}
############################################################################
# STOI OBJECTIVE MEASURE (DEPRECATED)
############################################################################
cl_scores, ex_scores = [], []
for i in tqdm(range(n_batch), desc='computing STOI scores'):
cl_scores.append(
stoi(tensor_to_np(x[i]).flatten(),
tensor_to_np(x_adv[i]).flatten(),
DataProperties.get('sample_rate'),
extended=False)
)
ex_scores.append(
stoi(tensor_to_np(x[i]).flatten(),
tensor_to_np(x_adv[i]).flatten(),
DataProperties.get('sample_rate'),
extended=True)
)
results = {
**results,
tag + 'STOI-Extended': cl_scores,
tag + 'STOI-Classical': ex_scores,
}
############################################################################
# BSS-EVAL SIGNAL METRICS
############################################################################
si_sdr, sd_sdr, snr, srr = [], [], [], []
for i in tqdm(range(n_batch), desc='computing BSS-EVAL metrics'):
si_sdr_i, sd_sdr_i, snr_i, srr_i = _bss_eval(
tensor_to_np(x_adv[i]).flatten(),
tensor_to_np(x[i]).flatten())
si_sdr.append(si_sdr_i)
sd_sdr.append(sd_sdr_i)
snr.append(snr_i)
srr.append(srr_i)
results = {
**results,
tag + 'SI-SDR': si_sdr,
tag + 'SD-SDR': sd_sdr,
tag + 'SNR': snr,
tag + 'SRR': srr
}
############################################################################
# ASR TRANSCRIPTION METRICS
############################################################################
# initialize ASR model / decoder
model = Wav2Vec2()
decoder = GreedyCTCDecoder(labels=model.labels)
# obtain delimiter token
delimiter = decoder.get_labels()[decoder.get_sep_idx()]
# move model to given device
model.to(device)
# store original and adversarial transcriptions
transcriptions = []
transcriptions_adv = []
n_batches = math.ceil(len(x) / batch_size)
for i in tqdm(range(n_batches), desc='computing WER/CER'):
# move batches to device and pass to model
x_batch = x[batch_size*i:batch_size*(i+1)].to(device)
x_adv_batch = x_adv[batch_size*i:batch_size*(i+1)].to(device)
emit_batch = model(x_batch)
emit_adv_batch = model(x_adv_batch)
# decode sequence probability emissions to obtain string transcriptions
transcriptions.extend(decoder(emit_batch)[0])
transcriptions_adv.extend(decoder(emit_adv_batch)[0])
# ASR WER
wer = compute_wer(transcriptions, transcriptions_adv, delimiter)
# ASR CER
cer = compute_cer(transcriptions, transcriptions_adv, delimiter)
results = {
**results,
tag + 'ASR-WER': wer,
tag + 'ASR-CER': cer,
}
return results
def compute_wer(
reference: List[str],
transcription: List[str],
delimiter: str = ' '):
"""
Compute average word error rate (WER) between string transcriptions.
WER = (Sw + Dw + Iw) / Nw
where:
Sw is the number of words substituted,
Dw is the number of words deleted,
Iw is the number of words inserted,
Nw is the number of words in the reference
Parameters
----------
Returns
-------
"""
assert len(reference) == len(transcription)
# for each reference-transcription pair in batch, count errors of each of
# the four types as well as total word count
total_edit_dist = 0
total_ref_len = 0
for r, t in zip(reference, transcription):
edit_dist, ref_len = _word_errors(r, t, delimiter=delimiter)
if ref_len == 0:
raise ValueError("Reference sentences must nonzero word count")
total_edit_dist += edit_dist
total_ref_len += ref_len
wer = float(total_edit_dist) / total_ref_len
return wer
def compute_cer(
reference: List[str],
transcription: List[str],
delimiter: str = ' ',
remove_delimiter: bool = False):
"""
Compute average character error rate (CER) between string transcriptions.
WER = (Sc + Dc + Ic) / Nc
where:
Sc is the number of characters substituted,
Dc is the number of characters deleted,
Ic is the number of characters inserted,
Nc is the number of characters in the reference
Parameters
----------
Returns
-------
"""
assert len(reference) == len(transcription)
# for each reference-transcription pair in batch, count errors of each of
# the four types as well as total character count
total_edit_dist = 0
total_ref_len = 0
for r, t in zip(reference, transcription):
edit_dist, ref_len = _char_errors(r,
t,
delimiter,
remove_delimiter)
if ref_len == 0:
raise ValueError("Reference sentences must nonzero character count")
total_edit_dist += edit_dist
total_ref_len += ref_len
cer = float(total_edit_dist) / total_ref_len
return cer
def _word_errors(reference: str, transcription: str, delimiter: str = ' '):
"""
Compute the Levenshtein distance between reference and transcription
sequences at word level.
"""
reference = reference.lower()
transcription = transcription.lower()
ref_words = reference.split(delimiter)
tra_words = transcription.split(delimiter)
edit_distance = _levenshtein_distance(ref_words, tra_words)
return float(edit_distance), len(ref_words)
def _char_errors(reference: str,
transcription: str,
delimiter: str = ' ',
remove_delimiter: bool = False
):
"""
Compute the Levenshtein distance between reference and transcription
sequences at word level.
"""
reference = reference.lower()
transcription = transcription.lower()
join_char = delimiter
if remove_delimiter:
join_char = ''
reference = join_char.join(filter(None, reference.split(delimiter)))
transcription = join_char.join(filter(None, transcription.split(delimiter)))
edit_distance = _levenshtein_distance(reference, transcription)
return float(edit_distance), len(reference)
def _levenshtein_distance(reference: Union[List[str], str],
transcription: Union[List[str], str]):
"""Levenshtein distance is a string metric for measuring the difference
between two sequences. Informally, the levenshtein disctance is defined as
the minimum number of single-character edits (substitutions, insertions or
deletions) required to change one word into the other. We can naturally
extend the edits to word level when calculate levenshtein disctance for
two sentences.
"""
m = len(reference)
n = len(transcription)
# special cases
if reference == transcription:
return 0
if m == 0:
return n
if n == 0:
return m
if m < n:
reference, transcription = transcription, reference
m, n = n, m
# use O(min(m, n)) space
distance = np.zeros((2, n + 1), dtype=np.int32)
# initialize distance matrix
for j in range(0, n + 1):
distance[0][j] = j
# calculate Levenshtein distance
for i in range(1, m + 1):
prev_row_idx = (i - 1) % 2
cur_row_idx = i % 2
distance[cur_row_idx][0] = i
for j in range(1, n + 1):
if reference[i - 1] == transcription[j - 1]:
distance[cur_row_idx][j] = distance[prev_row_idx][j - 1]
else:
s_num = distance[prev_row_idx][j - 1] + 1
i_num = distance[cur_row_idx][j - 1] + 1
d_num = distance[prev_row_idx][j] + 1
distance[cur_row_idx][j] = min(s_num, i_num, d_num)
return distance[m % 2][n]
def _bss_eval(x, x_ref):
x_ref_energy = (x_ref ** 2).sum()
alpha = (x_ref @ x / x_ref_energy)
e_true = x_ref
e_res = x - e_true
signal = (e_true ** 2).sum()
noise = (e_res ** 2).sum()
snr = 10 * np.log10(signal / noise)
e_true = x_ref * alpha
e_res = x - e_true
signal = (e_true ** 2).sum()
noise = (e_res ** 2).sum()
si_sdr = 10 * np.log10(signal / noise)
srr = -10 * np.log10((1 - (1/alpha)) ** 2)
sd_sdr = snr + 10 * np.log10(alpha ** 2)
return si_sdr, sd_sdr, snr, srr
|