utils.py 4.6 KB

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