audio.py 4.0 KB

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