infer_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. # -*- encoding: utf-8 -*-
  2. import functools
  3. import logging
  4. from pathlib import Path
  5. from typing import Any, Dict, Iterable, List, NamedTuple, Set, Tuple, Union
  6. import re
  7. import numpy as np
  8. import yaml
  9. try:
  10. from onnxruntime import (
  11. GraphOptimizationLevel,
  12. InferenceSession,
  13. SessionOptions,
  14. get_available_providers,
  15. get_device,
  16. )
  17. except:
  18. print("please pip3 install onnxruntime")
  19. import jieba
  20. import warnings
  21. root_dir = Path(__file__).resolve().parent
  22. logger_initialized = {}
  23. def pad_list(xs, pad_value, max_len=None):
  24. n_batch = len(xs)
  25. if max_len is None:
  26. max_len = max(x.size(0) for x in xs)
  27. # pad = xs[0].new(n_batch, max_len, *xs[0].size()[1:]).fill_(pad_value)
  28. # numpy format
  29. pad = (np.zeros((n_batch, max_len)) + pad_value).astype(np.int32)
  30. for i in range(n_batch):
  31. pad[i, : xs[i].shape[0]] = xs[i]
  32. return pad
  33. """
  34. def make_pad_mask(lengths, xs=None, length_dim=-1, maxlen=None):
  35. if length_dim == 0:
  36. raise ValueError("length_dim cannot be 0: {}".format(length_dim))
  37. if not isinstance(lengths, list):
  38. lengths = lengths.tolist()
  39. bs = int(len(lengths))
  40. if maxlen is None:
  41. if xs is None:
  42. maxlen = int(max(lengths))
  43. else:
  44. maxlen = xs.size(length_dim)
  45. else:
  46. assert xs is None
  47. assert maxlen >= int(max(lengths))
  48. seq_range = torch.arange(0, maxlen, dtype=torch.int64)
  49. seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen)
  50. seq_length_expand = seq_range_expand.new(lengths).unsqueeze(-1)
  51. mask = seq_range_expand >= seq_length_expand
  52. if xs is not None:
  53. assert xs.size(0) == bs, (xs.size(0), bs)
  54. if length_dim < 0:
  55. length_dim = xs.dim() + length_dim
  56. # ind = (:, None, ..., None, :, , None, ..., None)
  57. ind = tuple(
  58. slice(None) if i in (0, length_dim) else None for i in range(xs.dim())
  59. )
  60. mask = mask[ind].expand_as(xs).to(xs.device)
  61. return mask
  62. """
  63. class TokenIDConverter:
  64. def __init__(
  65. self,
  66. token_list: Union[List, str],
  67. ):
  68. self.token_list = token_list
  69. self.unk_symbol = token_list[-1]
  70. self.token2id = {v: i for i, v in enumerate(self.token_list)}
  71. self.unk_id = self.token2id[self.unk_symbol]
  72. def get_num_vocabulary_size(self) -> int:
  73. return len(self.token_list)
  74. def ids2tokens(self, integers: Union[np.ndarray, Iterable[int]]) -> List[str]:
  75. if isinstance(integers, np.ndarray) and integers.ndim != 1:
  76. raise TokenIDConverterError(f"Must be 1 dim ndarray, but got {integers.ndim}")
  77. return [self.token_list[i] for i in integers]
  78. def tokens2ids(self, tokens: Iterable[str]) -> List[int]:
  79. return [self.token2id.get(i, self.unk_id) for i in tokens]
  80. class CharTokenizer:
  81. def __init__(
  82. self,
  83. symbol_value: Union[Path, str, Iterable[str]] = None,
  84. space_symbol: str = "<space>",
  85. remove_non_linguistic_symbols: bool = False,
  86. ):
  87. self.space_symbol = space_symbol
  88. self.non_linguistic_symbols = self.load_symbols(symbol_value)
  89. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  90. @staticmethod
  91. def load_symbols(value: Union[Path, str, Iterable[str]] = None) -> Set:
  92. if value is None:
  93. return set()
  94. if isinstance(value, Iterable[str]):
  95. return set(value)
  96. file_path = Path(value)
  97. if not file_path.exists():
  98. logging.warning("%s doesn't exist.", file_path)
  99. return set()
  100. with file_path.open("r", encoding="utf-8") as f:
  101. return set(line.rstrip() for line in f)
  102. def text2tokens(self, line: Union[str, list]) -> List[str]:
  103. tokens = []
  104. while len(line) != 0:
  105. for w in self.non_linguistic_symbols:
  106. if line.startswith(w):
  107. if not self.remove_non_linguistic_symbols:
  108. tokens.append(line[: len(w)])
  109. line = line[len(w) :]
  110. break
  111. else:
  112. t = line[0]
  113. if t == " ":
  114. t = "<space>"
  115. tokens.append(t)
  116. line = line[1:]
  117. return tokens
  118. def tokens2text(self, tokens: Iterable[str]) -> str:
  119. tokens = [t if t != self.space_symbol else " " for t in tokens]
  120. return "".join(tokens)
  121. def __repr__(self):
  122. return (
  123. f"{self.__class__.__name__}("
  124. f'space_symbol="{self.space_symbol}"'
  125. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  126. f")"
  127. )
  128. class Hypothesis(NamedTuple):
  129. """Hypothesis data type."""
  130. yseq: np.ndarray
  131. score: Union[float, np.ndarray] = 0
  132. scores: Dict[str, Union[float, np.ndarray]] = dict()
  133. states: Dict[str, Any] = dict()
  134. def asdict(self) -> dict:
  135. """Convert data to JSON-friendly dict."""
  136. return self._replace(
  137. yseq=self.yseq.tolist(),
  138. score=float(self.score),
  139. scores={k: float(v) for k, v in self.scores.items()},
  140. )._asdict()
  141. class TokenIDConverterError(Exception):
  142. pass
  143. class ONNXRuntimeError(Exception):
  144. pass
  145. class OrtInferSession:
  146. def __init__(self, model_file, device_id=-1, intra_op_num_threads=4):
  147. device_id = str(device_id)
  148. sess_opt = SessionOptions()
  149. sess_opt.intra_op_num_threads = intra_op_num_threads
  150. sess_opt.log_severity_level = 4
  151. sess_opt.enable_cpu_mem_arena = False
  152. sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
  153. cuda_ep = "CUDAExecutionProvider"
  154. cuda_provider_options = {
  155. "device_id": device_id,
  156. "arena_extend_strategy": "kNextPowerOfTwo",
  157. "cudnn_conv_algo_search": "EXHAUSTIVE",
  158. "do_copy_in_default_stream": "true",
  159. }
  160. cpu_ep = "CPUExecutionProvider"
  161. cpu_provider_options = {
  162. "arena_extend_strategy": "kSameAsRequested",
  163. }
  164. EP_list = []
  165. if device_id != "-1" and get_device() == "GPU" and cuda_ep in get_available_providers():
  166. EP_list = [(cuda_ep, cuda_provider_options)]
  167. EP_list.append((cpu_ep, cpu_provider_options))
  168. self._verify_model(model_file)
  169. self.session = InferenceSession(model_file, sess_options=sess_opt, providers=EP_list)
  170. if device_id != "-1" and cuda_ep not in self.session.get_providers():
  171. warnings.warn(
  172. f"{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n"
  173. "Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, "
  174. "you can check their relations from the offical web site: "
  175. "https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html",
  176. RuntimeWarning,
  177. )
  178. def __call__(self, input_content: List[Union[np.ndarray, np.ndarray]]) -> np.ndarray:
  179. input_dict = dict(zip(self.get_input_names(), input_content))
  180. try:
  181. return self.session.run(self.get_output_names(), input_dict)
  182. except Exception as e:
  183. raise ONNXRuntimeError("ONNXRuntime inferece failed.") from e
  184. def get_input_names(
  185. self,
  186. ):
  187. return [v.name for v in self.session.get_inputs()]
  188. def get_output_names(
  189. self,
  190. ):
  191. return [v.name for v in self.session.get_outputs()]
  192. def get_character_list(self, key: str = "character"):
  193. return self.meta_dict[key].splitlines()
  194. def have_key(self, key: str = "character") -> bool:
  195. self.meta_dict = self.session.get_modelmeta().custom_metadata_map
  196. if key in self.meta_dict.keys():
  197. return True
  198. return False
  199. @staticmethod
  200. def _verify_model(model_path):
  201. model_path = Path(model_path)
  202. if not model_path.exists():
  203. raise FileNotFoundError(f"{model_path} does not exists.")
  204. if not model_path.is_file():
  205. raise FileExistsError(f"{model_path} is not a file.")
  206. def split_to_mini_sentence(words: list, word_limit: int = 20):
  207. assert word_limit > 1
  208. if len(words) <= word_limit:
  209. return [words]
  210. sentences = []
  211. length = len(words)
  212. sentence_len = length // word_limit
  213. for i in range(sentence_len):
  214. sentences.append(words[i * word_limit : (i + 1) * word_limit])
  215. if length % word_limit > 0:
  216. sentences.append(words[sentence_len * word_limit :])
  217. return sentences
  218. def code_mix_split_words(text: str):
  219. words = []
  220. segs = text.split()
  221. for seg in segs:
  222. # There is no space in seg.
  223. current_word = ""
  224. for c in seg:
  225. if len(c.encode()) == 1:
  226. # This is an ASCII char.
  227. current_word += c
  228. else:
  229. # This is a Chinese char.
  230. if len(current_word) > 0:
  231. words.append(current_word)
  232. current_word = ""
  233. words.append(c)
  234. if len(current_word) > 0:
  235. words.append(current_word)
  236. return words
  237. def isEnglish(text: str):
  238. if re.search("^[a-zA-Z']+$", text):
  239. return True
  240. else:
  241. return False
  242. def join_chinese_and_english(input_list):
  243. line = ""
  244. for token in input_list:
  245. if isEnglish(token):
  246. line = line + " " + token
  247. else:
  248. line = line + token
  249. line = line.strip()
  250. return line
  251. def code_mix_split_words_jieba(seg_dict_file: str):
  252. jieba.load_userdict(seg_dict_file)
  253. def _fn(text: str):
  254. input_list = text.split()
  255. token_list_all = []
  256. langauge_list = []
  257. token_list_tmp = []
  258. language_flag = None
  259. for token in input_list:
  260. if isEnglish(token) and language_flag == "Chinese":
  261. token_list_all.append(token_list_tmp)
  262. langauge_list.append("Chinese")
  263. token_list_tmp = []
  264. elif not isEnglish(token) and language_flag == "English":
  265. token_list_all.append(token_list_tmp)
  266. langauge_list.append("English")
  267. token_list_tmp = []
  268. token_list_tmp.append(token)
  269. if isEnglish(token):
  270. language_flag = "English"
  271. else:
  272. language_flag = "Chinese"
  273. if token_list_tmp:
  274. token_list_all.append(token_list_tmp)
  275. langauge_list.append(language_flag)
  276. result_list = []
  277. for token_list_tmp, language_flag in zip(token_list_all, langauge_list):
  278. if language_flag == "English":
  279. result_list.extend(token_list_tmp)
  280. else:
  281. seg_list = jieba.cut(join_chinese_and_english(token_list_tmp), HMM=False)
  282. result_list.extend(seg_list)
  283. return result_list
  284. return _fn
  285. def read_yaml(yaml_path: Union[str, Path]) -> Dict:
  286. if not Path(yaml_path).exists():
  287. raise FileExistsError(f"The {yaml_path} does not exist.")
  288. with open(str(yaml_path), "rb") as f:
  289. data = yaml.load(f, Loader=yaml.Loader)
  290. return data
  291. @functools.lru_cache()
  292. def get_logger(name="funasr_onnx"):
  293. """Initialize and get a logger by name.
  294. If the logger has not been initialized, this method will initialize the
  295. logger by adding one or two handlers, otherwise the initialized logger will
  296. be directly returned. During initialization, a StreamHandler will always be
  297. added.
  298. Args:
  299. name (str): Logger name.
  300. Returns:
  301. logging.Logger: The expected logger.
  302. """
  303. logger = logging.getLogger(name)
  304. if name in logger_initialized:
  305. return logger
  306. for logger_name in logger_initialized:
  307. if name.startswith(logger_name):
  308. return logger
  309. formatter = logging.Formatter(
  310. "[%(asctime)s] %(name)s %(levelname)s: %(message)s", datefmt="%Y/%m/%d %H:%M:%S"
  311. )
  312. sh = logging.StreamHandler()
  313. sh.setFormatter(formatter)
  314. logger.addHandler(sh)
  315. logger_initialized[name] = True
  316. logger.propagate = False
  317. logging.basicConfig(level=logging.ERROR)
  318. return logger