You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.9 KiB

  1. import torch
  2. from librosa.filters import mel as librosa_mel_fn
  3. from audio_processing import dynamic_range_compression
  4. from audio_processing import dynamic_range_decompression
  5. from stft import STFT
  6. class LinearNorm(torch.nn.Module):
  7. def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
  8. super(LinearNorm, self).__init__()
  9. self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
  10. torch.nn.init.xavier_uniform_(
  11. self.linear_layer.weight,
  12. gain=torch.nn.init.calculate_gain(w_init_gain))
  13. def forward(self, x):
  14. return self.linear_layer(x)
  15. class ConvNorm(torch.nn.Module):
  16. def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
  17. padding=None, dilation=1, bias=True, w_init_gain='linear'):
  18. super(ConvNorm, self).__init__()
  19. if padding is None:
  20. assert(kernel_size % 2 == 1)
  21. padding = int(dilation * (kernel_size - 1) / 2)
  22. self.conv = torch.nn.Conv1d(in_channels, out_channels,
  23. kernel_size=kernel_size, stride=stride,
  24. padding=padding, dilation=dilation,
  25. bias=bias)
  26. torch.nn.init.xavier_uniform_(
  27. self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
  28. def forward(self, signal):
  29. conv_signal = self.conv(signal)
  30. return conv_signal
  31. class TacotronSTFT(torch.nn.Module):
  32. def __init__(self, filter_length=1024, hop_length=256, win_length=1024,
  33. n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0,
  34. mel_fmax=8000.0):
  35. super(TacotronSTFT, self).__init__()
  36. self.n_mel_channels = n_mel_channels
  37. self.sampling_rate = sampling_rate
  38. self.stft_fn = STFT(filter_length, hop_length, win_length)
  39. mel_basis = librosa_mel_fn(
  40. sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax)
  41. mel_basis = torch.from_numpy(mel_basis).float()
  42. self.register_buffer('mel_basis', mel_basis)
  43. def spectral_normalize(self, magnitudes):
  44. output = dynamic_range_compression(magnitudes)
  45. return output
  46. def spectral_de_normalize(self, magnitudes):
  47. output = dynamic_range_decompression(magnitudes)
  48. return output
  49. def mel_spectrogram(self, y):
  50. """Computes mel-spectrograms from a batch of waves
  51. PARAMS
  52. ------
  53. y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
  54. RETURNS
  55. -------
  56. mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
  57. """
  58. assert(torch.min(y.data) >= -1)
  59. assert(torch.max(y.data) <= 1)
  60. magnitudes, phases = self.stft_fn.transform(y)
  61. magnitudes = magnitudes.data
  62. mel_output = torch.matmul(self.mel_basis, magnitudes)
  63. mel_output = self.spectral_normalize(mel_output)
  64. return mel_output