char_tokenizer.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. from pathlib import Path
  2. from typing import Iterable
  3. from typing import List
  4. from typing import Union
  5. import warnings
  6. import re
  7. from funasr.tokenizer.abs_tokenizer import BaseTokenizer
  8. from funasr.register import tables
  9. @tables.register("tokenizer_classes", "CharTokenizer")
  10. class CharTokenizer(BaseTokenizer):
  11. def __init__(
  12. self,
  13. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  14. space_symbol: str = "<space>",
  15. remove_non_linguistic_symbols: bool = False,
  16. split_with_space: bool = False,
  17. seg_dict: str = None,
  18. **kwargs,
  19. ):
  20. super().__init__(**kwargs)
  21. self.space_symbol = space_symbol
  22. if non_linguistic_symbols is None:
  23. self.non_linguistic_symbols = set()
  24. elif isinstance(non_linguistic_symbols, (Path, str)):
  25. non_linguistic_symbols = Path(non_linguistic_symbols)
  26. try:
  27. with non_linguistic_symbols.open("r", encoding="utf-8") as f:
  28. self.non_linguistic_symbols = set(line.rstrip() for line in f)
  29. except FileNotFoundError:
  30. warnings.warn(f"{non_linguistic_symbols} doesn't exist.")
  31. self.non_linguistic_symbols = set()
  32. else:
  33. self.non_linguistic_symbols = set(non_linguistic_symbols)
  34. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  35. self.split_with_space = split_with_space
  36. self.seg_dict = None
  37. if seg_dict is not None:
  38. self.seg_dict = load_seg_dict(seg_dict)
  39. def __repr__(self):
  40. return (
  41. f"{self.__class__.__name__}("
  42. f'space_symbol="{self.space_symbol}"'
  43. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  44. f")"
  45. )
  46. def text2tokens(self, line: Union[str, list]) -> List[str]:
  47. # if self.split_with_space:
  48. if self.seg_dict is not None:
  49. tokens = line.strip().split(" ")
  50. tokens = seg_tokenize(tokens, self.seg_dict)
  51. else:
  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. line = line[1:]
  65. continue
  66. tokens.append(t)
  67. line = line[1:]
  68. return tokens
  69. def tokens2text(self, tokens: Iterable[str]) -> str:
  70. tokens = [t if t != self.space_symbol else " " for t in tokens]
  71. return "".join(tokens)
  72. def load_seg_dict(seg_dict_file):
  73. seg_dict = {}
  74. assert isinstance(seg_dict_file, str)
  75. with open(seg_dict_file, "r", encoding="utf8") as f:
  76. lines = f.readlines()
  77. for line in lines:
  78. s = line.strip().split()
  79. key = s[0]
  80. value = s[1:]
  81. seg_dict[key] = " ".join(value)
  82. return seg_dict
  83. def seg_tokenize(txt, seg_dict):
  84. pattern = re.compile(r'^[\u4E00-\u9FA50-9]+$')
  85. out_txt = ""
  86. for word in txt:
  87. word = word.lower()
  88. if word in seg_dict:
  89. out_txt += seg_dict[word] + " "
  90. else:
  91. if pattern.match(word):
  92. for char in word:
  93. if char in seg_dict:
  94. out_txt += seg_dict[char] + " "
  95. else:
  96. out_txt += "<unk>" + " "
  97. else:
  98. out_txt += "<unk>" + " "
  99. return out_txt.strip().split()