audio.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import os
  2. from functools import lru_cache
  3. from typing import Optional, Union
  4. import ffmpeg
  5. import numpy as np
  6. import torch
  7. import torch.nn.functional as F
  8. from .utils import exact_div
  9. # hard-coded audio hyperparameters
  10. SAMPLE_RATE = 16000
  11. N_FFT = 400
  12. N_MELS = 80
  13. HOP_LENGTH = 160
  14. CHUNK_LENGTH = 30
  15. N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE # 480000 samples in a 30-second chunk
  16. N_FRAMES = exact_div(N_SAMPLES, HOP_LENGTH) # 3000 frames in a mel spectrogram input
  17. N_SAMPLES_PER_TOKEN = HOP_LENGTH * 2 # the initial convolutions has stride 2
  18. FRAMES_PER_SECOND = exact_div(SAMPLE_RATE, HOP_LENGTH) # 10ms per audio frame
  19. TOKENS_PER_SECOND = exact_div(SAMPLE_RATE, N_SAMPLES_PER_TOKEN) # 20ms per audio token
  20. def load_audio(file: str, sr: int = SAMPLE_RATE):
  21. """
  22. Open an audio file and read as mono waveform, resampling as necessary
  23. Parameters
  24. ----------
  25. file: str
  26. The audio file to open
  27. sr: int
  28. The sample rate to resample the audio if necessary
  29. Returns
  30. -------
  31. A NumPy array containing the audio waveform, in float32 dtype.
  32. """
  33. try:
  34. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  35. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  36. out, _ = (
  37. ffmpeg.input(file, threads=0)
  38. .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr)
  39. .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
  40. )
  41. except ffmpeg.Error as e:
  42. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
  43. return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
  44. def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1):
  45. """
  46. Pad or trim the audio array to N_SAMPLES, as expected by the encoder.
  47. """
  48. if torch.is_tensor(array):
  49. if array.shape[axis] > length:
  50. array = array.index_select(
  51. dim=axis, index=torch.arange(length, device=array.device)
  52. )
  53. if array.shape[axis] < length:
  54. pad_widths = [(0, 0)] * array.ndim
  55. pad_widths[axis] = (0, length - array.shape[axis])
  56. array = F.pad(array, [pad for sizes in pad_widths[::-1] for pad in sizes])
  57. else:
  58. if array.shape[axis] > length:
  59. array = array.take(indices=range(length), axis=axis)
  60. if array.shape[axis] < length:
  61. pad_widths = [(0, 0)] * array.ndim
  62. pad_widths[axis] = (0, length - array.shape[axis])
  63. array = np.pad(array, pad_widths)
  64. return array
  65. @lru_cache(maxsize=None)
  66. def mel_filters(device, n_mels: int = N_MELS) -> torch.Tensor:
  67. """
  68. load the mel filterbank matrix for projecting STFT into a Mel spectrogram.
  69. Allows decoupling librosa dependency; saved using:
  70. np.savez_compressed(
  71. "mel_filters.npz",
  72. mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80),
  73. )
  74. """
  75. assert n_mels == 80, f"Unsupported n_mels: {n_mels}"
  76. with np.load(
  77. os.path.join(os.path.dirname(__file__), "assets", "mel_filters.npz")
  78. ) as f:
  79. return torch.from_numpy(f[f"mel_{n_mels}"]).to(device)
  80. def log_mel_spectrogram(
  81. audio: Union[str, np.ndarray, torch.Tensor],
  82. n_mels: int = N_MELS,
  83. padding: int = 0,
  84. device: Optional[Union[str, torch.device]] = None,
  85. ):
  86. """
  87. Compute the log-Mel spectrogram of
  88. Parameters
  89. ----------
  90. audio: Union[str, np.ndarray, torch.Tensor], shape = (*)
  91. The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz
  92. n_mels: int
  93. The number of Mel-frequency filters, only 80 is supported
  94. padding: int
  95. Number of zero samples to pad to the right
  96. device: Optional[Union[str, torch.device]]
  97. If given, the audio tensor is moved to this device before STFT
  98. Returns
  99. -------
  100. torch.Tensor, shape = (80, n_frames)
  101. A Tensor that contains the Mel spectrogram
  102. """
  103. if not torch.is_tensor(audio):
  104. if isinstance(audio, str):
  105. audio = load_audio(audio)
  106. audio = torch.from_numpy(audio)
  107. if device is not None:
  108. audio = audio.to(device)
  109. if padding > 0:
  110. audio = F.pad(audio, (0, padding))
  111. window = torch.hann_window(N_FFT).to(audio.device)
  112. stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True)
  113. magnitudes = stft[..., :-1].abs() ** 2
  114. filters = mel_filters(audio.device, n_mels)
  115. mel_spec = filters @ magnitudes
  116. log_spec = torch.clamp(mel_spec, min=1e-10).log10()
  117. log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
  118. log_spec = (log_spec + 4.0) / 4.0
  119. return log_spec