Fork of https://github.com/alokprasad/fastspeech_squeezewave to also fix denoising in squeezewave
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.

158 lines
6.0 KiB

  1. import torch
  2. import torch.nn.functional as F
  3. from torch.autograd import Variable
  4. import numpy as np
  5. from scipy.signal import get_window
  6. from librosa.util import pad_center, tiny
  7. from librosa.filters import mel as librosa_mel_fn
  8. from audio.audio_processing import dynamic_range_compression
  9. from audio.audio_processing import dynamic_range_decompression
  10. from audio.audio_processing import window_sumsquare
  11. class STFT(torch.nn.Module):
  12. """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft"""
  13. def __init__(self, filter_length=800, hop_length=200, win_length=800,
  14. window='hann'):
  15. super(STFT, self).__init__()
  16. self.filter_length = filter_length
  17. self.hop_length = hop_length
  18. self.win_length = win_length
  19. self.window = window
  20. self.forward_transform = None
  21. scale = self.filter_length / self.hop_length
  22. fourier_basis = np.fft.fft(np.eye(self.filter_length))
  23. cutoff = int((self.filter_length / 2 + 1))
  24. fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
  25. np.imag(fourier_basis[:cutoff, :])])
  26. forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
  27. inverse_basis = torch.FloatTensor(
  28. np.linalg.pinv(scale * fourier_basis).T[:, None, :])
  29. if window is not None:
  30. assert(filter_length >= win_length)
  31. # get window and zero center pad it to filter_length
  32. fft_window = get_window(window, win_length, fftbins=True)
  33. fft_window = pad_center(fft_window, filter_length)
  34. fft_window = torch.from_numpy(fft_window).float()
  35. # window the bases
  36. forward_basis *= fft_window
  37. inverse_basis *= fft_window
  38. self.register_buffer('forward_basis', forward_basis.float())
  39. self.register_buffer('inverse_basis', inverse_basis.float())
  40. def transform(self, input_data):
  41. num_batches = input_data.size(0)
  42. num_samples = input_data.size(1)
  43. self.num_samples = num_samples
  44. # similar to librosa, reflect-pad the input
  45. input_data = input_data.view(num_batches, 1, num_samples)
  46. input_data = F.pad(
  47. input_data.unsqueeze(1),
  48. (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0),
  49. mode='reflect')
  50. input_data = input_data.squeeze(1)
  51. forward_transform = F.conv1d(
  52. input_data.cuda(),
  53. Variable(self.forward_basis, requires_grad=False).cuda(),
  54. stride=self.hop_length,
  55. padding=0).cpu()
  56. cutoff = int((self.filter_length / 2) + 1)
  57. real_part = forward_transform[:, :cutoff, :]
  58. imag_part = forward_transform[:, cutoff:, :]
  59. magnitude = torch.sqrt(real_part**2 + imag_part**2)
  60. phase = torch.autograd.Variable(
  61. torch.atan2(imag_part.data, real_part.data))
  62. return magnitude, phase
  63. def inverse(self, magnitude, phase):
  64. recombine_magnitude_phase = torch.cat(
  65. [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1)
  66. inverse_transform = F.conv_transpose1d(
  67. recombine_magnitude_phase,
  68. Variable(self.inverse_basis, requires_grad=False),
  69. stride=self.hop_length,
  70. padding=0)
  71. if self.window is not None:
  72. window_sum = window_sumsquare(
  73. self.window, magnitude.size(-1), hop_length=self.hop_length,
  74. win_length=self.win_length, n_fft=self.filter_length,
  75. dtype=np.float32)
  76. # remove modulation effects
  77. approx_nonzero_indices = torch.from_numpy(
  78. np.where(window_sum > tiny(window_sum))[0])
  79. window_sum = torch.autograd.Variable(
  80. torch.from_numpy(window_sum), requires_grad=False)
  81. window_sum = window_sum.cuda() if magnitude.is_cuda else window_sum
  82. inverse_transform[:, :,
  83. approx_nonzero_indices] /= window_sum[approx_nonzero_indices]
  84. # scale by hop ratio
  85. inverse_transform *= float(self.filter_length) / self.hop_length
  86. inverse_transform = inverse_transform[:, :, int(self.filter_length/2):]
  87. inverse_transform = inverse_transform[:,
  88. :, :-int(self.filter_length/2):]
  89. return inverse_transform
  90. def forward(self, input_data):
  91. self.magnitude, self.phase = self.transform(input_data)
  92. reconstruction = self.inverse(self.magnitude, self.phase)
  93. return reconstruction
  94. class TacotronSTFT(torch.nn.Module):
  95. def __init__(self, filter_length=1024, hop_length=256, win_length=1024,
  96. n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0,
  97. mel_fmax=8000.0):
  98. super(TacotronSTFT, self).__init__()
  99. self.n_mel_channels = n_mel_channels
  100. self.sampling_rate = sampling_rate
  101. self.stft_fn = STFT(filter_length, hop_length, win_length)
  102. mel_basis = librosa_mel_fn(
  103. sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax)
  104. mel_basis = torch.from_numpy(mel_basis).float()
  105. self.register_buffer('mel_basis', mel_basis)
  106. def spectral_normalize(self, magnitudes):
  107. output = dynamic_range_compression(magnitudes)
  108. return output
  109. def spectral_de_normalize(self, magnitudes):
  110. output = dynamic_range_decompression(magnitudes)
  111. return output
  112. def mel_spectrogram(self, y):
  113. """Computes mel-spectrograms from a batch of waves
  114. PARAMS
  115. ------
  116. y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
  117. RETURNS
  118. -------
  119. mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
  120. """
  121. assert(torch.min(y.data) >= -1)
  122. assert(torch.max(y.data) <= 1)
  123. magnitudes, phases = self.stft_fn.transform(y)
  124. magnitudes = magnitudes.data
  125. mel_output = torch.matmul(self.mel_basis, magnitudes)
  126. mel_output = self.spectral_normalize(mel_output)
  127. return mel_output