utils.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 typeguard import check_argument_types
  10. import warnings
  11. root_dir = Path(__file__).resolve().parent
  12. logger_initialized = {}
  13. class TokenIDConverter():
  14. def __init__(self, token_list: Union[List, str],
  15. ):
  16. check_argument_types()
  17. self.token_list = token_list
  18. self.unk_symbol = token_list[-1]
  19. self.token2id = {v: i for i, v in enumerate(self.token_list)}
  20. self.unk_id = self.token2id[self.unk_symbol]
  21. def get_num_vocabulary_size(self) -> int:
  22. return len(self.token_list)
  23. def ids2tokens(self,
  24. integers: Union[np.ndarray, Iterable[int]]) -> List[str]:
  25. if isinstance(integers, np.ndarray) and integers.ndim != 1:
  26. raise TokenIDConverterError(
  27. f"Must be 1 dim ndarray, but got {integers.ndim}")
  28. return [self.token_list[i] for i in integers]
  29. def tokens2ids(self, tokens: Iterable[str]) -> List[int]:
  30. return [self.token2id.get(i, self.unk_id) for i in tokens]
  31. class CharTokenizer():
  32. def __init__(
  33. self,
  34. symbol_value: Union[Path, str, Iterable[str]] = None,
  35. space_symbol: str = "<space>",
  36. remove_non_linguistic_symbols: bool = False,
  37. ):
  38. check_argument_types()
  39. self.space_symbol = space_symbol
  40. self.non_linguistic_symbols = self.load_symbols(symbol_value)
  41. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  42. @staticmethod
  43. def load_symbols(value: Union[Path, str, Iterable[str]] = None) -> Set:
  44. if value is None:
  45. return set()
  46. if isinstance(value, Iterable[str]):
  47. return set(value)
  48. file_path = Path(value)
  49. if not file_path.exists():
  50. logging.warning("%s doesn't exist.", file_path)
  51. return set()
  52. with file_path.open("r", encoding="utf-8") as f:
  53. return set(line.rstrip() for line in f)
  54. def text2tokens(self, line: Union[str, list]) -> List[str]:
  55. tokens = []
  56. while len(line) != 0:
  57. for w in self.non_linguistic_symbols:
  58. if line.startswith(w):
  59. if not self.remove_non_linguistic_symbols:
  60. tokens.append(line[: len(w)])
  61. line = line[len(w):]
  62. break
  63. else:
  64. t = line[0]
  65. if t == " ":
  66. t = "<space>"
  67. tokens.append(t)
  68. line = line[1:]
  69. return tokens
  70. def tokens2text(self, tokens: Iterable[str]) -> str:
  71. tokens = [t if t != self.space_symbol else " " for t in tokens]
  72. return "".join(tokens)
  73. def __repr__(self):
  74. return (
  75. f"{self.__class__.__name__}("
  76. f'space_symbol="{self.space_symbol}"'
  77. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  78. f")"
  79. )
  80. class Hypothesis(NamedTuple):
  81. """Hypothesis data type."""
  82. yseq: np.ndarray
  83. score: Union[float, np.ndarray] = 0
  84. scores: Dict[str, Union[float, np.ndarray]] = dict()
  85. states: Dict[str, Any] = dict()
  86. def asdict(self) -> dict:
  87. """Convert data to JSON-friendly dict."""
  88. return self._replace(
  89. yseq=self.yseq.tolist(),
  90. score=float(self.score),
  91. scores={k: float(v) for k, v in self.scores.items()},
  92. )._asdict()
  93. def read_yaml(yaml_path: Union[str, Path]) -> Dict:
  94. if not Path(yaml_path).exists():
  95. raise FileExistsError(f'The {yaml_path} does not exist.')
  96. with open(str(yaml_path), 'rb') as f:
  97. data = yaml.load(f, Loader=yaml.Loader)
  98. return data
  99. @functools.lru_cache()
  100. def get_logger(name='funasr_torch'):
  101. """Initialize and get a logger by name.
  102. If the logger has not been initialized, this method will initialize the
  103. logger by adding one or two handlers, otherwise the initialized logger will
  104. be directly returned. During initialization, a StreamHandler will always be
  105. added.
  106. Args:
  107. name (str): Logger name.
  108. Returns:
  109. logging.Logger: The expected logger.
  110. """
  111. logger = logging.getLogger(name)
  112. if name in logger_initialized:
  113. return logger
  114. for logger_name in logger_initialized:
  115. if name.startswith(logger_name):
  116. return logger
  117. formatter = logging.Formatter(
  118. '[%(asctime)s] %(name)s %(levelname)s: %(message)s',
  119. datefmt="%Y/%m/%d %H:%M:%S")
  120. sh = logging.StreamHandler()
  121. sh.setFormatter(formatter)
  122. logger.addHandler(sh)
  123. logger_initialized[name] = True
  124. logger.propagate = False
  125. return logger