You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

bert_tokenizer.py 14 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. from __future__ import absolute_import, division, print_function, unicode_literals
  2. import collections
  3. import os
  4. import unicodedata
  5. import six
  6. from io import open
  7. from .utils import cached_path
  8. PRETRAINED_VOCAB_ARCHIVE_MAP = {
  9. 'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
  10. 'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
  11. 'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
  12. 'bert-large-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt",
  13. 'bert-base-multilingual-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt",
  14. 'bert-base-multilingual-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt",
  15. 'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
  16. }
  17. PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP = {
  18. 'bert-base-uncased': 512,
  19. 'bert-large-uncased': 512,
  20. 'bert-base-cased': 512,
  21. 'bert-large-cased': 512,
  22. 'bert-base-multilingual-uncased': 512,
  23. 'bert-base-multilingual-cased': 512,
  24. 'bert-base-chinese': 512,
  25. }
  26. VOCAB_NAME = 'vocab.txt'
  27. def convert_to_unicode(text):
  28. """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  29. if six.PY3:
  30. if isinstance(text, str):
  31. return text
  32. elif isinstance(text, bytes):
  33. return text.decode("utf-8", "ignore")
  34. else:
  35. raise ValueError("Unsupported string type: %s" % (type(text)))
  36. elif six.PY2:
  37. if isinstance(text, str):
  38. return text.decode("utf-8", "ignore")
  39. elif isinstance(text, unicode):
  40. return text
  41. else:
  42. raise ValueError("Unsupported string type: %s" % (type(text)))
  43. else:
  44. raise ValueError("Not running on Python2 or Python 3?")
  45. def load_vocab(vocab_file):
  46. """Loads a vocabulary file into a dictionary."""
  47. vocab = collections.OrderedDict()
  48. index = 0
  49. with open(vocab_file, "r", encoding="utf-8") as reader:
  50. while True:
  51. token = reader.readline()
  52. if not token:
  53. break
  54. token = token.strip()
  55. vocab[token] = index
  56. index += 1
  57. return vocab
  58. def whitespace_tokenize(text):
  59. """Runs basic whitespace cleaning and splitting on a piece of text."""
  60. text = text.strip()
  61. if not text:
  62. return []
  63. tokens = text.split()
  64. return tokens
  65. class BertTokenizer(object):
  66. """Runs end-to-end tokenization: punctuation splitting + wordpiece"""
  67. def __init__(self, vocab_file, do_lower_case=True, max_len=None,
  68. never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
  69. if not os.path.isfile(vocab_file):
  70. raise ValueError(
  71. "Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained "
  72. "model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file))
  73. self.vocab = load_vocab(vocab_file)
  74. self.ids_to_tokens = collections.OrderedDict(
  75. [(ids, tok) for tok, ids in self.vocab.items()])
  76. self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,
  77. never_split=never_split)
  78. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
  79. self.max_len = max_len if max_len is not None else int(1e12)
  80. def tokenize(self, text):
  81. split_tokens = []
  82. for token in self.basic_tokenizer.tokenize(text):
  83. for sub_token in self.wordpiece_tokenizer.tokenize(token):
  84. split_tokens.append(sub_token)
  85. return split_tokens
  86. def convert_tokens_to_ids(self, tokens):
  87. """Converts a sequence of tokens into ids using the vocab."""
  88. ids = []
  89. for token in tokens:
  90. ids.append(self.vocab[token])
  91. if len(ids) > self.max_len:
  92. raise ValueError(
  93. "Token indices sequence length is longer than the specified maximum "
  94. " sequence length for this BERT model ({} > {}). Running this"
  95. " sequence through BERT will result in indexing errors".format(
  96. len(ids), self.max_len)
  97. )
  98. return ids
  99. def convert_ids_to_tokens(self, ids):
  100. """Converts a sequence of ids in wordpiece tokens using the vocab."""
  101. tokens = []
  102. for i in ids:
  103. tokens.append(self.ids_to_tokens[i])
  104. return tokens
  105. @classmethod
  106. def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
  107. """
  108. Instantiate a PreTrainedBertModel from a pre-trained model file.
  109. Download and cache the pre-trained model file if needed.
  110. """
  111. if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP:
  112. vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path]
  113. else:
  114. vocab_file = pretrained_model_name_or_path
  115. if os.path.isdir(vocab_file):
  116. vocab_file = os.path.join(vocab_file, VOCAB_NAME)
  117. # redirect to the cache, if necessary
  118. try:
  119. resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir)
  120. except EnvironmentError:
  121. print(
  122. "Model name '{}' was not found in model name list ({}). "
  123. "We assumed '{}' was a path or url but couldn't find any file "
  124. "associated to this path or url.".format(
  125. pretrained_model_name_or_path,
  126. ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()),
  127. vocab_file))
  128. return None
  129. if resolved_vocab_file == vocab_file:
  130. print("loading vocabulary file {}".format(vocab_file))
  131. else:
  132. print("loading vocabulary file {} from cache at {}".format(
  133. vocab_file, resolved_vocab_file))
  134. if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP:
  135. # if we're using a pretrained model, ensure the tokenizer wont index sequences longer
  136. # than the number of positional embeddings
  137. max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path]
  138. kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)
  139. # Instantiate tokenizer.
  140. tokenizer = cls(resolved_vocab_file, *inputs, **kwargs)
  141. return tokenizer
  142. class BasicTokenizer(object):
  143. """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
  144. def __init__(self,
  145. do_lower_case=True,
  146. never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
  147. """Constructs a BasicTokenizer.
  148. Args:
  149. do_lower_case: Whether to lower case the input.
  150. """
  151. self.do_lower_case = do_lower_case
  152. self.never_split = never_split
  153. def tokenize(self, text):
  154. """Tokenizes a piece of text."""
  155. text = self._clean_text(text)
  156. text = self._tokenize_chinese_chars(text)
  157. orig_tokens = whitespace_tokenize(text)
  158. split_tokens = []
  159. for token in orig_tokens:
  160. if self.do_lower_case and token not in self.never_split:
  161. token = token.lower()
  162. token = self._run_strip_accents(token)
  163. split_tokens.extend(self._run_split_on_punc(token))
  164. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  165. return output_tokens
  166. def _run_strip_accents(self, text):
  167. """Strips accents from a piece of text."""
  168. text = unicodedata.normalize("NFD", text)
  169. output = []
  170. for char in text:
  171. cat = unicodedata.category(char)
  172. if cat == "Mn":
  173. continue
  174. output.append(char)
  175. return "".join(output)
  176. def _run_split_on_punc(self, text):
  177. """Splits punctuation on a piece of text."""
  178. if text in self.never_split:
  179. return [text]
  180. chars = list(text)
  181. i = 0
  182. start_new_word = True
  183. output = []
  184. while i < len(chars):
  185. char = chars[i]
  186. if _is_punctuation(char):
  187. output.append([char])
  188. start_new_word = True
  189. else:
  190. if start_new_word:
  191. output.append([])
  192. start_new_word = False
  193. output[-1].append(char)
  194. i += 1
  195. return ["".join(x) for x in output]
  196. def _tokenize_chinese_chars(self, text):
  197. """Adds whitespace around any CJK character."""
  198. output = []
  199. for char in text:
  200. cp = ord(char)
  201. if self._is_chinese_char(cp):
  202. output.append(" ")
  203. output.append(char)
  204. output.append(" ")
  205. else:
  206. output.append(char)
  207. return "".join(output)
  208. def _is_chinese_char(self, cp):
  209. """Checks whether CP is the codepoint of a CJK character."""
  210. # This defines a "chinese character" as anything in the CJK Unicode block:
  211. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  212. #
  213. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  214. # despite its name. The modern Korean Hangul alphabet is a different block,
  215. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  216. # space-separated words, so they are not treated specially and handled
  217. # like the all of the other languages.
  218. if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
  219. (cp >= 0x3400 and cp <= 0x4DBF) or #
  220. (cp >= 0x20000 and cp <= 0x2A6DF) or #
  221. (cp >= 0x2A700 and cp <= 0x2B73F) or #
  222. (cp >= 0x2B740 and cp <= 0x2B81F) or #
  223. (cp >= 0x2B820 and cp <= 0x2CEAF) or
  224. (cp >= 0xF900 and cp <= 0xFAFF) or #
  225. (cp >= 0x2F800 and cp <= 0x2FA1F)): #
  226. return True
  227. return False
  228. def _clean_text(self, text):
  229. """Performs invalid character removal and whitespace cleanup on text."""
  230. output = []
  231. for char in text:
  232. cp = ord(char)
  233. if cp == 0 or cp == 0xfffd or _is_control(char):
  234. continue
  235. if _is_whitespace(char):
  236. output.append(" ")
  237. else:
  238. output.append(char)
  239. return "".join(output)
  240. class WordpieceTokenizer(object):
  241. """Runs WordPiece tokenization."""
  242. def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100):
  243. self.vocab = vocab
  244. self.unk_token = unk_token
  245. self.max_input_chars_per_word = max_input_chars_per_word
  246. def tokenize(self, text):
  247. """Tokenizes a piece of text into its word pieces.
  248. This uses a greedy longest-match-first algorithm to perform tokenization
  249. using the given vocabulary.
  250. For example:
  251. input = "unaffable"
  252. output = ["un", "##aff", "##able"]
  253. Args:
  254. text: A single token or whitespace separated tokens. This should have
  255. already been passed through `BasicTokenizer`.
  256. Returns:
  257. A list of wordpiece tokens.
  258. """
  259. output_tokens = []
  260. for token in whitespace_tokenize(text):
  261. chars = list(token)
  262. if len(chars) > self.max_input_chars_per_word:
  263. output_tokens.append(self.unk_token)
  264. continue
  265. is_bad = False
  266. start = 0
  267. sub_tokens = []
  268. while start < len(chars):
  269. end = len(chars)
  270. cur_substr = None
  271. while start < end:
  272. substr = "".join(chars[start:end])
  273. if start > 0:
  274. substr = "##" + substr
  275. if substr in self.vocab:
  276. cur_substr = substr
  277. break
  278. end -= 1
  279. if cur_substr is None:
  280. is_bad = True
  281. break
  282. sub_tokens.append(cur_substr)
  283. start = end
  284. if is_bad:
  285. output_tokens.append(self.unk_token)
  286. else:
  287. output_tokens.extend(sub_tokens)
  288. return output_tokens
  289. def _is_whitespace(char):
  290. """Checks whether `chars` is a whitespace character."""
  291. # \t, \n, and \r are technically contorl characters but we treat them
  292. # as whitespace since they are generally considered as such.
  293. if char == " " or char == "\t" or char == "\n" or char == "\r":
  294. return True
  295. cat = unicodedata.category(char)
  296. if cat == "Zs":
  297. return True
  298. return False
  299. def _is_control(char):
  300. """Checks whether `chars` is a control character."""
  301. # These are technically control characters but we count them as whitespace
  302. # characters.
  303. if char == "\t" or char == "\n" or char == "\r":
  304. return False
  305. cat = unicodedata.category(char)
  306. if cat.startswith("C"):
  307. return True
  308. return False
  309. def _is_punctuation(char):
  310. """Checks whether `chars` is a punctuation character."""
  311. cp = ord(char)
  312. # We treat all non-letter/number ASCII as punctuation.
  313. # Characters such as "^", "$", and "`" are not in the Unicode
  314. # Punctuation class but we treat them as punctuation anyways, for
  315. # consistency.
  316. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
  317. (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
  318. return True
  319. cat = unicodedata.category(char)
  320. if cat.startswith("P"):
  321. return True
  322. return False