char_tokenizer.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from pathlib import Path
  2. from typing import Iterable
  3. from typing import List
  4. from typing import Union
  5. import warnings
  6. from funasr.tokenizer.abs_tokenizer import BaseTokenizer
  7. from funasr.register import tables
  8. @tables.register("tokenizer_classes", "CharTokenizer")
  9. class CharTokenizer(BaseTokenizer):
  10. def __init__(
  11. self,
  12. non_linguistic_symbols: Union[Path, str, Iterable[str]] = None,
  13. space_symbol: str = "<space>",
  14. remove_non_linguistic_symbols: bool = False,
  15. **kwargs,
  16. ):
  17. super().__init__(**kwargs)
  18. self.space_symbol = space_symbol
  19. if non_linguistic_symbols is None:
  20. self.non_linguistic_symbols = set()
  21. elif isinstance(non_linguistic_symbols, (Path, str)):
  22. non_linguistic_symbols = Path(non_linguistic_symbols)
  23. try:
  24. with non_linguistic_symbols.open("r", encoding="utf-8") as f:
  25. self.non_linguistic_symbols = set(line.rstrip() for line in f)
  26. except FileNotFoundError:
  27. warnings.warn(f"{non_linguistic_symbols} doesn't exist.")
  28. self.non_linguistic_symbols = set()
  29. else:
  30. self.non_linguistic_symbols = set(non_linguistic_symbols)
  31. self.remove_non_linguistic_symbols = remove_non_linguistic_symbols
  32. def __repr__(self):
  33. return (
  34. f"{self.__class__.__name__}("
  35. f'space_symbol="{self.space_symbol}"'
  36. f'non_linguistic_symbols="{self.non_linguistic_symbols}"'
  37. f")"
  38. )
  39. def text2tokens(self, line: Union[str, list]) -> List[str]:
  40. tokens = []
  41. while len(line) != 0:
  42. for w in self.non_linguistic_symbols:
  43. if line.startswith(w):
  44. if not self.remove_non_linguistic_symbols:
  45. tokens.append(line[: len(w)])
  46. line = line[len(w) :]
  47. break
  48. else:
  49. t = line[0]
  50. if t == " ":
  51. t = "<space>"
  52. tokens.append(t)
  53. line = line[1:]
  54. return tokens
  55. def tokens2text(self, tokens: Iterable[str]) -> str:
  56. tokens = [t if t != self.space_symbol else " " for t in tokens]
  57. return "".join(tokens)