-
Notifications
You must be signed in to change notification settings - Fork 317
/
audio.py
133 lines (98 loc) · 4.5 KB
/
audio.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
class CMVN(torch.jit.ScriptModule):
__constants__ = ["mode", "dim", "eps"]
def __init__(self, mode="global", dim=2, eps=1e-10):
# `torchaudio.load()` loads audio with shape [channel, feature_dim, time]
# so perform normalization on dim=2 by default
super(CMVN, self).__init__()
if mode != "global":
raise NotImplementedError(
"Only support global mean variance normalization.")
self.mode = mode
self.dim = dim
self.eps = eps
@torch.jit.script_method
def forward(self, x):
if self.mode == "global":
return (x - x.mean(self.dim, keepdim=True)) / (self.eps + x.std(self.dim, keepdim=True))
def extra_repr(self):
return "mode={}, dim={}, eps={}".format(self.mode, self.dim, self.eps)
class Delta(torch.jit.ScriptModule):
__constants__ = ["order", "window_size", "padding"]
def __init__(self, order=1, window_size=2):
# Reference:
# https://kaldi-asr.org/doc/feature-functions_8cc_source.html
# https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_audio.py
super(Delta, self).__init__()
self.order = order
self.window_size = window_size
filters = self._create_filters(order, window_size)
self.register_buffer("filters", filters)
self.padding = (0, (filters.shape[-1] - 1) // 2)
@torch.jit.script_method
def forward(self, x):
# Unsqueeze batch dim
x = x.unsqueeze(0)
return F.conv2d(x, weight=self.filters, padding=self.padding)[0]
# TODO(WindQAQ): find more elegant way to create `scales`
def _create_filters(self, order, window_size):
scales = [[1.0]]
for i in range(1, order + 1):
prev_offset = (len(scales[i-1]) - 1) // 2
curr_offset = prev_offset + window_size
curr = [0] * (len(scales[i-1]) + 2 * window_size)
normalizer = 0.0
for j in range(-window_size, window_size + 1):
normalizer += j * j
for k in range(-prev_offset, prev_offset + 1):
curr[j+k+curr_offset] += (j * scales[i-1][k+prev_offset])
curr = [x / normalizer for x in curr]
scales.append(curr)
max_len = len(scales[-1])
for i, scale in enumerate(scales[:-1]):
padding = (max_len - len(scale)) // 2
scales[i] = [0] * padding + scale + [0] * padding
return torch.tensor(scales).unsqueeze(1).unsqueeze(1)
def extra_repr(self):
return "order={}, window_size={}".format(self.order, self.window_size)
class Postprocess(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
# [channel, feature_dim, time] -> [time, channel, feature_dim]
x = x.permute(2, 0, 1)
# [time, channel, feature_dim] -> [time, feature_dim * channel]
return x.reshape(x.size(0), -1).detach()
# TODO(Windqaq): make this scriptable
class ExtractAudioFeature(nn.Module):
def __init__(self, mode="fbank", num_mel_bins=40, **kwargs):
super(ExtractAudioFeature, self).__init__()
self.mode = mode
self.extract_fn = torchaudio.compliance.kaldi.fbank if mode == "fbank" else torchaudio.compliance.kaldi.mfcc
self.num_mel_bins = num_mel_bins
self.kwargs = kwargs
def forward(self, filepath):
waveform, sample_rate = torchaudio.load(filepath)
y = self.extract_fn(waveform,
num_mel_bins=self.num_mel_bins,
channel=-1,
sample_frequency=sample_rate,
**self.kwargs)
return y.transpose(0, 1).unsqueeze(0).detach()
def extra_repr(self):
return "mode={}, num_mel_bins={}".format(self.mode, self.num_mel_bins)
def create_transform(audio_config):
feat_type = audio_config.pop("feat_type")
feat_dim = audio_config.pop("feat_dim")
delta_order = audio_config.pop("delta_order", 0)
delta_window_size = audio_config.pop("delta_window_size", 2)
apply_cmvn = audio_config.pop("apply_cmvn")
transforms = [ExtractAudioFeature(feat_type, feat_dim, **audio_config)]
if delta_order >= 1:
transforms.append(Delta(delta_order, delta_window_size))
if apply_cmvn:
transforms.append(CMVN())
transforms.append(Postprocess())
return nn.Sequential(*transforms), feat_dim * (delta_order + 1)