Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2021 The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Tokenization classes for RoFormer."""16 17import json18from typing import Optional19 20from tokenizers import normalizers21from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer22 23from ...tokenization_utils_fast import PreTrainedTokenizerFast24from ...utils import logging25from .tokenization_roformer import RoFormerTokenizer26from .tokenization_utils import JiebaPreTokenizer27 28 29logger = logging.get_logger(__name__)30 31VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}32 33 34class RoFormerTokenizerFast(PreTrainedTokenizerFast):35 r"""36 Construct a "fast" RoFormer tokenizer (backed by HuggingFace's *tokenizers* library).37 38 [`RoFormerTokenizerFast`] is almost identical to [`BertTokenizerFast`] and runs end-to-end tokenization:39 punctuation splitting and wordpiece. There are some difference between them when tokenizing Chinese.40 41 This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should42 refer to this superclass for more information regarding those methods.43 44 Example:45 46 ```python47 >>> from transformers import RoFormerTokenizerFast48 49 >>> tokenizer = RoFormerTokenizerFast.from_pretrained("junnyu/roformer_chinese_base")50 >>> tokenizer.tokenize("今天天气非常好。")51 ['今', '天', '天', '气', '非常', '好', '。']52 ```"""53 54 vocab_files_names = VOCAB_FILES_NAMES55 slow_tokenizer_class = RoFormerTokenizer56 57 def __init__(58 self,59 vocab_file=None,60 tokenizer_file=None,61 do_lower_case=True,62 unk_token="[UNK]",63 sep_token="[SEP]",64 pad_token="[PAD]",65 cls_token="[CLS]",66 mask_token="[MASK]",67 tokenize_chinese_chars=True,68 strip_accents=None,69 **kwargs,70 ):71 super().__init__(72 vocab_file,73 tokenizer_file=tokenizer_file,74 do_lower_case=do_lower_case,75 unk_token=unk_token,76 sep_token=sep_token,77 pad_token=pad_token,78 cls_token=cls_token,79 mask_token=mask_token,80 tokenize_chinese_chars=tokenize_chinese_chars,81 strip_accents=strip_accents,82 **kwargs,83 )84 85 normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())86 if (87 normalizer_state.get("lowercase", do_lower_case) != do_lower_case88 or normalizer_state.get("strip_accents", strip_accents) != strip_accents89 ):90 normalizer_class = getattr(normalizers, normalizer_state.pop("type"))91 normalizer_state["lowercase"] = do_lower_case92 normalizer_state["strip_accents"] = strip_accents93 self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)94 95 # Make sure we correctly set the custom PreTokenizer96 vocab = self.backend_tokenizer.get_vocab()97 self.backend_tokenizer.pre_tokenizer = PreTokenizer.custom(JiebaPreTokenizer(vocab))98 99 self.do_lower_case = do_lower_case100 101 def __getstate__(self):102 state = self.__dict__.copy()103 state["_tokenizer"].pre_tokenizer = BertPreTokenizer()104 return state105 106 def __setstate__(self, d):107 self.__dict__ = d108 vocab = self.__dict__["_tokenizer"].get_vocab()109 self.__dict__["_tokenizer"].pre_tokenizer = PreTokenizer.custom(JiebaPreTokenizer(vocab))110 111 def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):112 """113 Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and114 adding special tokens. A RoFormer sequence has the following format:115 116 - single sequence: `[CLS] X [SEP]`117 - pair of sequences: `[CLS] A [SEP] B [SEP]`118 119 Args:120 token_ids_0 (`List[int]`):121 List of IDs to which the special tokens will be added.122 token_ids_1 (`List[int]`, *optional*):123 Optional second list of IDs for sequence pairs.124 125 Returns:126 `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.127 """128 output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]129 130 if token_ids_1 is not None:131 output += token_ids_1 + [self.sep_token_id]132 133 return output134 135 def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:136 files = self._tokenizer.model.save(save_directory, name=filename_prefix)137 return tuple(files)138 139 def save_pretrained(140 self,141 save_directory,142 legacy_format=None,143 filename_prefix=None,144 push_to_hub=False,145 **kwargs,146 ):147 self.backend_tokenizer.pre_tokenizer = BertPreTokenizer()148 return super().save_pretrained(save_directory, legacy_format, filename_prefix, push_to_hub, **kwargs)149 150 151__all__ = ["RoFormerTokenizerFast"]152 