preprocessor.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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 funasr.text.build_tokenizer import build_tokenizer
  14. from funasr.text.cleaner import TextCleaner
  15. from funasr.text.token_id_converter import TokenIDConverter
  16. class AbsPreprocessor(ABC):
  17. def __init__(self, train: bool):
  18. self.train = train
  19. @abstractmethod
  20. def __call__(
  21. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  22. ) -> Dict[str, np.ndarray]:
  23. raise NotImplementedError
  24. def forward_segment(text, dic):
  25. word_list = []
  26. i = 0
  27. while i < len(text):
  28. longest_word = text[i]
  29. for j in range(i + 1, len(text) + 1):
  30. word = text[i:j]
  31. if word in dic:
  32. if len(word) > len(longest_word):
  33. longest_word = word
  34. word_list.append(longest_word)
  35. i += len(longest_word)
  36. return word_list
  37. def seg_tokenize(txt, seg_dict):
  38. pattern = re.compile(r'^[\u4E00-\u9FA50-9]+$')
  39. out_txt = ""
  40. for word in txt:
  41. word = word.lower()
  42. if word in seg_dict:
  43. out_txt += seg_dict[word] + " "
  44. else:
  45. if pattern.match(word):
  46. for char in word:
  47. if char in seg_dict:
  48. out_txt += seg_dict[char] + " "
  49. else:
  50. out_txt += "<unk>" + " "
  51. else:
  52. out_txt += "<unk>" + " "
  53. return out_txt.strip().split()
  54. def seg_tokenize_wo_pattern(txt, seg_dict):
  55. out_txt = ""
  56. for word in txt:
  57. if word in seg_dict:
  58. out_txt += seg_dict[word] + " "
  59. else:
  60. out_txt += "<unk>" + " "
  61. return out_txt.strip().split()
  62. def framing(
  63. x,
  64. frame_length: int = 512,
  65. frame_shift: int = 256,
  66. centered: bool = True,
  67. padded: bool = True,
  68. ):
  69. if x.size == 0:
  70. raise ValueError("Input array size is zero")
  71. if frame_length < 1:
  72. raise ValueError("frame_length must be a positive integer")
  73. if frame_length > x.shape[-1]:
  74. raise ValueError("frame_length is greater than input length")
  75. if 0 >= frame_shift:
  76. raise ValueError("frame_shift must be greater than 0")
  77. if centered:
  78. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [
  79. (frame_length // 2, frame_length // 2)
  80. ]
  81. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  82. if padded:
  83. # Pad to integer number of windowed segments
  84. # I.e make x.shape[-1] = frame_length + (nseg-1)*nstep,
  85. # with integer nseg
  86. nadd = (-(x.shape[-1] - frame_length) % frame_shift) % frame_length
  87. pad_shape = [(0, 0) for _ in range(x.ndim - 1)] + [(0, nadd)]
  88. x = np.pad(x, pad_shape, mode="constant", constant_values=0)
  89. # Created strided array of data segments
  90. if frame_length == 1 and frame_length == frame_shift:
  91. result = x[..., None]
  92. else:
  93. shape = x.shape[:-1] + (
  94. (x.shape[-1] - frame_length) // frame_shift + 1,
  95. frame_length,
  96. )
  97. strides = x.strides[:-1] + (frame_shift * x.strides[-1], x.strides[-1])
  98. result = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
  99. return result
  100. def detect_non_silence(
  101. x: np.ndarray,
  102. threshold: float = 0.01,
  103. frame_length: int = 1024,
  104. frame_shift: int = 512,
  105. window: str = "boxcar",
  106. ) -> np.ndarray:
  107. """Power based voice activity detection.
  108. Args:
  109. x: (Channel, Time)
  110. >>> x = np.random.randn(1000)
  111. >>> detect = detect_non_silence(x)
  112. >>> assert x.shape == detect.shape
  113. >>> assert detect.dtype == np.bool
  114. """
  115. if x.shape[-1] < frame_length:
  116. return np.full(x.shape, fill_value=True, dtype=np.bool)
  117. if x.dtype.kind == "i":
  118. x = x.astype(np.float64)
  119. # framed_w: (C, T, F)
  120. framed_w = framing(
  121. x,
  122. frame_length=frame_length,
  123. frame_shift=frame_shift,
  124. centered=False,
  125. padded=True,
  126. )
  127. framed_w *= scipy.signal.get_window(window, frame_length).astype(framed_w.dtype)
  128. # power: (C, T)
  129. power = (framed_w ** 2).mean(axis=-1)
  130. # mean_power: (C, 1)
  131. mean_power = np.mean(power, axis=-1, keepdims=True)
  132. if np.all(mean_power == 0):
  133. return np.full(x.shape, fill_value=True, dtype=np.bool)
  134. # detect_frames: (C, T)
  135. detect_frames = power / mean_power > threshold
  136. # detects: (C, T, F)
  137. detects = np.broadcast_to(
  138. detect_frames[..., None], detect_frames.shape + (frame_shift,)
  139. )
  140. # detects: (C, TF)
  141. detects = detects.reshape(*detect_frames.shape[:-1], -1)
  142. # detects: (C, TF)
  143. return np.pad(
  144. detects,
  145. [(0, 0)] * (x.ndim - 1) + [(0, x.shape[-1] - detects.shape[-1])],
  146. mode="edge",
  147. )
  148. class CommonPreprocessor(AbsPreprocessor):
  149. def __init__(
  150. self,
  151. train: bool,
  152. token_type: str = None,
  153. token_list: Union[Path, str, Iterable[str]] = None,
  154. bpemodel: Union[Path, str, Iterable[str]] = None,
  155. text_cleaner: Collection[str] = None,
  156. g2p_type: str = None,
  157. unk_symbol: str = "<unk>",
  158. space_symbol: str = "<space>",
  159. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  160. delimiter: str = None,
  161. rir_scp: str = None,
  162. rir_apply_prob: float = 1.0,
  163. noise_scp: str = None,
  164. noise_apply_prob: float = 1.0,
  165. noise_db_range: str = "3_10",
  166. speech_volume_normalize: float = None,
  167. speech_name: str = "speech",
  168. text_name: str = "text",
  169. split_with_space: bool = False,
  170. seg_dict_file: str = None,
  171. ):
  172. super().__init__(train)
  173. self.train = train
  174. self.speech_name = speech_name
  175. self.text_name = text_name
  176. self.speech_volume_normalize = speech_volume_normalize
  177. self.rir_apply_prob = rir_apply_prob
  178. self.noise_apply_prob = noise_apply_prob
  179. self.split_with_space = split_with_space
  180. self.seg_dict = None
  181. if seg_dict_file is not None:
  182. self.seg_dict = {}
  183. with open(seg_dict_file) as f:
  184. lines = f.readlines()
  185. for line in lines:
  186. s = line.strip().split()
  187. key = s[0]
  188. value = s[1:]
  189. self.seg_dict[key] = " ".join(value)
  190. if token_type is not None:
  191. if token_list is None:
  192. raise ValueError("token_list is required if token_type is not None")
  193. self.text_cleaner = TextCleaner(text_cleaner)
  194. self.tokenizer = build_tokenizer(
  195. token_type=token_type,
  196. bpemodel=bpemodel,
  197. delimiter=delimiter,
  198. space_symbol=space_symbol,
  199. non_linguistic_symbols=non_linguistic_symbols,
  200. g2p_type=g2p_type,
  201. )
  202. self.token_id_converter = TokenIDConverter(
  203. token_list=token_list,
  204. unk_symbol=unk_symbol,
  205. )
  206. else:
  207. self.text_cleaner = None
  208. self.tokenizer = None
  209. self.token_id_converter = None
  210. if train and rir_scp is not None:
  211. self.rirs = []
  212. with open(rir_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.rirs.append(sps[0])
  217. else:
  218. self.rirs.append(sps[1])
  219. else:
  220. self.rirs = None
  221. if train and noise_scp is not None:
  222. self.noises = []
  223. with open(noise_scp, "r", encoding="utf-8") as f:
  224. for line in f:
  225. sps = line.strip().split(None, 1)
  226. if len(sps) == 1:
  227. self.noises.append(sps[0])
  228. else:
  229. self.noises.append(sps[1])
  230. sps = noise_db_range.split("_")
  231. if len(sps) == 1:
  232. self.noise_db_low, self.noise_db_high = float(sps[0])
  233. elif len(sps) == 2:
  234. self.noise_db_low, self.noise_db_high = float(sps[0]), float(sps[1])
  235. else:
  236. raise ValueError(
  237. "Format error: '{noise_db_range}' e.g. -3_4 -> [-3db,4db]"
  238. )
  239. else:
  240. self.noises = None
  241. def _speech_process(
  242. self, data: Dict[str, Union[str, np.ndarray]]
  243. ) -> Dict[str, Union[str, np.ndarray]]:
  244. if self.speech_name in data:
  245. if self.train and (self.rirs is not None or self.noises is not None):
  246. speech = data[self.speech_name]
  247. nsamples = len(speech)
  248. # speech: (Nmic, Time)
  249. if speech.ndim == 1:
  250. speech = speech[None, :]
  251. else:
  252. speech = speech.T
  253. # Calc power on non shlence region
  254. power = (speech[detect_non_silence(speech)] ** 2).mean()
  255. # 1. Convolve RIR
  256. if self.rirs is not None and self.rir_apply_prob >= np.random.random():
  257. rir_path = np.random.choice(self.rirs)
  258. if rir_path is not None:
  259. rir, _ = soundfile.read(
  260. rir_path, dtype=np.float64, always_2d=True
  261. )
  262. # rir: (Nmic, Time)
  263. rir = rir.T
  264. # speech: (Nmic, Time)
  265. # Note that this operation doesn't change the signal length
  266. speech = scipy.signal.convolve(speech, rir, mode="full")[
  267. :, : speech.shape[1]
  268. ]
  269. # Reverse mean power to the original power
  270. power2 = (speech[detect_non_silence(speech)] ** 2).mean()
  271. speech = np.sqrt(power / max(power2, 1e-10)) * speech
  272. # 2. Add Noise
  273. if (
  274. self.noises is not None
  275. and self.noise_apply_prob >= np.random.random()
  276. ):
  277. noise_path = np.random.choice(self.noises)
  278. if noise_path is not None:
  279. noise_db = np.random.uniform(
  280. self.noise_db_low, self.noise_db_high
  281. )
  282. with soundfile.SoundFile(noise_path) as f:
  283. if f.frames == nsamples:
  284. noise = f.read(dtype=np.float64, always_2d=True)
  285. elif f.frames < nsamples:
  286. offset = np.random.randint(0, nsamples - f.frames)
  287. # noise: (Time, Nmic)
  288. noise = f.read(dtype=np.float64, always_2d=True)
  289. # Repeat noise
  290. noise = np.pad(
  291. noise,
  292. [(offset, nsamples - f.frames - offset), (0, 0)],
  293. mode="wrap",
  294. )
  295. else:
  296. offset = np.random.randint(0, f.frames - nsamples)
  297. f.seek(offset)
  298. # noise: (Time, Nmic)
  299. noise = f.read(
  300. nsamples, dtype=np.float64, always_2d=True
  301. )
  302. if len(noise) != nsamples:
  303. raise RuntimeError(f"Something wrong: {noise_path}")
  304. # noise: (Nmic, Time)
  305. noise = noise.T
  306. noise_power = (noise ** 2).mean()
  307. scale = (
  308. 10 ** (-noise_db / 20)
  309. * np.sqrt(power)
  310. / np.sqrt(max(noise_power, 1e-10))
  311. )
  312. speech = speech + scale * noise
  313. speech = speech.T
  314. ma = np.max(np.abs(speech))
  315. if ma > 1.0:
  316. speech /= ma
  317. data[self.speech_name] = speech
  318. if self.speech_volume_normalize is not None:
  319. speech = data[self.speech_name]
  320. ma = np.max(np.abs(speech))
  321. data[self.speech_name] = speech * self.speech_volume_normalize / ma
  322. return data
  323. def _text_process(
  324. self, data: Dict[str, Union[str, np.ndarray]]
  325. ) -> Dict[str, np.ndarray]:
  326. if self.text_name in data and self.tokenizer is not None:
  327. text = data[self.text_name]
  328. text = self.text_cleaner(text)
  329. if self.split_with_space:
  330. tokens = text.strip().split(" ")
  331. if self.seg_dict is not None:
  332. tokens = seg_tokenize(tokens, self.seg_dict)
  333. else:
  334. tokens = self.tokenizer.text2tokens(text)
  335. text_ints = self.token_id_converter.tokens2ids(tokens)
  336. data[self.text_name] = np.array(text_ints, dtype=np.int64)
  337. return data
  338. def __call__(
  339. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  340. ) -> Dict[str, np.ndarray]:
  341. data = self._speech_process(data)
  342. data = self._text_process(data)
  343. return data
  344. ## FIXME
  345. class LMPreprocessor(CommonPreprocessor):
  346. def __init__(
  347. self,
  348. train: bool,
  349. token_type: str = None,
  350. token_list: Union[Path, str, Iterable[str]] = None,
  351. bpemodel: Union[Path, str, Iterable[str]] = None,
  352. text_cleaner: Collection[str] = None,
  353. g2p_type: str = None,
  354. unk_symbol: str = "<unk>",
  355. space_symbol: str = "<space>",
  356. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  357. delimiter: str = None,
  358. rir_scp: str = None,
  359. rir_apply_prob: float = 1.0,
  360. noise_scp: str = None,
  361. noise_apply_prob: float = 1.0,
  362. noise_db_range: str = "3_10",
  363. speech_volume_normalize: float = None,
  364. speech_name: str = "speech",
  365. text_name: str = "text",
  366. split_with_space: bool = False,
  367. seg_dict_file: str = None,
  368. ):
  369. super().__init__(train,
  370. token_type,
  371. token_list,
  372. bpemodel,
  373. text_cleaner,
  374. g2p_type,
  375. unk_symbol,
  376. space_symbol,
  377. non_linguistic_symbols,
  378. delimiter,
  379. rir_scp,
  380. rir_apply_prob,
  381. noise_scp,
  382. noise_apply_prob,
  383. noise_db_range,
  384. speech_volume_normalize,
  385. speech_name,
  386. text_name,
  387. split_with_space,
  388. seg_dict_file,
  389. )
  390. def _text_process(
  391. self, data: Dict[str, Union[str, np.ndarray]]
  392. ) -> Dict[str, np.ndarray]:
  393. if self.text_name in data and self.tokenizer is not None:
  394. text = data[self.text_name]
  395. text = self.text_cleaner(text)
  396. if self.split_with_space:
  397. tokens = text.strip().split(" ")
  398. if self.seg_dict is not None:
  399. tokens = seg_tokenize_wo_pattern(tokens, self.seg_dict)
  400. else:
  401. tokens = self.tokenizer.text2tokens(text)
  402. text_ints = self.token_id_converter.tokens2ids(tokens)
  403. data[self.text_name] = np.array(text_ints, dtype=np.int64)
  404. return data
  405. class CommonPreprocessor_multi(AbsPreprocessor):
  406. def __init__(
  407. self,
  408. train: bool,
  409. token_type: str = None,
  410. token_list: Union[Path, str, Iterable[str]] = None,
  411. bpemodel: Union[Path, str, Iterable[str]] = None,
  412. text_cleaner: Collection[str] = None,
  413. g2p_type: str = None,
  414. unk_symbol: str = "<unk>",
  415. space_symbol: str = "<space>",
  416. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  417. delimiter: str = None,
  418. speech_name: str = "speech",
  419. text_name: List[str] = ["text"],
  420. ):
  421. super().__init__(train)
  422. self.train = train
  423. self.speech_name = speech_name
  424. self.text_name = text_name
  425. if token_type is not None:
  426. if token_list is None:
  427. raise ValueError("token_list is required if token_type is not None")
  428. self.text_cleaner = TextCleaner(text_cleaner)
  429. self.tokenizer = build_tokenizer(
  430. token_type=token_type,
  431. bpemodel=bpemodel,
  432. delimiter=delimiter,
  433. space_symbol=space_symbol,
  434. non_linguistic_symbols=non_linguistic_symbols,
  435. g2p_type=g2p_type,
  436. )
  437. self.token_id_converter = TokenIDConverter(
  438. token_list=token_list,
  439. unk_symbol=unk_symbol,
  440. )
  441. else:
  442. self.text_cleaner = None
  443. self.tokenizer = None
  444. self.token_id_converter = None
  445. def _text_process(
  446. self, data: Dict[str, Union[str, np.ndarray]]
  447. ) -> Dict[str, np.ndarray]:
  448. for text_n in self.text_name:
  449. if text_n in data and self.tokenizer is not None:
  450. text = data[text_n]
  451. text = self.text_cleaner(text)
  452. tokens = self.tokenizer.text2tokens(text)
  453. text_ints = self.token_id_converter.tokens2ids(tokens)
  454. data[text_n] = np.array(text_ints, dtype=np.int64)
  455. return data
  456. def __call__(
  457. self, uid: str, data: Dict[str, Union[str, np.ndarray]]
  458. ) -> Dict[str, np.ndarray]:
  459. if self.speech_name in data:
  460. # Nothing now: candidates:
  461. # - STFT
  462. # - Fbank
  463. # - CMVN
  464. # - Data augmentation
  465. pass
  466. data = self._text_process(data)
  467. return data
  468. class MutliTokenizerCommonPreprocessor(CommonPreprocessor):
  469. def __init__(
  470. self,
  471. train: bool,
  472. token_type: List[str] = [None],
  473. token_list: List[Union[Path, str, Iterable[str]]] = [None],
  474. bpemodel: List[Union[Path, str, Iterable[str]]] = [None],
  475. text_cleaner: Collection[str] = None,
  476. g2p_type: str = None,
  477. unk_symbol: str = "<unk>",
  478. space_symbol: str = "<space>",
  479. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  480. delimiter: str = None,
  481. rir_scp: str = None,
  482. rir_apply_prob: float = 1.0,
  483. noise_scp: str = None,
  484. noise_apply_prob: float = 1.0,
  485. noise_db_range: str = "3_10",
  486. speech_volume_normalize: float = None,
  487. speech_name: str = "speech",
  488. text_name: List[str] = ["text"],
  489. ):
  490. # TODO(jiatong): sync with Kamo and Jing on interface for preprocessor
  491. super().__init__(
  492. train=train,
  493. token_type=token_type[0],
  494. token_list=token_list[0],
  495. bpemodel=bpemodel[0],
  496. text_cleaner=text_cleaner,
  497. g2p_type=g2p_type,
  498. unk_symbol=unk_symbol,
  499. space_symbol=space_symbol,
  500. non_linguistic_symbols=non_linguistic_symbols,
  501. delimiter=delimiter,
  502. speech_name=speech_name,
  503. text_name=text_name[0],
  504. rir_scp=rir_scp,
  505. rir_apply_prob=rir_apply_prob,
  506. noise_scp=noise_scp,
  507. noise_apply_prob=noise_apply_prob,
  508. noise_db_range=noise_db_range,
  509. speech_volume_normalize=speech_volume_normalize,
  510. )
  511. assert (
  512. len(token_type) == len(token_list) == len(bpemodel) == len(text_name)
  513. ), "token_type, token_list, bpemodel, or processing text_name mismatched"
  514. self.num_tokenizer = len(token_type)
  515. self.tokenizer = []
  516. self.token_id_converter = []
  517. for i in range(self.num_tokenizer):
  518. if token_type[i] is not None:
  519. if token_list[i] is None:
  520. raise ValueError("token_list is required if token_type is not None")
  521. self.tokenizer.append(
  522. build_tokenizer(
  523. token_type=token_type[i],
  524. bpemodel=bpemodel[i],
  525. delimiter=delimiter,
  526. space_symbol=space_symbol,
  527. non_linguistic_symbols=non_linguistic_symbols,
  528. g2p_type=g2p_type,
  529. )
  530. )
  531. self.token_id_converter.append(
  532. TokenIDConverter(
  533. token_list=token_list[i],
  534. unk_symbol=unk_symbol,
  535. )
  536. )
  537. else:
  538. self.tokenizer.append(None)
  539. self.token_id_converter.append(None)
  540. self.text_cleaner = TextCleaner(text_cleaner)
  541. self.text_name = text_name # override the text_name from CommonPreprocessor
  542. def _text_process(
  543. self, data: Dict[str, Union[str, np.ndarray]]
  544. ) -> Dict[str, np.ndarray]:
  545. for i in range(self.num_tokenizer):
  546. text_name = self.text_name[i]
  547. if text_name in data and self.tokenizer[i] is not None:
  548. text = data[text_name]
  549. text = self.text_cleaner(text)
  550. tokens = self.tokenizer[i].text2tokens(text)
  551. text_ints = self.token_id_converter[i].tokens2ids(tokens)
  552. data[text_name] = np.array(text_ints, dtype=np.int64)
  553. return data
  554. class CodeMixTokenizerCommonPreprocessor(CommonPreprocessor):
  555. def __init__(
  556. self,
  557. train: bool,
  558. token_type: str = None,
  559. token_list: Union[Path, str, Iterable[str]] = None,
  560. bpemodel: Union[Path, str, Iterable[str]] = None,
  561. text_cleaner: Collection[str] = None,
  562. g2p_type: str = None,
  563. unk_symbol: str = "<unk>",
  564. space_symbol: str = "<space>",
  565. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  566. delimiter: str = None,
  567. rir_scp: str = None,
  568. rir_apply_prob: float = 1.0,
  569. noise_scp: str = None,
  570. noise_apply_prob: float = 1.0,
  571. noise_db_range: str = "3_10",
  572. speech_volume_normalize: float = None,
  573. speech_name: str = "speech",
  574. text_name: str = "text",
  575. split_text_name: str = "split_text",
  576. split_with_space: bool = False,
  577. seg_jieba: bool = False,
  578. seg_dict_file: str = None,
  579. ):
  580. super().__init__(
  581. train=train,
  582. # Force to use word.
  583. token_type="word",
  584. token_list=token_list,
  585. bpemodel=bpemodel,
  586. text_cleaner=text_cleaner,
  587. g2p_type=g2p_type,
  588. unk_symbol=unk_symbol,
  589. space_symbol=space_symbol,
  590. non_linguistic_symbols=non_linguistic_symbols,
  591. delimiter=delimiter,
  592. speech_name=speech_name,
  593. text_name=text_name,
  594. rir_scp=rir_scp,
  595. rir_apply_prob=rir_apply_prob,
  596. noise_scp=noise_scp,
  597. noise_apply_prob=noise_apply_prob,
  598. noise_db_range=noise_db_range,
  599. speech_volume_normalize=speech_volume_normalize,
  600. split_with_space=split_with_space,
  601. seg_dict_file=seg_dict_file,
  602. )
  603. # The data field name for split text.
  604. self.split_text_name = split_text_name
  605. self.seg_jieba = seg_jieba
  606. if self.seg_jieba:
  607. import jieba
  608. jieba.load_userdict(seg_dict_file)
  609. @classmethod
  610. def split_words(cls, text: str):
  611. words = []
  612. segs = text.split()
  613. for seg in segs:
  614. # There is no space in seg.
  615. current_word = ""
  616. for c in seg:
  617. if len(c.encode()) == 1:
  618. # This is an ASCII char.
  619. current_word += c
  620. else:
  621. # This is a Chinese char.
  622. if len(current_word) > 0:
  623. words.append(current_word)
  624. current_word = ""
  625. words.append(c)
  626. if len(current_word) > 0:
  627. words.append(current_word)
  628. return words
  629. @classmethod
  630. def isEnglish(cls, text:str):
  631. if re.search('^[a-zA-Z\']+$', text):
  632. return True
  633. else:
  634. return False
  635. @classmethod
  636. def join_chinese_and_english(cls, input_list):
  637. line = ''
  638. for token in input_list:
  639. if cls.isEnglish(token):
  640. line = line + ' ' + token
  641. else:
  642. line = line + token
  643. line = line.strip()
  644. return line
  645. @classmethod
  646. def split_words_jieba(cls, text: str):
  647. input_list = text.split()
  648. token_list_all = []
  649. langauge_list = []
  650. token_list_tmp = []
  651. language_flag = None
  652. for token in input_list:
  653. if cls.isEnglish(token) and language_flag == 'Chinese':
  654. token_list_all.append(token_list_tmp)
  655. langauge_list.append('Chinese')
  656. token_list_tmp = []
  657. elif not cls.isEnglish(token) and language_flag == 'English':
  658. token_list_all.append(token_list_tmp)
  659. langauge_list.append('English')
  660. token_list_tmp = []
  661. token_list_tmp.append(token)
  662. if cls.isEnglish(token):
  663. language_flag = 'English'
  664. else:
  665. language_flag = 'Chinese'
  666. if token_list_tmp:
  667. token_list_all.append(token_list_tmp)
  668. langauge_list.append(language_flag)
  669. result_list = []
  670. for token_list_tmp, language_flag in zip(token_list_all, langauge_list):
  671. if language_flag == 'English':
  672. result_list.extend(token_list_tmp)
  673. else:
  674. seg_list = jieba.cut(cls.join_chinese_and_english(token_list_tmp), HMM=False)
  675. result_list.extend(seg_list)
  676. return result_list
  677. def __call__(
  678. self, uid: str, data: Dict[str, Union[list, str, np.ndarray]]
  679. ) -> Dict[str, Union[list, np.ndarray]]:
  680. # Split words.
  681. if isinstance(data[self.text_name], str):
  682. if self.seg_jieba:
  683. # jieba.load_userdict(seg_dict_file)
  684. split_text = self.split_words_jieba(data[self.text_name])
  685. else:
  686. split_text = self.split_words(data[self.text_name])
  687. else:
  688. split_text = data[self.text_name]
  689. data[self.text_name] = " ".join(split_text)
  690. data = self._speech_process(data)
  691. data = self._text_process(data)
  692. data[self.split_text_name] = split_text
  693. return data
  694. def pop_split_text_data(self, data: Dict[str, Union[str, np.ndarray]]):
  695. result = data[self.split_text_name]
  696. del data[self.split_text_name]
  697. return result
  698. class PuncTrainTokenizerCommonPreprocessor(CommonPreprocessor):
  699. def __init__(
  700. self,
  701. train: bool,
  702. token_type: List[str] = [None],
  703. token_list: List[Union[Path, str, Iterable[str]]] = [None],
  704. bpemodel: List[Union[Path, str, Iterable[str]]] = [None],
  705. text_cleaner: Collection[str] = None,
  706. g2p_type: str = None,
  707. unk_symbol: str = "<unk>",
  708. space_symbol: str = "<space>",
  709. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  710. delimiter: str = None,
  711. rir_scp: str = None,
  712. rir_apply_prob: float = 1.0,
  713. noise_scp: str = None,
  714. noise_apply_prob: float = 1.0,
  715. noise_db_range: str = "3_10",
  716. speech_volume_normalize: float = None,
  717. speech_name: str = "speech",
  718. text_name: List[str] = ["text"],
  719. vad_name: str = "vad_indexes",
  720. ):
  721. # TODO(jiatong): sync with Kamo and Jing on interface for preprocessor
  722. super().__init__(
  723. train=train,
  724. token_type=token_type[0],
  725. token_list=token_list[0],
  726. bpemodel=bpemodel[0],
  727. text_cleaner=text_cleaner,
  728. g2p_type=g2p_type,
  729. unk_symbol=unk_symbol,
  730. space_symbol=space_symbol,
  731. non_linguistic_symbols=non_linguistic_symbols,
  732. delimiter=delimiter,
  733. speech_name=speech_name,
  734. text_name=text_name[0],
  735. rir_scp=rir_scp,
  736. rir_apply_prob=rir_apply_prob,
  737. noise_scp=noise_scp,
  738. noise_apply_prob=noise_apply_prob,
  739. noise_db_range=noise_db_range,
  740. speech_volume_normalize=speech_volume_normalize,
  741. )
  742. assert (
  743. len(token_type) == len(token_list) == len(bpemodel) == len(text_name)
  744. ), "token_type, token_list, bpemodel, or processing text_name mismatched"
  745. self.num_tokenizer = len(token_type)
  746. self.tokenizer = []
  747. self.token_id_converter = []
  748. for i in range(self.num_tokenizer):
  749. if token_type[i] is not None:
  750. if token_list[i] is None:
  751. raise ValueError("token_list is required if token_type is not None")
  752. self.tokenizer.append(
  753. build_tokenizer(
  754. token_type=token_type[i],
  755. bpemodel=bpemodel[i],
  756. delimiter=delimiter,
  757. space_symbol=space_symbol,
  758. non_linguistic_symbols=non_linguistic_symbols,
  759. g2p_type=g2p_type,
  760. )
  761. )
  762. self.token_id_converter.append(
  763. TokenIDConverter(
  764. token_list=token_list[i],
  765. unk_symbol=unk_symbol,
  766. )
  767. )
  768. else:
  769. self.tokenizer.append(None)
  770. self.token_id_converter.append(None)
  771. self.text_cleaner = TextCleaner(text_cleaner)
  772. self.text_name = text_name # override the text_name from CommonPreprocessor
  773. self.vad_name = vad_name
  774. def _text_process(
  775. self, data: Dict[str, Union[str, np.ndarray]]
  776. ) -> Dict[str, np.ndarray]:
  777. for i in range(self.num_tokenizer):
  778. text_name = self.text_name[i]
  779. if text_name in data and self.tokenizer[i] is not None:
  780. text = data[text_name]
  781. text = self.text_cleaner(text)
  782. tokens = self.tokenizer[i].text2tokens(text)
  783. if "vad:" in tokens[-1]:
  784. vad = tokens[-1][4:]
  785. tokens = tokens[:-1]
  786. if len(vad) == 0:
  787. vad = -1
  788. else:
  789. vad = int(vad)
  790. data[self.vad_name] = np.array([vad], dtype=np.int64)
  791. text_ints = self.token_id_converter[i].tokens2ids(tokens)
  792. data[text_name] = np.array(text_ints, dtype=np.int64)
  793. return data
  794. def split_to_mini_sentence(words: list, word_limit: int = 20):
  795. assert word_limit > 1
  796. if len(words) <= word_limit:
  797. return [words]
  798. sentences = []
  799. length = len(words)
  800. sentence_len = length // word_limit
  801. for i in range(sentence_len):
  802. sentences.append(words[i * word_limit:(i + 1) * word_limit])
  803. if length % word_limit > 0:
  804. sentences.append(words[sentence_len * word_limit:])
  805. return sentences