utils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. import warnings
  15. root_dir = Path(__file__).resolve().parent
  16. logger_initialized = {}
  17. class TokenIDConverter():
  18. def __init__(self, token_list: Union[List, str],
  19. ):
  20. check_argument_types()
  21. # self.token_list = self.load_token(token_path)
  22. self.token_list = token_list
  23. self.unk_symbol = token_list[-1]
  24. # @staticmethod
  25. # def load_token(file_path: Union[Path, str]) -> List:
  26. # if not Path(file_path).exists():
  27. # raise TokenIDConverterError(f'The {file_path} does not exist.')
  28. #
  29. # with open(str(file_path), 'rb') as f:
  30. # token_list = pickle.load(f)
  31. #
  32. # if len(token_list) != len(set(token_list)):
  33. # raise TokenIDConverterError('The Token exists duplicated symbol.')
  34. # return token_list
  35. def get_num_vocabulary_size(self) -> int:
  36. return len(self.token_list)
  37. def ids2tokens(self,
  38. integers: Union[np.ndarray, Iterable[int]]) -> List[str]:
  39. if isinstance(integers, np.ndarray) and integers.ndim != 1:
  40. raise TokenIDConverterError(
  41. f"Must be 1 dim ndarray, but got {integers.ndim}")
  42. return [self.token_list[i] for i in integers]
  43. def tokens2ids(self, tokens: Iterable[str]) -> List[int]:
  44. token2id = {v: i for i, v in enumerate(self.token_list)}
  45. if self.unk_symbol not in token2id:
  46. raise TokenIDConverterError(
  47. f"Unknown symbol '{self.unk_symbol}' doesn't exist in the token_list"
  48. )
  49. unk_id = token2id[self.unk_symbol]
  50. return [token2id.get(i, unk_id) for i in tokens]
  51. class CharTokenizer():
  52. def __init__(
  53. self,
  54. symbol_value: Union[Path, str, Iterable[str]] = None,
  55. space_symbol: str = "<space>",
  56. remove_non_linguistic_symbols: bool = False,
  57. ):
  58. check_argument_types()
  59. self.space_symbol = space_symbol
  60. self.non_linguistic_symbols = self.load_symbols(symbol_value)
  61. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  62. @staticmethod
  63. def load_symbols(value: Union[Path, str, Iterable[str]] = None) -> Set:
  64. if value is None:
  65. return set()
  66. if isinstance(value, Iterable[str]):
  67. return set(value)
  68. file_path = Path(value)
  69. if not file_path.exists():
  70. logging.warning("%s doesn't exist.", file_path)
  71. return set()
  72. with file_path.open("r", encoding="utf-8") as f:
  73. return set(line.rstrip() for line in f)
  74. def text2tokens(self, line: Union[str, list]) -> List[str]:
  75. tokens = []
  76. while len(line) != 0:
  77. for w in self.non_linguistic_symbols:
  78. if line.startswith(w):
  79. if not self.remove_non_linguistic_symbols:
  80. tokens.append(line[: len(w)])
  81. line = line[len(w):]
  82. break
  83. else:
  84. t = line[0]
  85. if t == " ":
  86. t = "<space>"
  87. tokens.append(t)
  88. line = line[1:]
  89. return tokens
  90. def tokens2text(self, tokens: Iterable[str]) -> str:
  91. tokens = [t if t != self.space_symbol else " " for t in tokens]
  92. return "".join(tokens)
  93. def __repr__(self):
  94. return (
  95. f"{self.__class__.__name__}("
  96. f'space_symbol="{self.space_symbol}"'
  97. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  98. f")"
  99. )
  100. class Hypothesis(NamedTuple):
  101. """Hypothesis data type."""
  102. yseq: np.ndarray
  103. score: Union[float, np.ndarray] = 0
  104. scores: Dict[str, Union[float, np.ndarray]] = dict()
  105. states: Dict[str, Any] = dict()
  106. def asdict(self) -> dict:
  107. """Convert data to JSON-friendly dict."""
  108. return self._replace(
  109. yseq=self.yseq.tolist(),
  110. score=float(self.score),
  111. scores={k: float(v) for k, v in self.scores.items()},
  112. )._asdict()
  113. class TokenIDConverterError(Exception):
  114. pass
  115. class ONNXRuntimeError(Exception):
  116. pass
  117. class OrtInferSession():
  118. def __init__(self, model_file, device_id=-1):
  119. device_id = str(device_id)
  120. sess_opt = SessionOptions()
  121. sess_opt.intra_op_num_threads = 4
  122. sess_opt.log_severity_level = 4
  123. sess_opt.enable_cpu_mem_arena = False
  124. sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
  125. cuda_ep = 'CUDAExecutionProvider'
  126. cuda_provider_options = {
  127. "device_id": device_id,
  128. "arena_extend_strategy": "kNextPowerOfTwo",
  129. "cudnn_conv_algo_search": "EXHAUSTIVE",
  130. "do_copy_in_default_stream": "true",
  131. }
  132. cpu_ep = 'CPUExecutionProvider'
  133. cpu_provider_options = {
  134. "arena_extend_strategy": "kSameAsRequested",
  135. }
  136. EP_list = []
  137. if device_id != "-1" and get_device() == 'GPU' \
  138. and cuda_ep in get_available_providers():
  139. EP_list = [(cuda_ep, cuda_provider_options)]
  140. EP_list.append((cpu_ep, cpu_provider_options))
  141. self._verify_model(model_file)
  142. self.session = InferenceSession(model_file,
  143. sess_options=sess_opt,
  144. providers=EP_list)
  145. if device_id != "-1" and cuda_ep not in self.session.get_providers():
  146. warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
  147. 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
  148. 'you can check their relations from the offical web site: '
  149. 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
  150. RuntimeWarning)
  151. def __call__(self,
  152. input_content: List[Union[np.ndarray, np.ndarray]]) -> np.ndarray:
  153. input_dict = dict(zip(self.get_input_names(), input_content))
  154. try:
  155. return self.session.run(None, input_dict)
  156. except Exception as e:
  157. raise ONNXRuntimeError('ONNXRuntime inferece failed.') from e
  158. def get_input_names(self, ):
  159. return [v.name for v in self.session.get_inputs()]
  160. def get_output_names(self,):
  161. return [v.name for v in self.session.get_outputs()]
  162. def get_character_list(self, key: str = 'character'):
  163. return self.meta_dict[key].splitlines()
  164. def have_key(self, key: str = 'character') -> bool:
  165. self.meta_dict = self.session.get_modelmeta().custom_metadata_map
  166. if key in self.meta_dict.keys():
  167. return True
  168. return False
  169. @staticmethod
  170. def _verify_model(model_path):
  171. model_path = Path(model_path)
  172. if not model_path.exists():
  173. raise FileNotFoundError(f'{model_path} does not exists.')
  174. if not model_path.is_file():
  175. raise FileExistsError(f'{model_path} is not a file.')
  176. def read_yaml(yaml_path: Union[str, Path]) -> Dict:
  177. if not Path(yaml_path).exists():
  178. raise FileExistsError(f'The {yaml_path} does not exist.')
  179. with open(str(yaml_path), 'rb') as f:
  180. data = yaml.load(f, Loader=yaml.Loader)
  181. return data
  182. @functools.lru_cache()
  183. def get_logger(name='rapdi_paraformer'):
  184. """Initialize and get a logger by name.
  185. If the logger has not been initialized, this method will initialize the
  186. logger by adding one or two handlers, otherwise the initialized logger will
  187. be directly returned. During initialization, a StreamHandler will always be
  188. added.
  189. Args:
  190. name (str): Logger name.
  191. Returns:
  192. logging.Logger: The expected logger.
  193. """
  194. logger = logging.getLogger(name)
  195. if name in logger_initialized:
  196. return logger
  197. for logger_name in logger_initialized:
  198. if name.startswith(logger_name):
  199. return logger
  200. formatter = logging.Formatter(
  201. '[%(asctime)s] %(name)s %(levelname)s: %(message)s',
  202. datefmt="%Y/%m/%d %H:%M:%S")
  203. sh = logging.StreamHandler()
  204. sh.setFormatter(formatter)
  205. logger.addHandler(sh)
  206. logger_initialized[name] = True
  207. logger.propagate = False
  208. return logger