frontend.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- encoding: utf-8 -*-
  2. from pathlib import Path
  3. from typing import Any, Dict, Iterable, List, NamedTuple, Set, Tuple, Union
  4. import copy
  5. import numpy as np
  6. import kaldi_native_fbank as knf
  7. root_dir = Path(__file__).resolve().parent
  8. logger_initialized = {}
  9. class WavFrontend:
  10. """Conventional frontend structure for ASR."""
  11. def __init__(
  12. self,
  13. cmvn_file: str = None,
  14. fs: int = 16000,
  15. window: str = "hamming",
  16. n_mels: int = 80,
  17. frame_length: int = 25,
  18. frame_shift: int = 10,
  19. lfr_m: int = 1,
  20. lfr_n: int = 1,
  21. dither: float = 1.0,
  22. **kwargs,
  23. ) -> None:
  24. opts = knf.FbankOptions()
  25. opts.frame_opts.samp_freq = fs
  26. opts.frame_opts.dither = dither
  27. opts.frame_opts.window_type = window
  28. opts.frame_opts.frame_shift_ms = float(frame_shift)
  29. opts.frame_opts.frame_length_ms = float(frame_length)
  30. opts.mel_opts.num_bins = n_mels
  31. opts.energy_floor = 0
  32. opts.frame_opts.snip_edges = True
  33. opts.mel_opts.debug_mel = False
  34. self.opts = opts
  35. self.lfr_m = lfr_m
  36. self.lfr_n = lfr_n
  37. self.cmvn_file = cmvn_file
  38. if self.cmvn_file:
  39. self.cmvn = self.load_cmvn()
  40. self.fbank_fn = None
  41. self.fbank_beg_idx = 0
  42. self.reset_status()
  43. def fbank(self, waveform: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  44. waveform = waveform * (1 << 15)
  45. self.fbank_fn = knf.OnlineFbank(self.opts)
  46. self.fbank_fn.accept_waveform(self.opts.frame_opts.samp_freq, waveform.tolist())
  47. frames = self.fbank_fn.num_frames_ready
  48. mat = np.empty([frames, self.opts.mel_opts.num_bins])
  49. for i in range(frames):
  50. mat[i, :] = self.fbank_fn.get_frame(i)
  51. feat = mat.astype(np.float32)
  52. feat_len = np.array(mat.shape[0]).astype(np.int32)
  53. return feat, feat_len
  54. def fbank_online(self, waveform: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  55. waveform = waveform * (1 << 15)
  56. # self.fbank_fn = knf.OnlineFbank(self.opts)
  57. self.fbank_fn.accept_waveform(self.opts.frame_opts.samp_freq, waveform.tolist())
  58. frames = self.fbank_fn.num_frames_ready
  59. mat = np.empty([frames, self.opts.mel_opts.num_bins])
  60. for i in range(self.fbank_beg_idx, frames):
  61. mat[i, :] = self.fbank_fn.get_frame(i)
  62. # self.fbank_beg_idx += (frames-self.fbank_beg_idx)
  63. feat = mat.astype(np.float32)
  64. feat_len = np.array(mat.shape[0]).astype(np.int32)
  65. return feat, feat_len
  66. def reset_status(self):
  67. self.fbank_fn = knf.OnlineFbank(self.opts)
  68. self.fbank_beg_idx = 0
  69. def lfr_cmvn(self, feat: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  70. if self.lfr_m != 1 or self.lfr_n != 1:
  71. feat = self.apply_lfr(feat, self.lfr_m, self.lfr_n)
  72. if self.cmvn_file:
  73. feat = self.apply_cmvn(feat)
  74. feat_len = np.array(feat.shape[0]).astype(np.int32)
  75. return feat, feat_len
  76. @staticmethod
  77. def apply_lfr(inputs: np.ndarray, lfr_m: int, lfr_n: int) -> np.ndarray:
  78. LFR_inputs = []
  79. T = inputs.shape[0]
  80. T_lfr = int(np.ceil(T / lfr_n))
  81. left_padding = np.tile(inputs[0], ((lfr_m - 1) // 2, 1))
  82. inputs = np.vstack((left_padding, inputs))
  83. T = T + (lfr_m - 1) // 2
  84. for i in range(T_lfr):
  85. if lfr_m <= T - i * lfr_n:
  86. LFR_inputs.append((inputs[i * lfr_n : i * lfr_n + lfr_m]).reshape(1, -1))
  87. else:
  88. # process last LFR frame
  89. num_padding = lfr_m - (T - i * lfr_n)
  90. frame = inputs[i * lfr_n :].reshape(-1)
  91. for _ in range(num_padding):
  92. frame = np.hstack((frame, inputs[-1]))
  93. LFR_inputs.append(frame)
  94. LFR_outputs = np.vstack(LFR_inputs).astype(np.float32)
  95. return LFR_outputs
  96. def apply_cmvn(self, inputs: np.ndarray) -> np.ndarray:
  97. """
  98. Apply CMVN with mvn data
  99. """
  100. frame, dim = inputs.shape
  101. means = np.tile(self.cmvn[0:1, :dim], (frame, 1))
  102. vars = np.tile(self.cmvn[1:2, :dim], (frame, 1))
  103. inputs = (inputs + means) * vars
  104. return inputs
  105. def load_cmvn(
  106. self,
  107. ) -> np.ndarray:
  108. with open(self.cmvn_file, "r", encoding="utf-8") as f:
  109. lines = f.readlines()
  110. means_list = []
  111. vars_list = []
  112. for i in range(len(lines)):
  113. line_item = lines[i].split()
  114. if line_item[0] == "<AddShift>":
  115. line_item = lines[i + 1].split()
  116. if line_item[0] == "<LearnRateCoef>":
  117. add_shift_line = line_item[3 : (len(line_item) - 1)]
  118. means_list = list(add_shift_line)
  119. continue
  120. elif line_item[0] == "<Rescale>":
  121. line_item = lines[i + 1].split()
  122. if line_item[0] == "<LearnRateCoef>":
  123. rescale_line = line_item[3 : (len(line_item) - 1)]
  124. vars_list = list(rescale_line)
  125. continue
  126. means = np.array(means_list).astype(np.float64)
  127. vars = np.array(vars_list).astype(np.float64)
  128. cmvn = np.array([means, vars])
  129. return cmvn
  130. class WavFrontendOnline(WavFrontend):
  131. def __init__(self, **kwargs):
  132. super().__init__(**kwargs)
  133. # self.fbank_fn = knf.OnlineFbank(self.opts)
  134. # add variables
  135. self.frame_sample_length = int(
  136. self.opts.frame_opts.frame_length_ms * self.opts.frame_opts.samp_freq / 1000
  137. )
  138. self.frame_shift_sample_length = int(
  139. self.opts.frame_opts.frame_shift_ms * self.opts.frame_opts.samp_freq / 1000
  140. )
  141. self.waveform = None
  142. self.reserve_waveforms = None
  143. self.input_cache = None
  144. self.lfr_splice_cache = []
  145. @staticmethod
  146. # inputs has catted the cache
  147. def apply_lfr(
  148. inputs: np.ndarray, lfr_m: int, lfr_n: int, is_final: bool = False
  149. ) -> Tuple[np.ndarray, np.ndarray, int]:
  150. """
  151. Apply lfr with data
  152. """
  153. LFR_inputs = []
  154. T = inputs.shape[0] # include the right context
  155. T_lfr = int(
  156. np.ceil((T - (lfr_m - 1) // 2) / lfr_n)
  157. ) # minus the right context: (lfr_m - 1) // 2
  158. splice_idx = T_lfr
  159. for i in range(T_lfr):
  160. if lfr_m <= T - i * lfr_n:
  161. LFR_inputs.append((inputs[i * lfr_n : i * lfr_n + lfr_m]).reshape(1, -1))
  162. else: # process last LFR frame
  163. if is_final:
  164. num_padding = lfr_m - (T - i * lfr_n)
  165. frame = (inputs[i * lfr_n :]).reshape(-1)
  166. for _ in range(num_padding):
  167. frame = np.hstack((frame, inputs[-1]))
  168. LFR_inputs.append(frame)
  169. else:
  170. # update splice_idx and break the circle
  171. splice_idx = i
  172. break
  173. splice_idx = min(T - 1, splice_idx * lfr_n)
  174. lfr_splice_cache = inputs[splice_idx:, :]
  175. LFR_outputs = np.vstack(LFR_inputs)
  176. return LFR_outputs.astype(np.float32), lfr_splice_cache, splice_idx
  177. @staticmethod
  178. def compute_frame_num(
  179. sample_length: int, frame_sample_length: int, frame_shift_sample_length: int
  180. ) -> int:
  181. frame_num = int((sample_length - frame_sample_length) / frame_shift_sample_length + 1)
  182. return frame_num if frame_num >= 1 and sample_length >= frame_sample_length else 0
  183. def fbank(
  184. self, input: np.ndarray, input_lengths: np.ndarray
  185. ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
  186. self.fbank_fn = knf.OnlineFbank(self.opts)
  187. batch_size = input.shape[0]
  188. if self.input_cache is None:
  189. self.input_cache = np.empty((batch_size, 0), dtype=np.float32)
  190. input = np.concatenate((self.input_cache, input), axis=1)
  191. frame_num = self.compute_frame_num(
  192. input.shape[-1], self.frame_sample_length, self.frame_shift_sample_length
  193. )
  194. # update self.in_cache
  195. self.input_cache = input[
  196. :, -(input.shape[-1] - frame_num * self.frame_shift_sample_length) :
  197. ]
  198. waveforms = np.empty(0, dtype=np.float32)
  199. feats_pad = np.empty(0, dtype=np.float32)
  200. feats_lens = np.empty(0, dtype=np.int32)
  201. if frame_num:
  202. waveforms = []
  203. feats = []
  204. feats_lens = []
  205. for i in range(batch_size):
  206. waveform = input[i]
  207. waveforms.append(
  208. waveform[
  209. : (
  210. (frame_num - 1) * self.frame_shift_sample_length
  211. + self.frame_sample_length
  212. )
  213. ]
  214. )
  215. waveform = waveform * (1 << 15)
  216. self.fbank_fn.accept_waveform(self.opts.frame_opts.samp_freq, waveform.tolist())
  217. frames = self.fbank_fn.num_frames_ready
  218. mat = np.empty([frames, self.opts.mel_opts.num_bins])
  219. for i in range(frames):
  220. mat[i, :] = self.fbank_fn.get_frame(i)
  221. feat = mat.astype(np.float32)
  222. feat_len = np.array(mat.shape[0]).astype(np.int32)
  223. feats.append(feat)
  224. feats_lens.append(feat_len)
  225. waveforms = np.stack(waveforms)
  226. feats_lens = np.array(feats_lens)
  227. feats_pad = np.array(feats)
  228. self.fbanks = feats_pad
  229. self.fbanks_lens = copy.deepcopy(feats_lens)
  230. return waveforms, feats_pad, feats_lens
  231. def get_fbank(self) -> Tuple[np.ndarray, np.ndarray]:
  232. return self.fbanks, self.fbanks_lens
  233. def lfr_cmvn(
  234. self, input: np.ndarray, input_lengths: np.ndarray, is_final: bool = False
  235. ) -> Tuple[np.ndarray, np.ndarray, List[int]]:
  236. batch_size = input.shape[0]
  237. feats = []
  238. feats_lens = []
  239. lfr_splice_frame_idxs = []
  240. for i in range(batch_size):
  241. mat = input[i, : input_lengths[i], :]
  242. lfr_splice_frame_idx = -1
  243. if self.lfr_m != 1 or self.lfr_n != 1:
  244. # update self.lfr_splice_cache in self.apply_lfr
  245. mat, self.lfr_splice_cache[i], lfr_splice_frame_idx = self.apply_lfr(
  246. mat, self.lfr_m, self.lfr_n, is_final
  247. )
  248. if self.cmvn_file is not None:
  249. mat = self.apply_cmvn(mat)
  250. feat_length = mat.shape[0]
  251. feats.append(mat)
  252. feats_lens.append(feat_length)
  253. lfr_splice_frame_idxs.append(lfr_splice_frame_idx)
  254. feats_lens = np.array(feats_lens)
  255. feats_pad = np.array(feats)
  256. return feats_pad, feats_lens, lfr_splice_frame_idxs
  257. def extract_fbank(
  258. self, input: np.ndarray, input_lengths: np.ndarray, is_final: bool = False
  259. ) -> Tuple[np.ndarray, np.ndarray]:
  260. batch_size = input.shape[0]
  261. assert (
  262. batch_size == 1
  263. ), "we support to extract feature online only when the batch size is equal to 1 now"
  264. waveforms, feats, feats_lengths = self.fbank(input, input_lengths) # input shape: B T D
  265. if feats.shape[0]:
  266. self.waveforms = (
  267. waveforms
  268. if self.reserve_waveforms is None
  269. else np.concatenate((self.reserve_waveforms, waveforms), axis=1)
  270. )
  271. if not self.lfr_splice_cache:
  272. for i in range(batch_size):
  273. self.lfr_splice_cache.append(
  274. np.expand_dims(feats[i][0, :], axis=0).repeat((self.lfr_m - 1) // 2, axis=0)
  275. )
  276. if feats_lengths[0] + self.lfr_splice_cache[0].shape[0] >= self.lfr_m:
  277. lfr_splice_cache_np = np.stack(self.lfr_splice_cache) # B T D
  278. feats = np.concatenate((lfr_splice_cache_np, feats), axis=1)
  279. feats_lengths += lfr_splice_cache_np[0].shape[0]
  280. frame_from_waveforms = int(
  281. (self.waveforms.shape[1] - self.frame_sample_length)
  282. / self.frame_shift_sample_length
  283. + 1
  284. )
  285. minus_frame = (self.lfr_m - 1) // 2 if self.reserve_waveforms is None else 0
  286. feats, feats_lengths, lfr_splice_frame_idxs = self.lfr_cmvn(
  287. feats, feats_lengths, is_final
  288. )
  289. if self.lfr_m == 1:
  290. self.reserve_waveforms = None
  291. else:
  292. reserve_frame_idx = lfr_splice_frame_idxs[0] - minus_frame
  293. # print('reserve_frame_idx: ' + str(reserve_frame_idx))
  294. # print('frame_frame: ' + str(frame_from_waveforms))
  295. self.reserve_waveforms = self.waveforms[
  296. :,
  297. reserve_frame_idx
  298. * self.frame_shift_sample_length : frame_from_waveforms
  299. * self.frame_shift_sample_length,
  300. ]
  301. sample_length = (
  302. frame_from_waveforms - 1
  303. ) * self.frame_shift_sample_length + self.frame_sample_length
  304. self.waveforms = self.waveforms[:, :sample_length]
  305. else:
  306. # update self.reserve_waveforms and self.lfr_splice_cache
  307. self.reserve_waveforms = self.waveforms[
  308. :, : -(self.frame_sample_length - self.frame_shift_sample_length)
  309. ]
  310. for i in range(batch_size):
  311. self.lfr_splice_cache[i] = np.concatenate(
  312. (self.lfr_splice_cache[i], feats[i]), axis=0
  313. )
  314. return np.empty(0, dtype=np.float32), feats_lengths
  315. else:
  316. if is_final:
  317. self.waveforms = (
  318. waveforms if self.reserve_waveforms is None else self.reserve_waveforms
  319. )
  320. feats = np.stack(self.lfr_splice_cache)
  321. feats_lengths = np.zeros(batch_size, dtype=np.int32) + feats.shape[1]
  322. feats, feats_lengths, _ = self.lfr_cmvn(feats, feats_lengths, is_final)
  323. if is_final:
  324. self.cache_reset()
  325. return feats, feats_lengths
  326. def get_waveforms(self):
  327. return self.waveforms
  328. def cache_reset(self):
  329. self.fbank_fn = knf.OnlineFbank(self.opts)
  330. self.reserve_waveforms = None
  331. self.input_cache = None
  332. self.lfr_splice_cache = []
  333. def load_bytes(input):
  334. middle_data = np.frombuffer(input, dtype=np.int16)
  335. middle_data = np.asarray(middle_data)
  336. if middle_data.dtype.kind not in "iu":
  337. raise TypeError("'middle_data' must be an array of integers")
  338. dtype = np.dtype("float32")
  339. if dtype.kind != "f":
  340. raise TypeError("'dtype' must be a floating point type")
  341. i = np.iinfo(middle_data.dtype)
  342. abs_max = 2 ** (i.bits - 1)
  343. offset = i.min + abs_max
  344. array = np.frombuffer((middle_data.astype(dtype) - offset) / abs_max, dtype=np.float32)
  345. return array
  346. class SinusoidalPositionEncoderOnline:
  347. """Streaming Positional encoding."""
  348. def encode(self, positions: np.ndarray = None, depth: int = None, dtype: np.dtype = np.float32):
  349. batch_size = positions.shape[0]
  350. positions = positions.astype(dtype)
  351. log_timescale_increment = np.log(np.array([10000], dtype=dtype)) / (depth / 2 - 1)
  352. inv_timescales = np.exp(np.arange(depth / 2).astype(dtype) * (-log_timescale_increment))
  353. inv_timescales = np.reshape(inv_timescales, [batch_size, -1])
  354. scaled_time = np.reshape(positions, [1, -1, 1]) * np.reshape(inv_timescales, [1, 1, -1])
  355. encoding = np.concatenate((np.sin(scaled_time), np.cos(scaled_time)), axis=2)
  356. return encoding.astype(dtype)
  357. def forward(self, x, start_idx=0):
  358. batch_size, timesteps, input_dim = x.shape
  359. positions = np.arange(1, timesteps + 1 + start_idx)[None, :]
  360. position_encoding = self.encode(positions, input_dim, x.dtype)
  361. return x + position_encoding[:, start_idx : start_idx + timesteps]
  362. def test():
  363. path = "/nfs/zhifu.gzf/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/example/asr_example.wav"
  364. import librosa
  365. cmvn_file = "/nfs/zhifu.gzf/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/am.mvn"
  366. config_file = "/nfs/zhifu.gzf/export/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/config.yaml"
  367. from funasr.runtime.python.onnxruntime.rapid_paraformer.utils.utils import read_yaml
  368. config = read_yaml(config_file)
  369. waveform, _ = librosa.load(path, sr=None)
  370. frontend = WavFrontend(
  371. cmvn_file=cmvn_file,
  372. **config["frontend_conf"],
  373. )
  374. speech, _ = frontend.fbank_online(waveform) # 1d, (sample,), numpy
  375. feat, feat_len = frontend.lfr_cmvn(
  376. speech
  377. ) # 2d, (frame, 450), np.float32 -> torch, torch.from_numpy(), dtype, (1, frame, 450)
  378. frontend.reset_status() # clear cache
  379. return feat, feat_len
  380. if __name__ == "__main__":
  381. test()