preprocessor.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import re
  2. from abc import ABC
  3. from abc import abstractmethod
  4. from pathlib import Path
  5. from typing import Collection
  6. from typing import Dict
  7. from typing import Iterable
  8. from typing import List
  9. from typing import Union
  10. import numpy as np
  11. import scipy.signal
  12. import soundfile
  13. from typeguard import check_argument_types
  14. from typeguard import check_return_type
  15. from funasr.text.build_tokenizer import build_tokenizer
  16. from funasr.text.cleaner import TextCleaner
  17. from funasr.text.token_id_converter import TokenIDConverter
  18. class AbsPreprocessor(ABC):
  19. def __init__(self, train: bool):
  20. self.train = train
  21. @abstractmethod
  22. def __call__(
  23. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  24. ) -> Dict[str, np.ndarray]:
  25. raise NotImplementedError
  26. def forward_segment(text, dic):
  27. word_list = []
  28. i = 0
  29. while i < len(text):
  30. longest_word = text[i]
  31. for j in range(i + 1, len(text) + 1):
  32. word = text[i:j]
  33. if word in dic:
  34. if len(word) > len(longest_word):
  35. longest_word = word
  36. word_list.append(longest_word)
  37. i += len(longest_word)
  38. return word_list
  39. def seg_tokenize(txt, seg_dict):
  40. out_txt = ""
  41. for word in txt:
  42. if word in seg_dict:
  43. out_txt += seg_dict[word] + " "
  44. else:
  45. out_txt += "<unk>" + " "
  46. return out_txt.strip().split()
  47. def seg_tokenize_wo_pattern(txt, seg_dict):
  48. out_txt = ""
  49. for word in txt:
  50. if word in seg_dict:
  51. out_txt += seg_dict[word] + " "
  52. else:
  53. out_txt += "<unk>" + " "
  54. return out_txt.strip().split()
  55. def framing(
  56. x,
  57. frame_length: int = 512,
  58. frame_shift: int = 256,
  59. centered: bool = True,
  60. padded: bool = True,
  61. ):
  62. if x.size == 0:
  63. raise ValueError("Input array size is zero")
  64. if frame_length < 1:
  65. raise ValueError("frame_length must be a positive integer")
  66. if frame_length > x.shape[-1]:
  67. raise ValueError("frame_length is greater than input length")
  68. if 0 >= frame_shift:
  69. raise ValueError("frame_shift must be greater than 0")
  70. if centered:
  71. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [
  72. (frame_length // 2, frame_length // 2)
  73. ]
  74. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  75. if padded:
  76. # Pad to integer number of windowed segments
  77. # I.e make x.shape[-1] = frame_length + (nseg-1)*nstep,
  78. # with integer nseg
  79. nadd = (-(x.shape[-1] - frame_length) % frame_shift) % frame_length
  80. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [(0, nadd)]
  81. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  82. # Created strided array of data segments
  83. if frame_length == 1 and frame_length == frame_shift:
  84. result = x[..., None]
  85. else:
  86. shape = x.shape[:-1] + (
  87. (x.shape[-1] - frame_length) // frame_shift + 1,
  88. frame_length,
  89. )
  90. strides = x.strides[:-1] + (frame_shift * x.strides[-1], x.strides[-1])
  91. result = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
  92. return result
  93. def detect_non_silence(
  94. x: np.ndarray,
  95. threshold: float = 0.01,
  96. frame_length: int = 1024,
  97. frame_shift: int = 512,
  98. window: str = "boxcar",
  99. ) -> np.ndarray:
  100. """Power based voice activity detection.
  101. Args:
  102. x: (Channel, Time)
  103. >>> x = np.random.randn(1000)
  104. >>> detect = detect_non_silence(x)
  105. >>> assert x.shape == detect.shape
  106. >>> assert detect.dtype == np.bool
  107. """
  108. if x.shape[-1] < frame_length:
  109. return np.full(x.shape, fill_value=True, dtype=np.bool)
  110. if x.dtype.kind == "i":
  111. x = x.astype(np.float64)
  112. # framed_w: (C, T, F)
  113. framed_w = framing(
  114. x,
  115. frame_length=frame_length,
  116. frame_shift=frame_shift,
  117. centered=False,
  118. padded=True,
  119. )
  120. framed_w *= scipy.signal.get_window(window, frame_length).astype(framed_w.dtype)
  121. # power: (C, T)
  122. power = (framed_w ** 2).mean(axis=-1)
  123. # mean_power: (C, 1)
  124. mean_power = np.mean(power, axis=-1, keepdims=True)
  125. if np.all(mean_power == 0):
  126. return np.full(x.shape, fill_value=True, dtype=np.bool)
  127. # detect_frames: (C, T)
  128. detect_frames = power / mean_power > threshold
  129. # detects: (C, T, F)
  130. detects = np.broadcast_to(
  131. detect_frames[..., None], detect_frames.shape + (frame_shift,)
  132. )
  133. # detects: (C, TF)
  134. detects = detects.reshape(*detect_frames.shape[:-1], -1)
  135. # detects: (C, TF)
  136. return np.pad(
  137. detects,
  138. [(0, 0)] * (x.ndim - 1) + [(0, x.shape[-1] - detects.shape[-1])],
  139. mode="edge",
  140. )
  141. class CommonPreprocessor(AbsPreprocessor):
  142. def __init__(
  143. self,
  144. train: bool,
  145. token_type: str = None,
  146. token_list: Union[Path, str, Iterable[str]] = None,
  147. bpemodel: Union[Path, str, Iterable[str]] = None,
  148. text_cleaner: Collection[str] = None,
  149. g2p_type: str = None,
  150. unk_symbol: str = "<unk>",
  151. space_symbol: str = "<space>",
  152. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  153. delimiter: str = None,
  154. rir_scp: str = None,
  155. rir_apply_prob: float = 1.0,
  156. noise_scp: str = None,
  157. noise_apply_prob: float = 1.0,
  158. noise_db_range: str = "3_10",
  159. speech_volume_normalize: float = None,
  160. speech_name: str = "speech",
  161. text_name: str = "text",
  162. split_with_space: bool = False,
  163. seg_dict_file: str = None,
  164. ):
  165. super().__init__(train)
  166. self.train = train
  167. self.speech_name = speech_name
  168. self.text_name = text_name
  169. self.speech_volume_normalize = speech_volume_normalize
  170. self.rir_apply_prob = rir_apply_prob
  171. self.noise_apply_prob = noise_apply_prob
  172. self.split_with_space = split_with_space
  173. self.seg_dict = None
  174. if seg_dict_file is not None:
  175. self.seg_dict = {}
  176. with open(seg_dict_file) as f:
  177. lines = f.readlines()
  178. for line in lines:
  179. s = line.strip().split()
  180. key = s[0]
  181. value = s[1:]
  182. self.seg_dict[key] = " ".join(value)
  183. if token_type is not None:
  184. if token_list is None:
  185. raise ValueError("token_list is required if token_type is not None")
  186. self.text_cleaner = TextCleaner(text_cleaner)
  187. self.tokenizer = build_tokenizer(
  188. token_type=token_type,
  189. bpemodel=bpemodel,
  190. delimiter=delimiter,
  191. space_symbol=space_symbol,
  192. non_linguistic_symbols=non_linguistic_symbols,
  193. g2p_type=g2p_type,
  194. )
  195. self.token_id_converter = TokenIDConverter(
  196. token_list=token_list,
  197. unk_symbol=unk_symbol,
  198. )
  199. else:
  200. self.text_cleaner = None
  201. self.tokenizer = None
  202. self.token_id_converter = None
  203. if train and rir_scp is not None:
  204. self.rirs = []
  205. with open(rir_scp, "r", encoding="utf-8") as f:
  206. for line in f:
  207. sps = line.strip().split(None, 1)
  208. if len(sps) == 1:
  209. self.rirs.append(sps[0])
  210. else:
  211. self.rirs.append(sps[1])
  212. else:
  213. self.rirs = None
  214. if train and noise_scp is not None:
  215. self.noises = []
  216. with open(noise_scp, "r", encoding="utf-8") as f:
  217. for line in f:
  218. sps = line.strip().split(None, 1)
  219. if len(sps) == 1:
  220. self.noises.append(sps[0])
  221. else:
  222. self.noises.append(sps[1])
  223. sps = noise_db_range.split("_")
  224. if len(sps) == 1:
  225. self.noise_db_low, self.noise_db_high = float(sps[0])
  226. elif len(sps) == 2:
  227. self.noise_db_low, self.noise_db_high = float(sps[0]), float(sps[1])
  228. else:
  229. raise ValueError(
  230. "Format error: '{noise_db_range}' e.g. -3_4 -> [-3db,4db]"
  231. )
  232. else:
  233. self.noises = None
  234. def _speech_process(
  235. self, data: Dict[str, Union[str, np.ndarray]]
  236. ) -> Dict[str, Union[str, np.ndarray]]:
  237. assert check_argument_types()
  238. if self.speech_name in data:
  239. if self.train and (self.rirs is not None or self.noises is not None):
  240. speech = data[self.speech_name]
  241. nsamples = len(speech)
  242. # speech: (Nmic, Time)
  243. if speech.ndim == 1:
  244. speech = speech[None, :]
  245. else:
  246. speech = speech.T
  247. # Calc power on non shlence region
  248. power = (speech[detect_non_silence(speech)] ** 2).mean()
  249. # 1. Convolve RIR
  250. if self.rirs is not None and self.rir_apply_prob >= np.random.random():
  251. rir_path = np.random.choice(self.rirs)
  252. if rir_path is not None:
  253. rir, _ = soundfile.read(
  254. rir_path, dtype=np.float64, always_2d=True
  255. )
  256. # rir: (Nmic, Time)
  257. rir = rir.T
  258. # speech: (Nmic, Time)
  259. # Note that this operation doesn't change the signal length
  260. speech = scipy.signal.convolve(speech, rir, mode="full")[
  261. :, : speech.shape[1]
  262. ]
  263. # Reverse mean power to the original power
  264. power2 = (speech[detect_non_silence(speech)] ** 2).mean()
  265. speech = np.sqrt(power / max(power2, 1e-10)) * speech
  266. # 2. Add Noise
  267. if (
  268. self.noises is not None
  269. and self.noise_apply_prob >= np.random.random()
  270. ):
  271. noise_path = np.random.choice(self.noises)
  272. if noise_path is not None:
  273. noise_db = np.random.uniform(
  274. self.noise_db_low, self.noise_db_high
  275. )
  276. with soundfile.SoundFile(noise_path) as f:
  277. if f.frames == nsamples:
  278. noise = f.read(dtype=np.float64, always_2d=True)
  279. elif f.frames < nsamples:
  280. offset = np.random.randint(0, nsamples - f.frames)
  281. # noise: (Time, Nmic)
  282. noise = f.read(dtype=np.float64, always_2d=True)
  283. # Repeat noise
  284. noise = np.pad(
  285. noise,
  286. [(offset, nsamples - f.frames - offset), (0, 0)],
  287. mode="wrap",
  288. )
  289. else:
  290. offset = np.random.randint(0, f.frames - nsamples)
  291. f.seek(offset)
  292. # noise: (Time, Nmic)
  293. noise = f.read(
  294. nsamples, dtype=np.float64, always_2d=True
  295. )
  296. if len(noise) != nsamples:
  297. raise RuntimeError(f"Something wrong: {noise_path}")
  298. # noise: (Nmic, Time)
  299. noise = noise.T
  300. noise_power = (noise ** 2).mean()
  301. scale = (
  302. 10 ** (-noise_db / 20)
  303. * np.sqrt(power)
  304. / np.sqrt(max(noise_power, 1e-10))
  305. )
  306. speech = speech + scale * noise
  307. speech = speech.T
  308. ma = np.max(np.abs(speech))
  309. if ma > 1.0:
  310. speech /= ma
  311. data[self.speech_name] = speech
  312. if self.speech_volume_normalize is not None:
  313. speech = data[self.speech_name]
  314. ma = np.max(np.abs(speech))
  315. data[self.speech_name] = speech * self.speech_volume_normalize / ma
  316. assert check_return_type(data)
  317. return data
  318. def _text_process(
  319. self, data: Dict[str, Union[str, np.ndarray]]
  320. ) -> Dict[str, np.ndarray]:
  321. if self.text_name in data and self.tokenizer is not None:
  322. text = data[self.text_name]
  323. text = self.text_cleaner(text)
  324. if self.split_with_space:
  325. tokens = text.strip().split(" ")
  326. if self.seg_dict is not None:
  327. tokens = forward_segment("".join(tokens), self.seg_dict)
  328. tokens = seg_tokenize(tokens, self.seg_dict)
  329. else:
  330. tokens = self.tokenizer.text2tokens(text)
  331. text_ints = self.token_id_converter.tokens2ids(tokens)
  332. data[self.text_name] = np.array(text_ints, dtype=np.int64)
  333. assert check_return_type(data)
  334. return data
  335. def __call__(
  336. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  337. ) -> Dict[str, np.ndarray]:
  338. assert check_argument_types()
  339. data = self._speech_process(data)
  340. data = self._text_process(data)
  341. return data
  342. class CodeMixTokenizerCommonPreprocessor(CommonPreprocessor):
  343. def __init__(
  344. self,
  345. train: bool,
  346. token_type: str = None,
  347. token_list: Union[Path, str, Iterable[str]] = None,
  348. bpemodel: Union[Path, str, Iterable[str]] = None,
  349. text_cleaner: Collection[str] = None,
  350. g2p_type: str = None,
  351. unk_symbol: str = "<unk>",
  352. space_symbol: str = "<space>",
  353. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  354. delimiter: str = None,
  355. rir_scp: str = None,
  356. rir_apply_prob: float = 1.0,
  357. noise_scp: str = None,
  358. noise_apply_prob: float = 1.0,
  359. noise_db_range: str = "3_10",
  360. speech_volume_normalize: float = None,
  361. speech_name: str = "speech",
  362. text_name: str = "text",
  363. split_text_name: str = "split_text",
  364. split_with_space: bool = False,
  365. seg_dict_file: str = None,
  366. ):
  367. super().__init__(
  368. train=train,
  369. # Force to use word.
  370. token_type="word",
  371. token_list=token_list,
  372. bpemodel=bpemodel,
  373. text_cleaner=text_cleaner,
  374. g2p_type=g2p_type,
  375. unk_symbol=unk_symbol,
  376. space_symbol=space_symbol,
  377. non_linguistic_symbols=non_linguistic_symbols,
  378. delimiter=delimiter,
  379. speech_name=speech_name,
  380. text_name=text_name,
  381. rir_scp=rir_scp,
  382. rir_apply_prob=rir_apply_prob,
  383. noise_scp=noise_scp,
  384. noise_apply_prob=noise_apply_prob,
  385. noise_db_range=noise_db_range,
  386. speech_volume_normalize=speech_volume_normalize,
  387. split_with_space=split_with_space,
  388. seg_dict_file=seg_dict_file,
  389. )
  390. # The data field name for split text.
  391. self.split_text_name = split_text_name
  392. @classmethod
  393. def split_words(cls, text: str):
  394. words = []
  395. segs = text.split()
  396. for seg in segs:
  397. # There is no space in seg.
  398. current_word = ""
  399. for c in seg:
  400. if len(c.encode()) == 1:
  401. # This is an ASCII char.
  402. current_word += c
  403. else:
  404. # This is a Chinese char.
  405. if len(current_word) > 0:
  406. words.append(current_word)
  407. current_word = ""
  408. words.append(c)
  409. if len(current_word) > 0:
  410. words.append(current_word)
  411. return words
  412. def __call__(
  413. self, uid: str, data: Dict[str, Union[list, str, np.ndarray]]
  414. ) -> Dict[str, Union[list, np.ndarray]]:
  415. assert check_argument_types()
  416. # Split words.
  417. if isinstance(data[self.text_name], str):
  418. split_text = self.split_words(data[self.text_name])
  419. else:
  420. split_text = data[self.text_name]
  421. data[self.text_name] = " ".join(split_text)
  422. data = self._speech_process(data)
  423. data = self._text_process(data)
  424. data[self.split_text_name] = split_text
  425. return data
  426. def pop_split_text_data(self, data: Dict[str, Union[str, np.ndarray]]):
  427. result = data[self.split_text_name]
  428. del data[self.split_text_name]
  429. return result