tokenizer.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from tokenizers import Tokenizer
  15. class JiebaBPETokenizer:
  16. """SentencePiece BPE tokenizer with Jieba integration"""
  17. def __init__(self, tokenizer_json_file):
  18. self.name = 'Jieba BPE Tokenizer'
  19. self.tokenizer = Tokenizer.from_file(tokenizer_json_file)
  20. self.eod_id = self.tokenizer.token_to_id('<|endoftext|>')
  21. try:
  22. import jieba
  23. except ImportError:
  24. raise ImportError(
  25. 'You need to install rjieba to use JiebaTokenizer. '
  26. 'See https://pypi.org/project/rjieba/ for installation.')
  27. self.jieba = jieba
  28. self.new_line = self.vocab['\n']
  29. self.sep_token = self.vocab['<sep>']
  30. @property
  31. def vocab_size(self):
  32. return self.tokenizer.get_vocab_size(with_added_tokens=True)
  33. @property
  34. def vocab(self):
  35. return self.tokenizer.get_vocab(with_added_tokens=True)
  36. @property
  37. def inv_vocab(self):
  38. vocab = self.vocab
  39. inv_vocab = dict()
  40. for key, val in vocab.items():
  41. inv_vocab[val] = key
  42. return inv_vocab
  43. def tokenize(self, text, is_code=False):
  44. if not is_code:
  45. seg_list = [x for x in self.jieba.cut(text)]
  46. return self.tokenizer.encode(
  47. seg_list, is_pretokenized=True, add_special_tokens=True).ids
  48. else:
  49. return self.tokenizer.encode(
  50. text, is_pretokenized=False, add_special_tokens=True).ids
  51. def detokenize(self, token_ids):
  52. text = self.tokenizer.decode(token_ids, skip_special_tokens=False)
  53. return text
  54. @property
  55. def eod(self):
  56. return self.eod_id