


'''simple docstring'''






import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


a_   :      Union[str, Any]				    =      logging.get_logger(__name__)

a_   :      Union[str, Any]				    =      {"vocab_file": "spiece.model"}

a_   :      List[Any]				    =      {
    "vocab_file": {
        "bert_for_seq_generation": (
            "https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model"
        ),
    }
}

a_   :      Dict				    =      {"bert_for_seq_generation": 5_1_2}




class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		VOCAB_FILES_NAMES
 _lowerCAmelCase	   =		PRETRAINED_VOCAB_FILES_MAP
 _lowerCAmelCase	   =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCAmelCase	   =		[]
 _lowerCAmelCase	   =		["""input_ids""", """attention_mask"""]
 def __init__(	self      ,			__magic_name__      ,			__magic_name__="<s>"      ,			__magic_name__="</s>"      ,			__magic_name__="<unk>"      ,			__magic_name__="<pad>"      ,			__magic_name__="<::::>"      ,			__magic_name__ = None      ,			**__magic_name__      ,			)   ->							None:
      _a      =							{} if sp_model_kwargs is None else sp_model_kwargs

      # Add extra_ids to the special token list
      super().__init__(
          bos_token=__magic_name__      ,			eos_token=__magic_name__      ,			unk_token=__magic_name__      ,			pad_token=__magic_name__      ,			sep_token=__magic_name__      ,			sp_model_kwargs=self.sp_model_kwargs      ,			**__magic_name__      ,			)

      _a      =							vocab_file

      _a      =							spm.SentencePieceProcessor(**self.sp_model_kwargs  )
      self.sp_model.Load(__magic_name__  )
 @property
 def 							__UpperCAmelCase						(	self  )   ->							Dict:
      return self.sp_model.get_piece_size()
 def 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							{self.convert_ids_to_tokens(__magic_name__  ): i for i in range(self.vocab_size  )}
      vocab.update(self.added_tokens_encoder  )
      return vocab
 def __getstate__(	self  )   ->							Any:
      _a      =							self.__dict__.copy()
      _a      =							None
      return state
 def __setstate__(	self      ,			__magic_name__  )   ->							int:
      _a      =							d

      # for backward compatibility
      if not hasattr(self      ,			'sp_model_kwargs'  ):
           _a      =							{}

      _a      =							spm.SentencePieceProcessor(**self.sp_model_kwargs  )
      self.sp_model.Load(self.vocab_file  )
 def 							__UpperCAmelCase						(	self      ,			__magic_name__  )   ->							List[str]:
      return self.sp_model.encode(__magic_name__      ,			out_type=__magic_name__  )
 def 							__UpperCAmelCase						(	self      ,			__magic_name__  )   ->							List[str]:
      return self.sp_model.piece_to_id(__magic_name__  )
 def 							__UpperCAmelCase						(	self      ,			__magic_name__  )   ->							List[str]:
      _a      =							self.sp_model.IdToPiece(__magic_name__  )
      return token
 def 							__UpperCAmelCase						(	self      ,			__magic_name__  )   ->							Optional[Any]:
      _a      =							[]
      _a      =							''
      for token in tokens:
           # make sure that special tokens are not decoded using sentencepiece model
           if token in self.all_special_tokens:
                out_string += self.sp_model.decode(__magic_name__  ) + token
                _a      =							[]
           else:
                current_sub_tokens.append(__magic_name__  )
      out_string += self.sp_model.decode(__magic_name__  )
      return out_string.strip()




 def 							__UpperCAmelCase						(	self      ,			__magic_name__      ,			__magic_name__ = None  )   ->							Tuple[str]:
      if not os.path.isdir(__magic_name__  ):
           logger.error(f'Vocabulary path ({save_directory}) should be a directory'  )
           return
      _a      =							os.path.join(
          __magic_name__      ,			(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )

      if os.path.abspath(self.vocab_file  ) != os.path.abspath(__magic_name__  ) and os.path.isfile(self.vocab_file  ):
           copyfile(self.vocab_file      ,			__magic_name__  )
      elif not os.path.isfile(self.vocab_file  ):
           with open(__magic_name__      ,			'wb'  ) as fi:
                _a      =							self.sp_model.serialized_model_proto()
                fi.write(__magic_name__  )

      return (out_vocab_file,)





'''simple docstring'''






from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


a_   :      List[str]				    =      logging.get_logger(__name__)




class 	a       (       _SCREAMING_SNAKE_CASE    ):
 def __init__(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__ ,			**__magic_name__  )   ->							Any:
      _a      =							feature_size
      _a      =							sampling_rate
      _a      =							padding_value

      _a      =							kwargs.pop('padding_side' ,			'right'  )
      _a      =							kwargs.pop('return_attention_mask' ,			__magic_name__  )

      super().__init__(**__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ = True ,			__magic_name__ = None ,			__magic_name__ = False ,			__magic_name__ = None ,			__magic_name__ = None ,			__magic_name__ = None ,			)   ->							BatchFeature:
      # If we have a list of dicts, let's convert it in a dict of lists
      # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
      if isinstance(__magic_name__ ,			(list, tuple)  ) and isinstance(processed_features[0] ,			(dict, BatchFeature)  ):
           _a      =							{
               key: [example[key] for example in processed_features] for key in processed_features[0].keys()
           }

      # The model's main input name, usually `input_values`, has be passed for padding
      if self.model_input_names[0] not in processed_features:
           raise ValueError(
               'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`'
               f' to this method that includes {self.model_input_names[0]}, but you provided'
               f' {list(processed_features.keys()  )}'  )

      _a      =							processed_features[self.model_input_names[0]]
      _a      =							(
          return_attention_mask if return_attention_mask is not None else self.return_attention_mask
      )

      if len(__magic_name__  ) == 0:
           if return_attention_mask:
                _a      =							[]
           return processed_features

      # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
      # and rebuild them afterwards if no return_tensors is specified
      # Note that we lose the specific device the tensor may be on for PyTorch

      _a      =							required_input[0]
      if isinstance(__magic_name__ ,			(list, tuple)  ):
           # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
           _a      =							0
           while len(required_input[index]  ) == 0:
                index += 1
           if index < len(__magic_name__  ):
                _a      =							required_input[index][0]

      if return_tensors is None:
           if is_tf_tensor(__magic_name__  ):
                _a      =							'tf'
           elif is_torch_tensor(__magic_name__  ):
                _a      =							'pt'
           elif isinstance(__magic_name__ ,			(int, float, list, tuple, np.ndarray)  ):
                _a      =							'np'
           else:
                raise ValueError(
                    f'type of {first_element} unknown: {type(__magic_name__  )}. '
                    'Should be one of a python, numpy, pytorch or tensorflow object.'  )

      for key, value in processed_features.items():
           if isinstance(value[0] ,			(int, float)  ):
                _a      =							to_numpy(__magic_name__  )
           else:
                _a      =							[to_numpy(__magic_name__  ) for v in value]

        # Convert padding_strategy in PaddingStrategy
      _a      =							self._get_padding_strategies(padding=__magic_name__ ,			max_length=__magic_name__  )

      _a      =							processed_features[self.model_input_names[0]]

      _a      =							len(__magic_name__  )
      if not all(len(__magic_name__  ) == batch_size for v in processed_features.values()  ):
           raise ValueError('Some items in the output dictionary have a different batch size than others.'  )

      _a      =							[]
      for i in range(__magic_name__  ):
           _a      =							{k: v[i] for k, v in processed_features.items()}
           # truncation
           _a      =							self._truncate(
               __magic_name__ ,			max_length=__magic_name__ ,			pad_to_multiple_of=__magic_name__ ,			truncation=__magic_name__ ,			)
           truncated_inputs.append(__magic_name__  )

      if padding_strategy == PaddingStrategy.LONGEST:
           # make sure that `max_length` cannot be longer than the longest truncated length
           _a      =							max(len(input_slice[self.model_input_names[0]]  ) for input_slice in truncated_inputs  )
           _a      =							PaddingStrategy.MAX_LENGTH

      _a      =							{}
      for i in range(__magic_name__  ):
           # padding
           _a      =							self._pad(
               truncated_inputs[i] ,			max_length=__magic_name__ ,			padding_strategy=__magic_name__ ,			pad_to_multiple_of=__magic_name__ ,			return_attention_mask=__magic_name__ ,			)

           for key, value in outputs.items():
                if key not in batch_outputs:
                     _a      =							[]
                if value.dtype is np.dtype(np.floataa  ):
                     _a      =							value.astype(np.floataa  )
                batch_outputs[key].append(__magic_name__  )

      return BatchFeature(__magic_name__ ,			tensor_type=__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ = None ,			__magic_name__ = PaddingStrategy.DO_NOT_PAD ,			__magic_name__ = None ,			__magic_name__ = None ,			)   ->							dict:
      _a      =							processed_features[self.model_input_names[0]]

      if padding_strategy == PaddingStrategy.LONGEST:
           _a      =							len(__magic_name__  )

      if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
           _a      =							((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

      _a      =							padding_strategy != PaddingStrategy.DO_NOT_PAD and len(__magic_name__  ) < max_length

      if return_attention_mask and "attention_mask" not in processed_features:
           _a      =							np.ones(len(__magic_name__  ) ,			dtype=np.intaa  )

      if needs_to_be_padded:
           _a      =							max_length - len(__magic_name__  )
           if self.padding_side == "right":
                if return_attention_mask:
                     _a      =							np.pad(
                         processed_features['attention_mask'] ,			(0, difference)  )
                _a      =							((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
                _a      =							np.pad(
                    __magic_name__ ,			__magic_name__ ,			'constant' ,			constant_values=self.padding_value  )
           elif self.padding_side == "left":
                if return_attention_mask:
                     _a      =							np.pad(
                         processed_features['attention_mask'] ,			(difference, 0)  )
                _a      =							((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
                _a      =							np.pad(
                    __magic_name__ ,			__magic_name__ ,			'constant' ,			constant_values=self.padding_value  )
           else:
                raise ValueError('Invalid padding strategy:' + str(self.padding_side  )  )

      return processed_features
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ = None ,			__magic_name__ = None ,			__magic_name__ = None ,			)   ->							List[str]:
      if not truncation:
           return processed_features
      elif truncation and max_length is None:
           raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.'  )

      _a      =							processed_features[self.model_input_names[0]]

      # find `max_length` that fits `pad_to_multiple_of`
      if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
           _a      =							((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

      _a      =							len(__magic_name__  ) > max_length

      if needs_to_be_truncated:
           _a      =							processed_features[self.model_input_names[0]][:max_length]
           if "attention_mask" in processed_features:
                _a      =							processed_features['attention_mask'][:max_length]

      return processed_features




 def 							__UpperCAmelCase						(	self ,			__magic_name__=False ,			__magic_name__=None  )   ->							Dict:

      # Get padding strategy
      if padding is not False:
           if padding is True:
                _a      =							PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
           elif not isinstance(__magic_name__ ,			__magic_name__  ):
                _a      =							PaddingStrategy(__magic_name__  )
           elif isinstance(__magic_name__ ,			__magic_name__  ):
                _a      =							padding
      else:
           _a      =							PaddingStrategy.DO_NOT_PAD

      # Set max length if needed
      if max_length is None:
           if padding_strategy == PaddingStrategy.MAX_LENGTH:
                raise ValueError(
                    f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined'  )

        # Test if we have a padding value
      if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
           raise ValueError(
               'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use'
               ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.'  )

      return padding_strategy

