Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2023 The Facebook Inc. and 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 class for SpeechT5."""16 17import os18from shutil import copyfile19from typing import Any, Optional20 21import sentencepiece as spm22 23from ...tokenization_utils import PreTrainedTokenizer24from ...utils import logging25from ...utils.import_utils import requires26from .number_normalizer import EnglishNumberNormalizer27 28 29logger = logging.get_logger(__name__)30 31VOCAB_FILES_NAMES = {"vocab_file": "spm_char.model"}32 33 34@requires(backends=("sentencepiece",))35class SpeechT5Tokenizer(PreTrainedTokenizer):36 """37 Construct a SpeechT5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).38 39 This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to40 this superclass for more information regarding those methods.41 42 Args:43 vocab_file (`str`):44 [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that45 contains the vocabulary necessary to instantiate a tokenizer.46 bos_token (`str`, *optional*, defaults to `"<s>"`):47 The begin of sequence token.48 eos_token (`str`, *optional*, defaults to `"</s>"`):49 The end of sequence token.50 unk_token (`str`, *optional*, defaults to `"<unk>"`):51 The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this52 token instead.53 pad_token (`str`, *optional*, defaults to `"<pad>"`):54 The token used for padding, for example when batching sequences of different lengths.55 normalize (`bool`, *optional*, defaults to `False`):56 Whether to convert numeric quantities in the text to their spelt-out english counterparts.57 sp_model_kwargs (`dict`, *optional*):58 Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for59 SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,60 to set:61 62 - `enable_sampling`: Enable subword regularization.63 - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.64 65 - `nbest_size = {0,1}`: No sampling is performed.66 - `nbest_size > 1`: samples from the nbest_size results.67 - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)68 using forward-filtering-and-backward-sampling algorithm.69 70 - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for71 BPE-dropout.72 73 Attributes:74 sp_model (`SentencePieceProcessor`):75 The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).76 """77 78 vocab_files_names = VOCAB_FILES_NAMES79 model_input_names = ["input_ids", "attention_mask"]80 81 def __init__(82 self,83 vocab_file,84 bos_token="<s>",85 eos_token="</s>",86 unk_token="<unk>",87 pad_token="<pad>",88 normalize=False,89 sp_model_kwargs: Optional[dict[str, Any]] = None,90 **kwargs,91 ) -> None:92 self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs93 self.vocab_file = vocab_file94 self.normalize = normalize95 self._normalizer = None96 97 self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)98 self.sp_model.Load(vocab_file)99 100 super().__init__(101 bos_token=bos_token,102 eos_token=eos_token,103 unk_token=unk_token,104 pad_token=pad_token,105 normalize=normalize,106 sp_model_kwargs=self.sp_model_kwargs,107 **kwargs,108 )109 110 def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):111 normalize = kwargs.pop("normalize", self.normalize)112 if is_split_into_words:113 text = " " + text114 if normalize:115 text = self.normalizer(text)116 return (text, kwargs)117 118 @property119 def vocab_size(self):120 return self.sp_model.get_piece_size()121 122 @property123 def normalizer(self):124 if self._normalizer is None:125 self._normalizer = EnglishNumberNormalizer()126 return self._normalizer127 128 @normalizer.setter129 def normalizer(self, value):130 self._normalizer = value131 132 def get_vocab(self):133 vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}134 vocab.update(self.added_tokens_encoder)135 return vocab136 137 def __getstate__(self):138 state = self.__dict__.copy()139 state["sp_model"] = None140 return state141 142 def __setstate__(self, d):143 self.__dict__ = d144 145 # for backward compatibility146 if not hasattr(self, "sp_model_kwargs"):147 self.sp_model_kwargs = {}148 149 self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)150 self.sp_model.Load(self.vocab_file)151 152 def _tokenize(self, text: str) -> list[str]:153 """Take as input a string and return a list of strings (tokens) for words/sub-words"""154 return self.sp_model.encode(text, out_type=str)155 156 def _convert_token_to_id(self, token):157 """Converts a token (str) in an id using the vocab."""158 return self.sp_model.piece_to_id(token)159 160 def _convert_id_to_token(self, index):161 """Converts an index (integer) in a token (str) using the vocab."""162 token = self.sp_model.IdToPiece(index)163 return token164 165 # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string166 def convert_tokens_to_string(self, tokens):167 """Converts a sequence of tokens (string) in a single string."""168 current_sub_tokens = []169 out_string = ""170 prev_is_special = False171 for token in tokens:172 # make sure that special tokens are not decoded using sentencepiece model173 if token in self.all_special_tokens:174 if not prev_is_special:175 out_string += " "176 out_string += self.sp_model.decode(current_sub_tokens) + token177 prev_is_special = True178 current_sub_tokens = []179 else:180 current_sub_tokens.append(token)181 prev_is_special = False182 out_string += self.sp_model.decode(current_sub_tokens)183 return out_string.strip()184 185 def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:186 """Build model inputs from a sequence by appending eos_token_id."""187 if token_ids_1 is None:188 return token_ids_0 + [self.eos_token_id]189 # We don't expect to process pairs, but leave the pair logic for API consistency190 return token_ids_0 + token_ids_1 + [self.eos_token_id]191 192 def get_special_tokens_mask(193 self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False194 ) -> list[int]:195 if already_has_special_tokens:196 return super().get_special_tokens_mask(197 token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True198 )199 200 suffix_ones = [1]201 if token_ids_1 is None:202 return ([0] * len(token_ids_0)) + suffix_ones203 return ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones204 205 def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:206 if not os.path.isdir(save_directory):207 logger.error(f"Vocabulary path ({save_directory}) should be a directory")208 return209 out_vocab_file = os.path.join(210 save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]211 )212 213 if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):214 copyfile(self.vocab_file, out_vocab_file)215 elif not os.path.isfile(self.vocab_file):216 with open(out_vocab_file, "wb") as fi:217 content_spiece_model = self.sp_model.serialized_model_proto()218 fi.write(content_spiece_model)219 220 return (out_vocab_file,)221 222 223__all__ = ["SpeechT5Tokenizer"]224 