




'''simple docstring'''







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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase_    	=							logging.get_logger(__name__)
lowerCAmelCase_    	=							{'''vocab_file''': '''spiece.model'''}

lowerCAmelCase_    	=							{
    '''vocab_file''': {
        '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/spiece.model''',
        '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/spiece.model''',
    },
}

lowerCAmelCase_    	=							{
    '''google/fnet-base''': 5_1_2,
    '''google/fnet-large''': 5_1_2,
}

lowerCAmelCase_    	=							'''▁'''

class   _snake_case( UpperCAmelCase			):
 __snake_case:       Tuple									=				VOCAB_FILES_NAMES
 __snake_case:       Optional[Any]									=				PRETRAINED_VOCAB_FILES_MAP
 __snake_case:       List[str]									=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __snake_case:       str									=				['''input_ids''', '''token_type_ids''']






 def __init__(self					:     Tuple						,		a					:     Optional[int]						,		a					:     Dict=False						,		a					:     Union[str, Any]=True						,		a					:     int=True						,		a					:     int="<unk>"						,		a					:     List[str]="[SEP]"						,		a					:     Union[str, Any]="<pad>"						,		a					:     Any="[CLS]"						,		a					:     Any="[MASK]"						,		a					:     Optional[Dict[str, Any]] = None						,		**a					:     List[str]						,		)					->      None:






    """simple docstring"""


    A__         =    (
        AddedToken(a						,		lstrip=a						,		rstrip=a						,		normalized=a						)
        if isinstance(a						,		a						)
        else mask_token
    )

    A__         =    {} if sp_model_kwargs is None else sp_model_kwargs

    super().__init__(
        do_lower_case=a						,		remove_space=a						,		keep_accents=a						,		unk_token=a						,		sep_token=a						,		pad_token=a						,		cls_token=a						,		mask_token=a						,		sp_model_kwargs=self.sp_model_kwargs						,		**a						,		)

    A__         =    do_lower_case
    A__         =    remove_space
    A__         =    keep_accents
    A__         =    vocab_file

    A__         =    spm.SentencePieceProcessor(**self.sp_model_kwargs						)
    self.sp_model.Load(a						)






 @property
 def 	_UpperCamelCase   (self					:     Dict						)					->      int:






    """simple docstring"""


    return len(self.sp_model						)






 def 	_UpperCamelCase   (self					:     Any						)					->      Optional[int]:






    """simple docstring"""


    A__         =    {self.convert_ids_to_tokens(a						): i for i in range(self.vocab_size						)}
    vocab.update(self.added_tokens_encoder						)
    return vocab






 def __getstate__(self					:     Any						)					->      Tuple:






    """simple docstring"""


    A__         =    self.__dict__.copy()
    A__         =    None
    return state






 def __setstate__(self					:     Tuple						,		a					:     int						)					->      Optional[int]:






    """simple docstring"""


    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					:     Dict						,		a					:     Optional[Any]						)					->      Optional[Any]:






    """simple docstring"""


    if self.remove_space:
       A__         =    " ".join(inputs.strip().split()						)
    else:
       A__         =    inputs
    A__         =    outputs.replace("``"						,		"\""						).replace("\'\'"						,		"\""						)

    if not self.keep_accents:
       A__         =    unicodedata.normalize("NFKD"						,		a						)
       A__         =    "".join([c for c in outputs if not unicodedata.combining(a						)]						)
    if self.do_lower_case:
       A__         =    outputs.lower()

    return outputs






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     str						)					->      List[str]:






    """simple docstring"""


    A__         =    self.preprocess_text(a						)
    A__         =    self.sp_model.encode(a						,		out_type=a						)
    A__         =    []
    for piece in pieces:
       if len(a						) > 1 and piece[-1] == str(","						) and piece[-2].isdigit():
          A__         =    self.sp_model.EncodeAsPieces(piece[:-1].replace(a						,		""						)						)
          if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
             if len(cur_pieces[0]						) == 1:
                A__         =    cur_pieces[1:]
             else:
                A__         =    cur_pieces[0][1:]
          cur_pieces.append(piece[-1]						)
          new_pieces.extend(a						)
       else:
          new_pieces.append(a						)

    return new_pieces






 def 	_UpperCamelCase   (self					:     List[str]						,		a					:     Union[str, Any]						)					->      Optional[int]:






    """simple docstring"""


    return self.sp_model.PieceToId(a						)






 def 	_UpperCamelCase   (self					:     List[str]						,		a					:     str						)					->      Optional[int]:






    """simple docstring"""


    return self.sp_model.IdToPiece(a						)






 def 	_UpperCamelCase   (self					:     Optional[Any]						,		a					:     List[str]						)					->      Any:






    """simple docstring"""


    A__         =    []
    A__         =    ""
    A__         =    False
    for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
          if not prev_is_special:
             out_string += " "
          out_string += self.sp_model.decode(a						) + token
          A__         =    True
          A__         =    []
       else:
          current_sub_tokens.append(a						)
          A__         =    False
    out_string += self.sp_model.decode(a						)
    return out_string.strip()






 def 	_UpperCamelCase   (self					:     Optional[int]						,		a					:     List[int]						,		a					:     bool = False						,		a					:     bool = None						,		a					:     bool = True						,		**a					:     List[Any]						,		)					->      str:






    """simple docstring"""


    A__         =    kwargs.pop("use_source_tokenizer"						,		a						)

    A__         =    self.convert_ids_to_tokens(a						,		skip_special_tokens=a						)

    # To avoid mixing byte-level and unicode for byte-level BPT
    # we need to build string separately for added tokens and byte-level tokens
    # cf. https://github.com/huggingface/transformers/issues/1133
    A__         =    []
    A__         =    []
    for token in filtered_tokens:
       if skip_special_tokens and token in self.all_special_ids:
          continue
       if token in self.added_tokens_encoder:
          if current_sub_text:
             sub_texts.append(self.convert_tokens_to_string(a						)						)
             A__         =    []
          sub_texts.append(a						)
       else:
          current_sub_text.append(a						)
    if current_sub_text:
       sub_texts.append(self.convert_tokens_to_string(a						)						)

    # Mimic the behavior of the Rust tokenizer:
    # No space after <unk>
    if spaces_between_special_tokens:
       A__         =    re.sub(R"(<unk>) "						,		R"\1"						,		" ".join(a						)						)
    else:
       A__         =    "".join(a						)

    A__         =    (
        clean_up_tokenization_spaces
        if clean_up_tokenization_spaces is not None
        else self.clean_up_tokenization_spaces
    )
    if clean_up_tokenization_spaces:
       A__         =    self.clean_up_tokenization(a						)
       return clean_text
    else:
       return text






 def 	_UpperCamelCase   (self					:     int						,		a					:     List[int]						,		a					:     Optional[List[int]] = None						)					->      List[int]:






    """simple docstring"""


    A__         =    [self.sep_token_id]
    A__         =    [self.cls_token_id]
    if token_ids_a is None:
       return cls + token_ids_a + sep
    return cls + token_ids_a + sep + token_ids_a + sep






 def 	_UpperCamelCase   (self					:     Tuple						,		a					:     List[int]						,		a					:     Optional[List[int]] = None						,		a					:     bool = False						)					->      List[int]:






    """simple docstring"""


    if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=a						,		token_ids_a=a						,		already_has_special_tokens=a						)

    if token_ids_a is not None:
       return [1] + ([0] * len(a						)) + [1] + ([0] * len(a						)) + [1]
    return [1] + ([0] * len(a						)) + [1]






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     List[int]						,		a					:     Optional[List[int]] = None						)					->      List[int]:






    """simple docstring"""


    A__         =    [self.sep_token_id]
    A__         =    [self.cls_token_id]

    if token_ids_a is None:
       return len(cls + token_ids_a + sep						) * [0]
    return len(cls + token_ids_a + sep						) * [0] + len(token_ids_a + sep						) * [1]






 def 	_UpperCamelCase   (self					:     List[str]						,		a					:     str						,		a					:     Optional[str] = None						)					->      Tuple[str]:






    """simple docstring"""


    if not os.path.isdir(a						):
       logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""						)
       return
    A__         =    os.path.join(
        a						,		(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)

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

    return (out_vocab_file,)








'''simple docstring'''







import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


lowerCAmelCase_    	=							logging.get_logger(__name__)

if is_tf_available():
    import tensorflow as tf

@dataclass
class   _snake_case( UpperCAmelCase			):
 __snake_case:       Optional[Any]									=				'''tf'''
 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Name of TPU'''}					,   )

 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Zone of TPU'''}					,   )

 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Name of Cloud TPU-enabled project'''}					,   )

 __snake_case:       float									=				field(
     default=1.0					,   metadata={'''help''': '''Power for the Polynomial decay LR scheduler.'''}					,   )

 __snake_case:       bool									=				field(default=UpperCAmelCase					,   metadata={'''help''': '''Whether to activate the XLA compilation or not'''}			)






 @cached_property
 def 	_UpperCamelCase   (self					:     Tuple						)					->      Tuple["tf.distribute.Strategy", int]:






    """simple docstring"""


    requires_backends(self						,		['tf']						)
    logger.info('Tensorflow: setting up strategy'						)

    A__         =    tf.config.list_physical_devices('GPU'						)

    # Set to float16 at first
    if self.fpaa:
       tf.keras.mixed_precision.set_global_policy('mixed_float16'						)

    if self.no_cuda:
       A__         =    tf.distribute.OneDeviceStrategy(device='/cpu:0'						)
    else:
       try:
          if self.tpu_name:
             A__         =    tf.distribute.cluster_resolver.TPUClusterResolver(
                 self.tpu_name						,		zone=self.tpu_zone						,		project=self.gcp_project						)
          else:
             A__         =    tf.distribute.cluster_resolver.TPUClusterResolver()
       except ValueError:
          if self.tpu_name:
             raise RuntimeError(f"""Couldn't connect to TPU {self.tpu_name}!"""						)
          else:
             A__         =    None

       if tpu:
          # Set to bfloat16 in case of TPU
          if self.fpaa:
             tf.keras.mixed_precision.set_global_policy('mixed_bfloat16'						)

          tf.config.experimental_connect_to_cluster(a						)
          tf.tpu.experimental.initialize_tpu_system(a						)

          A__         =    tf.distribute.TPUStrategy(a						)

       elif len(a						) == 0:
          A__         =    tf.distribute.OneDeviceStrategy(device='/cpu:0'						)
       elif len(a						) == 1:
          A__         =    tf.distribute.OneDeviceStrategy(device='/gpu:0'						)
       elif len(a						) > 1:
          # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
          A__         =    tf.distribute.MirroredStrategy()
       else:
          raise ValueError('Cannot find the proper strategy, please check your environment properties.'						)

    return strategy






 @property
 def 	_UpperCamelCase   (self					:     List[Any]						)					->      "tf.distribute.Strategy":






    """simple docstring"""


    requires_backends(self						,		['tf']						)
    return self._setup_strategy






 @property
 def 	_UpperCamelCase   (self					:     Tuple						)					->      int:






    """simple docstring"""


    requires_backends(self						,		['tf']						)
    return self._setup_strategy.num_replicas_in_sync






 @property
 def 	_UpperCamelCase   (self					:     Optional[Any]						)					->      int:






    """simple docstring"""


    return False  # TF Logging is handled by Keras not the Trainer






 @property
 def 	_UpperCamelCase   (self					:     Union[str, Any]						)					->      int:






    """simple docstring"""


    if self.per_gpu_train_batch_size:
       logger.warning(
           'Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future '
           'version. Using `--per_device_train_batch_size` is preferred.'						)
    A__         =    self.per_gpu_train_batch_size or self.per_device_train_batch_size
    return per_device_batch_size * self.n_replicas






 @property
 def 	_UpperCamelCase   (self					:     Optional[int]						)					->      int:






    """simple docstring"""


    if self.per_gpu_eval_batch_size:
       logger.warning(
           'Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future '
           'version. Using `--per_device_eval_batch_size` is preferred.'						)
    A__         =    self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
    return per_device_batch_size * self.n_replicas






 @property
 def 	_UpperCamelCase   (self					:     Optional[Any]						)					->      int:






    """simple docstring"""


    requires_backends(self						,		['tf']						)
    warnings.warn(
        'The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.'						,		a						,		)
    return self._setup_strategy.num_replicas_in_sync


