preprocessor.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. pattern = re.compile(r"([\u4E00-\u9FA5A-Za-z0-9])")
  42. for word in txt:
  43. if pattern.match(word):
  44. if word in seg_dict:
  45. out_txt += seg_dict[word] + " "
  46. else:
  47. out_txt += "<unk>" + " "
  48. else:
  49. continue
  50. return out_txt.strip().split()
  51. def framing(
  52. x,
  53. frame_length: int = 512,
  54. frame_shift: int = 256,
  55. centered: bool = True,
  56. padded: bool = True,
  57. ):
  58. if x.size == 0:
  59. raise ValueError("Input array size is zero")
  60. if frame_length < 1:
  61. raise ValueError("frame_length must be a positive integer")
  62. if frame_length > x.shape[-1]:
  63. raise ValueError("frame_length is greater than input length")
  64. if 0 >= frame_shift:
  65. raise ValueError("frame_shift must be greater than 0")
  66. if centered:
  67. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [
  68. (frame_length // 2, frame_length // 2)
  69. ]
  70. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  71. if padded:
  72. # Pad to integer number of windowed segments
  73. # I.e make x.shape[-1] = frame_length + (nseg-1)*nstep,
  74. # with integer nseg
  75. nadd = (-(x.shape[-1] - frame_length) % frame_shift) % frame_length
  76. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [(0, nadd)]
  77. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  78. # Created strided array of data segments
  79. if frame_length == 1 and frame_length == frame_shift:
  80. result = x[..., None]
  81. else:
  82. shape = x.shape[:-1] + (
  83. (x.shape[-1] - frame_length) // frame_shift + 1,
  84. frame_length,
  85. )
  86. strides = x.strides[:-1] + (frame_shift * x.strides[-1], x.strides[-1])
  87. result = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
  88. return result
  89. def detect_non_silence(
  90. x: np.ndarray,
  91. threshold: float = 0.01,
  92. frame_length: int = 1024,
  93. frame_shift: int = 512,
  94. window: str = "boxcar",
  95. ) -> np.ndarray:
  96. """Power based voice activity detection.
  97. Args:
  98. x: (Channel, Time)
  99. >>> x = np.random.randn(1000)
  100. >>> detect = detect_non_silence(x)
  101. >>> assert x.shape == detect.shape
  102. >>> assert detect.dtype == np.bool
  103. """
  104. if x.shape[-1] < frame_length:
  105. return np.full(x.shape, fill_value=True, dtype=np.bool)
  106. if x.dtype.kind == "i":
  107. x = x.astype(np.float64)
  108. # framed_w: (C, T, F)
  109. framed_w = framing(
  110. x,
  111. frame_length=frame_length,
  112. frame_shift=frame_shift,
  113. centered=False,
  114. padded=True,
  115. )
  116. framed_w *= scipy.signal.get_window(window, frame_length).astype(framed_w.dtype)
  117. # power: (C, T)
  118. power = (framed_w ** 2).mean(axis=-1)
  119. # mean_power: (C, 1)
  120. mean_power = np.mean(power, axis=-1, keepdims=True)
  121. if np.all(mean_power == 0):
  122. return np.full(x.shape, fill_value=True, dtype=np.bool)
  123. # detect_frames: (C, T)
  124. detect_frames = power / mean_power > threshold
  125. # detects: (C, T, F)
  126. detects = np.broadcast_to(
  127. detect_frames[..., None], detect_frames.shape + (frame_shift,)
  128. )
  129. # detects: (C, TF)
  130. detects = detects.reshape(*detect_frames.shape[:-1], -1)
  131. # detects: (C, TF)
  132. return np.pad(
  133. detects,
  134. [(0, 0)] * (x.ndim - 1) + [(0, x.shape[-1] - detects.shape[-1])],
  135. mode="edge",
  136. )
  137. class CommonPreprocessor(AbsPreprocessor):
  138. def __init__(
  139. self,
  140. train: bool,
  141. token_type: str = None,
  142. token_list: Union[Path, str, Iterable[str]] = None,
  143. bpemodel: Union[Path, str, Iterable[str]] = None,
  144. text_cleaner: Collection[str] = None,
  145. g2p_type: str = None,
  146. unk_symbol: str = "<unk>",
  147. space_symbol: str = "<space>",
  148. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  149. delimiter: str = None,
  150. rir_scp: str = None,
  151. rir_apply_prob: float = 1.0,
  152. noise_scp: str = None,
  153. noise_apply_prob: float = 1.0,
  154. noise_db_range: str = "3_10",
  155. speech_volume_normalize: float = None,
  156. speech_name: str = "speech",
  157. text_name: str = "text",
  158. split_with_space: bool = False,
  159. seg_dict_file: str = None,
  160. ):
  161. super().__init__(train)
  162. self.train = train
  163. self.speech_name = speech_name
  164. self.text_name = text_name
  165. self.speech_volume_normalize = speech_volume_normalize
  166. self.rir_apply_prob = rir_apply_prob
  167. self.noise_apply_prob = noise_apply_prob
  168. self.split_with_space = split_with_space
  169. self.seg_dict = None
  170. if seg_dict_file is not None:
  171. self.seg_dict = {}
  172. with open(seg_dict_file) as f:
  173. lines = f.readlines()
  174. for line in lines:
  175. s = line.strip().split()
  176. key = s[0]
  177. value = s[1:]
  178. self.seg_dict[key] = " ".join(value)
  179. if token_type is not None:
  180. if token_list is None:
  181. raise ValueError("token_list is required if token_type is not None")
  182. self.text_cleaner = TextCleaner(text_cleaner)
  183. self.tokenizer = build_tokenizer(
  184. token_type=token_type,
  185. bpemodel=bpemodel,
  186. delimiter=delimiter,
  187. space_symbol=space_symbol,
  188. non_linguistic_symbols=non_linguistic_symbols,
  189. g2p_type=g2p_type,
  190. )
  191. self.token_id_converter = TokenIDConverter(
  192. token_list=token_list,
  193. unk_symbol=unk_symbol,
  194. )
  195. else:
  196. self.text_cleaner = None
  197. self.tokenizer = None
  198. self.token_id_converter = None
  199. if train and rir_scp is not None:
  200. self.rirs = []
  201. with open(rir_scp, "r", encoding="utf-8") as f:
  202. for line in f:
  203. sps = line.strip().split(None, 1)
  204. if len(sps) == 1:
  205. self.rirs.append(sps[0])
  206. else:
  207. self.rirs.append(sps[1])
  208. else:
  209. self.rirs = None
  210. if train and noise_scp is not None:
  211. self.noises = []
  212. with open(noise_scp, "r", encoding="utf-8") as f:
  213. for line in f:
  214. sps = line.strip().split(None, 1)
  215. if len(sps) == 1:
  216. self.noises.append(sps[0])
  217. else:
  218. self.noises.append(sps[1])
  219. sps = noise_db_range.split("_")
  220. if len(sps) == 1:
  221. self.noise_db_low, self.noise_db_high = float(sps[0])
  222. elif len(sps) == 2:
  223. self.noise_db_low, self.noise_db_high = float(sps[0]), float(sps[1])
  224. else:
  225. raise ValueError(
  226. "Format error: '{noise_db_range}' e.g. -3_4 -> [-3db,4db]"
  227. )
  228. else:
  229. self.noises = None
  230. def _speech_process(
  231. self, data: Dict[str, Union[str, np.ndarray]]
  232. ) -> Dict[str, Union[str, np.ndarray]]:
  233. assert check_argument_types()
  234. if self.speech_name in data:
  235. if self.train and (self.rirs is not None or self.noises is not None):
  236. speech = data[self.speech_name]
  237. nsamples = len(speech)
  238. # speech: (Nmic, Time)
  239. if speech.ndim == 1:
  240. speech = speech[None, :]
  241. else:
  242. speech = speech.T
  243. # Calc power on non shlence region
  244. power = (speech[detect_non_silence(speech)] ** 2).mean()
  245. # 1. Convolve RIR
  246. if self.rirs is not None and self.rir_apply_prob >= np.random.random():
  247. rir_path = np.random.choice(self.rirs)
  248. if rir_path is not None:
  249. rir, _ = soundfile.read(
  250. rir_path, dtype=np.float64, always_2d=True
  251. )
  252. # rir: (Nmic, Time)
  253. rir = rir.T
  254. # speech: (Nmic, Time)
  255. # Note that this operation doesn't change the signal length
  256. speech = scipy.signal.convolve(speech, rir, mode="full")[
  257. :, : speech.shape[1]
  258. ]
  259. # Reverse mean power to the original power
  260. power2 = (speech[detect_non_silence(speech)] ** 2).mean()
  261. speech = np.sqrt(power / max(power2, 1e-10)) * speech
  262. # 2. Add Noise
  263. if (
  264. self.noises is not None
  265. and self.noise_apply_prob >= np.random.random()
  266. ):
  267. noise_path = np.random.choice(self.noises)
  268. if noise_path is not None:
  269. noise_db = np.random.uniform(
  270. self.noise_db_low, self.noise_db_high
  271. )
  272. with soundfile.SoundFile(noise_path) as f:
  273. if f.frames == nsamples:
  274. noise = f.read(dtype=np.float64, always_2d=True)
  275. elif f.frames < nsamples:
  276. offset = np.random.randint(0, nsamples - f.frames)
  277. # noise: (Time, Nmic)
  278. noise = f.read(dtype=np.float64, always_2d=True)
  279. # Repeat noise
  280. noise = np.pad(
  281. noise,
  282. [(offset, nsamples - f.frames - offset), (0, 0)],
  283. mode="wrap",
  284. )
  285. else:
  286. offset = np.random.randint(0, f.frames - nsamples)
  287. f.seek(offset)
  288. # noise: (Time, Nmic)
  289. noise = f.read(
  290. nsamples, dtype=np.float64, always_2d=True
  291. )
  292. if len(noise) != nsamples:
  293. raise RuntimeError(f"Something wrong: {noise_path}")
  294. # noise: (Nmic, Time)
  295. noise = noise.T
  296. noise_power = (noise ** 2).mean()
  297. scale = (
  298. 10 ** (-noise_db / 20)
  299. * np.sqrt(power)
  300. / np.sqrt(max(noise_power, 1e-10))
  301. )
  302. speech = speech + scale * noise
  303. speech = speech.T
  304. ma = np.max(np.abs(speech))
  305. if ma > 1.0:
  306. speech /= ma
  307. data[self.speech_name] = speech
  308. if self.speech_volume_normalize is not None:
  309. speech = data[self.speech_name]
  310. ma = np.max(np.abs(speech))
  311. data[self.speech_name] = speech * self.speech_volume_normalize / ma
  312. assert check_return_type(data)
  313. return data
  314. def _text_process(
  315. self, data: Dict[str, Union[str, np.ndarray]]
  316. ) -> Dict[str, np.ndarray]:
  317. if self.text_name in data and self.tokenizer is not None:
  318. text = data[self.text_name]
  319. text = self.text_cleaner(text)
  320. if self.split_with_space:
  321. tokens = text.strip().split(" ")
  322. if self.seg_dict is not None:
  323. tokens = forward_segment("".join(tokens).lower(), self.seg_dict)
  324. tokens = seg_tokenize(tokens, self.seg_dict)
  325. else:
  326. tokens = self.tokenizer.text2tokens(text)
  327. text_ints = self.token_id_converter.tokens2ids(tokens)
  328. data[self.text_name] = np.array(text_ints, dtype=np.int64)
  329. assert check_return_type(data)
  330. return data
  331. def __call__(
  332. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  333. ) -> Dict[str, np.ndarray]:
  334. assert check_argument_types()
  335. data = self._speech_process(data)
  336. data = self._text_process(data)
  337. return data
  338. class CommonPreprocessor_multi(AbsPreprocessor):
  339. def __init__(
  340. self,
  341. train: bool,
  342. token_type: str = None,
  343. token_list: Union[Path, str, Iterable[str]] = None,
  344. bpemodel: Union[Path, str, Iterable[str]] = None,
  345. text_cleaner: Collection[str] = None,
  346. g2p_type: str = None,
  347. unk_symbol: str = "<unk>",
  348. space_symbol: str = "<space>",
  349. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  350. delimiter: str = None,
  351. speech_name: str = "speech",
  352. text_name: List[str] = ["text"],
  353. ):
  354. super().__init__(train)
  355. self.train = train
  356. self.speech_name = speech_name
  357. self.text_name = text_name
  358. if token_type is not None:
  359. if token_list is None:
  360. raise ValueError("token_list is required if token_type is not None")
  361. self.text_cleaner = TextCleaner(text_cleaner)
  362. self.tokenizer = build_tokenizer(
  363. token_type=token_type,
  364. bpemodel=bpemodel,
  365. delimiter=delimiter,
  366. space_symbol=space_symbol,
  367. non_linguistic_symbols=non_linguistic_symbols,
  368. g2p_type=g2p_type,
  369. )
  370. self.token_id_converter = TokenIDConverter(
  371. token_list=token_list,
  372. unk_symbol=unk_symbol,
  373. )
  374. else:
  375. self.text_cleaner = None
  376. self.tokenizer = None
  377. self.token_id_converter = None
  378. def _text_process(
  379. self, data: Dict[str, Union[str, np.ndarray]]
  380. ) -> Dict[str, np.ndarray]:
  381. for text_n in self.text_name:
  382. if text_n in data and self.tokenizer is not None:
  383. text = data[text_n]
  384. text = self.text_cleaner(text)
  385. tokens = self.tokenizer.text2tokens(text)
  386. text_ints = self.token_id_converter.tokens2ids(tokens)
  387. data[text_n] = np.array(text_ints, dtype=np.int64)
  388. assert check_return_type(data)
  389. return data
  390. def __call__(
  391. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  392. ) -> Dict[str, np.ndarray]:
  393. assert check_argument_types()
  394. if self.speech_name in data:
  395. # Nothing now: candidates:
  396. # - STFT
  397. # - Fbank
  398. # - CMVN
  399. # - Data augmentation
  400. pass
  401. data = self._text_process(data)
  402. return data
  403. class MutliTokenizerCommonPreprocessor(CommonPreprocessor):
  404. def __init__(
  405. self,
  406. train: bool,
  407. token_type: List[str] = [None],
  408. token_list: List[Union[Path, str, Iterable[str]]] = [None],
  409. bpemodel: List[Union[Path, str, Iterable[str]]] = [None],
  410. text_cleaner: Collection[str] = None,
  411. g2p_type: str = None,
  412. unk_symbol: str = "<unk>",
  413. space_symbol: str = "<space>",
  414. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  415. delimiter: str = None,
  416. rir_scp: str = None,
  417. rir_apply_prob: float = 1.0,
  418. noise_scp: str = None,
  419. noise_apply_prob: float = 1.0,
  420. noise_db_range: str = "3_10",
  421. speech_volume_normalize: float = None,
  422. speech_name: str = "speech",
  423. text_name: List[str] = ["text"],
  424. ):
  425. # TODO(jiatong): sync with Kamo and Jing on interface for preprocessor
  426. super().__init__(
  427. train=train,
  428. token_type=token_type[0],
  429. token_list=token_list[0],
  430. bpemodel=bpemodel[0],
  431. text_cleaner=text_cleaner,
  432. g2p_type=g2p_type,
  433. unk_symbol=unk_symbol,
  434. space_symbol=space_symbol,
  435. non_linguistic_symbols=non_linguistic_symbols,
  436. delimiter=delimiter,
  437. speech_name=speech_name,
  438. text_name=text_name[0],
  439. rir_scp=rir_scp,
  440. rir_apply_prob=rir_apply_prob,
  441. noise_scp=noise_scp,
  442. noise_apply_prob=noise_apply_prob,
  443. noise_db_range=noise_db_range,
  444. speech_volume_normalize=speech_volume_normalize,
  445. )
  446. assert (
  447. len(token_type) == len(token_list) == len(bpemodel) == len(text_name)
  448. ), "token_type, token_list, bpemodel, or processing text_name mismatched"
  449. self.num_tokenizer = len(token_type)
  450. self.tokenizer = []
  451. self.token_id_converter = []
  452. for i in range(self.num_tokenizer):
  453. if token_type[i] is not None:
  454. if token_list[i] is None:
  455. raise ValueError("token_list is required if token_type is not None")
  456. self.tokenizer.append(
  457. build_tokenizer(
  458. token_type=token_type[i],
  459. bpemodel=bpemodel[i],
  460. delimiter=delimiter,
  461. space_symbol=space_symbol,
  462. non_linguistic_symbols=non_linguistic_symbols,
  463. g2p_type=g2p_type,
  464. )
  465. )
  466. self.token_id_converter.append(
  467. TokenIDConverter(
  468. token_list=token_list[i],
  469. unk_symbol=unk_symbol,
  470. )
  471. )
  472. else:
  473. self.tokenizer.append(None)
  474. self.token_id_converter.append(None)
  475. self.text_cleaner = TextCleaner(text_cleaner)
  476. self.text_name = text_name # override the text_name from CommonPreprocessor
  477. def _text_process(
  478. self, data: Dict[str, Union[str, np.ndarray]]
  479. ) -> Dict[str, np.ndarray]:
  480. for i in range(self.num_tokenizer):
  481. text_name = self.text_name[i]
  482. if text_name in data and self.tokenizer[i] is not None:
  483. text = data[text_name]
  484. text = self.text_cleaner(text)
  485. tokens = self.tokenizer[i].text2tokens(text)
  486. text_ints = self.token_id_converter[i].tokens2ids(tokens)
  487. data[text_name] = np.array(text_ints, dtype=np.int64)
  488. assert check_return_type(data)
  489. return data
  490. class CodeMixTokenizerCommonPreprocessor(CommonPreprocessor):
  491. def __init__(
  492. self,
  493. train: bool,
  494. token_type: str = None,
  495. token_list: Union[Path, str, Iterable[str]] = None,
  496. bpemodel: Union[Path, str, Iterable[str]] = None,
  497. text_cleaner: Collection[str] = None,
  498. g2p_type: str = None,
  499. unk_symbol: str = "<unk>",
  500. space_symbol: str = "<space>",
  501. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  502. delimiter: str = None,
  503. rir_scp: str = None,
  504. rir_apply_prob: float = 1.0,
  505. noise_scp: str = None,
  506. noise_apply_prob: float = 1.0,
  507. noise_db_range: str = "3_10",
  508. speech_volume_normalize: float = None,
  509. speech_name: str = "speech",
  510. text_name: str = "text",
  511. split_text_name: str = "split_text",
  512. split_with_space: bool = False,
  513. seg_dict_file: str = None,
  514. ):
  515. super().__init__(
  516. train=train,
  517. # Force to use word.
  518. token_type="word",
  519. token_list=token_list,
  520. bpemodel=bpemodel,
  521. text_cleaner=text_cleaner,
  522. g2p_type=g2p_type,
  523. unk_symbol=unk_symbol,
  524. space_symbol=space_symbol,
  525. non_linguistic_symbols=non_linguistic_symbols,
  526. delimiter=delimiter,
  527. speech_name=speech_name,
  528. text_name=text_name,
  529. rir_scp=rir_scp,
  530. rir_apply_prob=rir_apply_prob,
  531. noise_scp=noise_scp,
  532. noise_apply_prob=noise_apply_prob,
  533. noise_db_range=noise_db_range,
  534. speech_volume_normalize=speech_volume_normalize,
  535. split_with_space=split_with_space,
  536. seg_dict_file=seg_dict_file,
  537. )
  538. # The data field name for split text.
  539. self.split_text_name = split_text_name
  540. @classmethod
  541. def split_words(cls, text: str):
  542. words = []
  543. segs = text.split()
  544. for seg in segs:
  545. # There is no space in seg.
  546. current_word = ""
  547. for c in seg:
  548. if len(c.encode()) == 1:
  549. # This is an ASCII char.
  550. current_word += c
  551. else:
  552. # This is a Chinese char.
  553. if len(current_word) > 0:
  554. words.append(current_word)
  555. current_word = ""
  556. words.append(c)
  557. if len(current_word) > 0:
  558. words.append(current_word)
  559. return words
  560. def __call__(
  561. self, uid: str, data: Dict[str, Union[list, str, np.ndarray]]
  562. ) -> Dict[str, Union[list, np.ndarray]]:
  563. assert check_argument_types()
  564. # Split words.
  565. if isinstance(data[self.text_name], str):
  566. split_text = self.split_words(data[self.text_name])
  567. else:
  568. split_text = data[self.text_name]
  569. data[self.text_name] = " ".join(split_text)
  570. data = self._speech_process(data)
  571. data = self._text_process(data)
  572. data[self.split_text_name] = split_text
  573. return data
  574. def pop_split_text_data(self, data: Dict[str, Union[str, np.ndarray]]):
  575. result = data[self.split_text_name]
  576. del data[self.split_text_name]
  577. return result