utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # -*- encoding: utf-8 -*-
  2. # @Author: SWHL
  3. # @Contact: liekkaskono@163.com
  4. import functools
  5. import logging
  6. import pickle
  7. from pathlib import Path
  8. from typing import Any, Dict, Iterable, List, NamedTuple, Set, Tuple, Union
  9. import numpy as np
  10. import yaml
  11. from onnxruntime import (GraphOptimizationLevel, InferenceSession,
  12. SessionOptions, get_available_providers, get_device)
  13. from typeguard import check_argument_types
  14. from .kaldifeat import compute_fbank_feats
  15. root_dir = Path(__file__).resolve().parent
  16. logger_initialized = {}
  17. class TokenIDConverter():
  18. def __init__(self, token_path: Union[Path, str],
  19. unk_symbol: str = "<unk>",):
  20. check_argument_types()
  21. self.token_list = self.load_token(token_path)
  22. self.unk_symbol = unk_symbol
  23. @staticmethod
  24. def load_token(file_path: Union[Path, str]) -> List:
  25. if not Path(file_path).exists():
  26. raise TokenIDConverterError(f'The {file_path} does not exist.')
  27. with open(str(file_path), 'rb') as f:
  28. token_list = pickle.load(f)
  29. if len(token_list) != len(set(token_list)):
  30. raise TokenIDConverterError('The Token exists duplicated symbol.')
  31. return token_list
  32. def get_num_vocabulary_size(self) -> int:
  33. return len(self.token_list)
  34. def ids2tokens(self,
  35. integers: Union[np.ndarray, Iterable[int]]) -> List[str]:
  36. if isinstance(integers, np.ndarray) and integers.ndim != 1:
  37. raise TokenIDConverterError(
  38. f"Must be 1 dim ndarray, but got {integers.ndim}")
  39. return [self.token_list[i] for i in integers]
  40. def tokens2ids(self, tokens: Iterable[str]) -> List[int]:
  41. token2id = {v: i for i, v in enumerate(self.token_list)}
  42. if self.unk_symbol not in token2id:
  43. raise TokenIDConverterError(
  44. f"Unknown symbol '{self.unk_symbol}' doesn't exist in the token_list"
  45. )
  46. unk_id = token2id[self.unk_symbol]
  47. return [token2id.get(i, unk_id) for i in tokens]
  48. class CharTokenizer():
  49. def __init__(
  50. self,
  51. symbol_value: Union[Path, str, Iterable[str]] = None,
  52. space_symbol: str = "<space>",
  53. remove_non_linguistic_symbols: bool = False,
  54. ):
  55. check_argument_types()
  56. self.space_symbol = space_symbol
  57. self.non_linguistic_symbols = self.load_symbols(symbol_value)
  58. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  59. @staticmethod
  60. def load_symbols(value: Union[Path, str, Iterable[str]] = None) -> Set:
  61. if value is None:
  62. return set()
  63. if isinstance(value, Iterable[str]):
  64. return set(value)
  65. file_path = Path(value)
  66. if not file_path.exists():
  67. logging.warning("%s doesn't exist.", file_path)
  68. return set()
  69. with file_path.open("r", encoding="utf-8") as f:
  70. return set(line.rstrip() for line in f)
  71. def text2tokens(self, line: Union[str, list]) -> List[str]:
  72. tokens = []
  73. while len(line) != 0:
  74. for w in self.non_linguistic_symbols:
  75. if line.startswith(w):
  76. if not self.remove_non_linguistic_symbols:
  77. tokens.append(line[: len(w)])
  78. line = line[len(w):]
  79. break
  80. else:
  81. t = line[0]
  82. if t == " ":
  83. t = "<space>"
  84. tokens.append(t)
  85. line = line[1:]
  86. return tokens
  87. def tokens2text(self, tokens: Iterable[str]) -> str:
  88. tokens = [t if t != self.space_symbol else " " for t in tokens]
  89. return "".join(tokens)
  90. def __repr__(self):
  91. return (
  92. f"{self.__class__.__name__}("
  93. f'space_symbol="{self.space_symbol}"'
  94. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  95. f")"
  96. )
  97. class WavFrontend():
  98. """Conventional frontend structure for ASR.
  99. """
  100. def __init__(
  101. self,
  102. cmvn_file: str = None,
  103. fs: int = 16000,
  104. window: str = 'hamming',
  105. n_mels: int = 80,
  106. frame_length: int = 25,
  107. frame_shift: int = 10,
  108. filter_length_min: int = -1,
  109. filter_length_max: float = -1,
  110. lfr_m: int = 1,
  111. lfr_n: int = 1,
  112. dither: float = 1.0
  113. ) -> None:
  114. check_argument_types()
  115. self.fs = fs
  116. self.window = window
  117. self.n_mels = n_mels
  118. self.frame_length = frame_length
  119. self.frame_shift = frame_shift
  120. self.filter_length_min = filter_length_min
  121. self.filter_length_max = filter_length_max
  122. self.lfr_m = lfr_m
  123. self.lfr_n = lfr_n
  124. self.cmvn_file = cmvn_file
  125. self.dither = dither
  126. if self.cmvn_file:
  127. self.cmvn = self.load_cmvn()
  128. def fbank(self,
  129. input_content: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  130. waveform_len = input_content.shape[1]
  131. waveform = input_content[0][:waveform_len]
  132. waveform = waveform * (1 << 15)
  133. mat = compute_fbank_feats(waveform,
  134. num_mel_bins=self.n_mels,
  135. frame_length=self.frame_length,
  136. frame_shift=self.frame_shift,
  137. dither=self.dither,
  138. energy_floor=0.0,
  139. sample_frequency=self.fs,
  140. window_type=self.window)
  141. feat = mat.astype(np.float32)
  142. feat_len = np.array(mat.shape[0]).astype(np.int32)
  143. return feat, feat_len
  144. def lfr_cmvn(self, feat: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
  145. if self.lfr_m != 1 or self.lfr_n != 1:
  146. feat = self.apply_lfr(feat, self.lfr_m, self.lfr_n)
  147. if self.cmvn_file:
  148. feat = self.apply_cmvn(feat)
  149. feat_len = np.array(feat.shape[0]).astype(np.int32)
  150. return feat, feat_len
  151. @staticmethod
  152. def apply_lfr(inputs: np.ndarray, lfr_m: int, lfr_n: int) -> np.ndarray:
  153. LFR_inputs = []
  154. T = inputs.shape[0]
  155. T_lfr = int(np.ceil(T / lfr_n))
  156. left_padding = np.tile(inputs[0], ((lfr_m - 1) // 2, 1))
  157. inputs = np.vstack((left_padding, inputs))
  158. T = T + (lfr_m - 1) // 2
  159. for i in range(T_lfr):
  160. if lfr_m <= T - i * lfr_n:
  161. LFR_inputs.append(
  162. (inputs[i * lfr_n:i * lfr_n + lfr_m]).reshape(1, -1))
  163. else:
  164. # process last LFR frame
  165. num_padding = lfr_m - (T - i * lfr_n)
  166. frame = inputs[i * lfr_n:].reshape(-1)
  167. for _ in range(num_padding):
  168. frame = np.hstack((frame, inputs[-1]))
  169. LFR_inputs.append(frame)
  170. LFR_outputs = np.vstack(LFR_inputs).astype(np.float32)
  171. return LFR_outputs
  172. def apply_cmvn(self, inputs: np.ndarray) -> np.ndarray:
  173. """
  174. Apply CMVN with mvn data
  175. """
  176. frame, dim = inputs.shape
  177. means = np.tile(self.cmvn[0:1, :dim], (frame, 1))
  178. vars = np.tile(self.cmvn[1:2, :dim], (frame, 1))
  179. inputs = (inputs + means) * vars
  180. return inputs
  181. def load_cmvn(self,) -> np.ndarray:
  182. with open(self.cmvn_file, 'r', encoding='utf-8') as f:
  183. lines = f.readlines()
  184. means_list = []
  185. vars_list = []
  186. for i in range(len(lines)):
  187. line_item = lines[i].split()
  188. if line_item[0] == '<AddShift>':
  189. line_item = lines[i + 1].split()
  190. if line_item[0] == '<LearnRateCoef>':
  191. add_shift_line = line_item[3:(len(line_item) - 1)]
  192. means_list = list(add_shift_line)
  193. continue
  194. elif line_item[0] == '<Rescale>':
  195. line_item = lines[i + 1].split()
  196. if line_item[0] == '<LearnRateCoef>':
  197. rescale_line = line_item[3:(len(line_item) - 1)]
  198. vars_list = list(rescale_line)
  199. continue
  200. means = np.array(means_list).astype(np.float64)
  201. vars = np.array(vars_list).astype(np.float64)
  202. cmvn = np.array([means, vars])
  203. return cmvn
  204. class Hypothesis(NamedTuple):
  205. """Hypothesis data type."""
  206. yseq: np.ndarray
  207. score: Union[float, np.ndarray] = 0
  208. scores: Dict[str, Union[float, np.ndarray]] = dict()
  209. states: Dict[str, Any] = dict()
  210. def asdict(self) -> dict:
  211. """Convert data to JSON-friendly dict."""
  212. return self._replace(
  213. yseq=self.yseq.tolist(),
  214. score=float(self.score),
  215. scores={k: float(v) for k, v in self.scores.items()},
  216. )._asdict()
  217. class TokenIDConverterError(Exception):
  218. pass
  219. class ONNXRuntimeError(Exception):
  220. pass
  221. class OrtInferSession():
  222. def __init__(self, config):
  223. sess_opt = SessionOptions()
  224. sess_opt.log_severity_level = 4
  225. sess_opt.enable_cpu_mem_arena = False
  226. sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
  227. cuda_ep = 'CUDAExecutionProvider'
  228. cpu_ep = 'CPUExecutionProvider'
  229. cpu_provider_options = {
  230. "arena_extend_strategy": "kSameAsRequested",
  231. }
  232. EP_list = []
  233. if config['use_cuda'] and get_device() == 'GPU' \
  234. and cuda_ep in get_available_providers():
  235. EP_list = [(cuda_ep, config[cuda_ep])]
  236. EP_list.append((cpu_ep, cpu_provider_options))
  237. config['model_path'] = config['model_path']
  238. self._verify_model(config['model_path'])
  239. self.session = InferenceSession(config['model_path'],
  240. sess_options=sess_opt,
  241. providers=EP_list)
  242. if config['use_cuda'] and cuda_ep not in self.session.get_providers():
  243. warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
  244. 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
  245. 'you can check their relations from the offical web site: '
  246. 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
  247. RuntimeWarning)
  248. def __call__(self,
  249. input_content: List[Union[np.ndarray, np.ndarray]]) -> np.ndarray:
  250. input_dict = dict(zip(self.get_input_names(), input_content))
  251. try:
  252. return self.session.run(None, input_dict)
  253. except Exception as e:
  254. raise ONNXRuntimeError('ONNXRuntime inferece failed.') from e
  255. def get_input_names(self, ):
  256. return [v.name for v in self.session.get_inputs()]
  257. def get_output_names(self,):
  258. return [v.name for v in self.session.get_outputs()]
  259. def get_character_list(self, key: str = 'character'):
  260. return self.meta_dict[key].splitlines()
  261. def have_key(self, key: str = 'character') -> bool:
  262. self.meta_dict = self.session.get_modelmeta().custom_metadata_map
  263. if key in self.meta_dict.keys():
  264. return True
  265. return False
  266. @staticmethod
  267. def _verify_model(model_path):
  268. model_path = Path(model_path)
  269. if not model_path.exists():
  270. raise FileNotFoundError(f'{model_path} does not exists.')
  271. if not model_path.is_file():
  272. raise FileExistsError(f'{model_path} is not a file.')
  273. def read_yaml(yaml_path: Union[str, Path]) -> Dict:
  274. if not Path(yaml_path).exists():
  275. raise FileExistsError(f'The {yaml_path} does not exist.')
  276. with open(str(yaml_path), 'rb') as f:
  277. data = yaml.load(f, Loader=yaml.Loader)
  278. return data
  279. @functools.lru_cache()
  280. def get_logger(name='rapdi_paraformer'):
  281. """Initialize and get a logger by name.
  282. If the logger has not been initialized, this method will initialize the
  283. logger by adding one or two handlers, otherwise the initialized logger will
  284. be directly returned. During initialization, a StreamHandler will always be
  285. added.
  286. Args:
  287. name (str): Logger name.
  288. Returns:
  289. logging.Logger: The expected logger.
  290. """
  291. logger = logging.getLogger(name)
  292. if name in logger_initialized:
  293. return logger
  294. for logger_name in logger_initialized:
  295. if name.startswith(logger_name):
  296. return logger
  297. formatter = logging.Formatter(
  298. '[%(asctime)s] %(name)s %(levelname)s: %(message)s',
  299. datefmt="%Y/%m/%d %H:%M:%S")
  300. sh = logging.StreamHandler()
  301. sh.setFormatter(formatter)
  302. logger.addHandler(sh)
  303. logger_initialized[name] = True
  304. logger.propagate = False
  305. return logger