utils.py 9.0 KB

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