utils.py 12 KB

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