


import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


UpperCAmelCase_      : int  					=       logging.get_logger(__name__)


UpperCAmelCase_      : Union[str, Any]  					=       {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

# See all BART models at https://huggingface.co/models?filter=bart
UpperCAmelCase_      : Any  					=       {
    'vocab_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json',
    },
    'merges_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json',
    },
}

UpperCAmelCase_      : int  					=       {
    'facebook/bart-base': 1024,
    'facebook/bart-large': 1024,
    'facebook/bart-large-mnli': 1024,
    'facebook/bart-large-cnn': 1024,
    'facebook/bart-large-xsum': 1024,
    'yjernite/bart_eli5': 1024,
}
class  SCREAMING_SNAKE_CASE__  (				lowercase__			):
      snake_case__				:     Dict        =						VOCAB_FILES_NAMES
      snake_case__				:     Union[str, Any]        =						PRETRAINED_VOCAB_FILES_MAP
      snake_case__				:     Any        =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      snake_case__				:     Any        =						['''input_ids''', '''attention_mask''']
      snake_case__				:     List[Any]        =						BartTokenizer
      def __init__(       self				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       List[str]=None     ,							SCREAMING_SNAKE_CASE__				:       Dict=None     ,							SCREAMING_SNAKE_CASE__				:       Dict=None     ,							SCREAMING_SNAKE_CASE__				:       Dict="replace"     ,							SCREAMING_SNAKE_CASE__				:       List[Any]="<s>"     ,							SCREAMING_SNAKE_CASE__				:       str="</s>"     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]="</s>"     ,							SCREAMING_SNAKE_CASE__				:       str="<s>"     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]="<unk>"     ,							SCREAMING_SNAKE_CASE__				:       Dict="<pad>"     ,							SCREAMING_SNAKE_CASE__				:       int="<mask>"     ,							SCREAMING_SNAKE_CASE__				:       List[Any]=False     ,							SCREAMING_SNAKE_CASE__				:       Dict=True     ,							**SCREAMING_SNAKE_CASE__				:       int     ,							)		->			List[Any]:
             super().__init__(
                 SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							tokenizer_file=SCREAMING_SNAKE_CASE__     ,							errors=SCREAMING_SNAKE_CASE__     ,							bos_token=SCREAMING_SNAKE_CASE__     ,							eos_token=SCREAMING_SNAKE_CASE__     ,							sep_token=SCREAMING_SNAKE_CASE__     ,							cls_token=SCREAMING_SNAKE_CASE__     ,							unk_token=SCREAMING_SNAKE_CASE__     ,							pad_token=SCREAMING_SNAKE_CASE__     ,							mask_token=SCREAMING_SNAKE_CASE__     ,							add_prefix_space=SCREAMING_SNAKE_CASE__     ,							trim_offsets=SCREAMING_SNAKE_CASE__     ,							**SCREAMING_SNAKE_CASE__     ,							)

             a_					:		Dict							=  json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()     )
             if pre_tok_state.get('add_prefix_space'     ,							SCREAMING_SNAKE_CASE__     ) != add_prefix_space:
                    a_					:		Any							=  getattr(SCREAMING_SNAKE_CASE__     ,							pre_tok_state.pop('type'     )     )
                    a_					:		Any							=  add_prefix_space
                    a_					:		Optional[int]							=  pre_tok_class(**SCREAMING_SNAKE_CASE__     )

             a_					:		List[str]							=  add_prefix_space

             # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
             a_					:		int							=  'post_processor'
             a_					:		str							=  getattr(self.backend_tokenizer     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             if tokenizer_component_instance:
                    a_					:		Dict							=  json.loads(tokenizer_component_instance.__getstate__()     )

                    # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
                    if "sep" in state:
                           a_					:		List[str]							=  tuple(state['sep']     )
                    if "cls" in state:
                           a_					:		Dict							=  tuple(state['cls']     )

                    a_					:		List[str]							=  False

                    if state.get('add_prefix_space'     ,							SCREAMING_SNAKE_CASE__     ) != add_prefix_space:
                           a_					:		List[str]							=  add_prefix_space
                           a_					:		str							=  True

                    if state.get('trim_offsets'     ,							SCREAMING_SNAKE_CASE__     ) != trim_offsets:
                           a_					:		Union[str, Any]							=  trim_offsets
                           a_					:		Dict							=  True

                    if changes_to_apply:
                           a_					:		Any							=  getattr(SCREAMING_SNAKE_CASE__     ,							state.pop('type'     )     )
                           a_					:		Tuple							=  component_class(**SCREAMING_SNAKE_CASE__     )
                           setattr(self.backend_tokenizer     ,							SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			str:
             if self._mask_token is None:
                    if self.verbose:
                           logger.error('Using mask_token, but it is not set yet.'     )
                    return None
             return str(self._mask_token     )
      @mask_token.setter
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     )		->			Tuple:
             a_					:		Tuple							=  AddedToken(SCREAMING_SNAKE_CASE__     ,							lstrip=SCREAMING_SNAKE_CASE__     ,							rstrip=SCREAMING_SNAKE_CASE__     ) if isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ) else value
             a_					:		List[Any]							=  value
      def        SCREAMING_SNAKE_CASE							(       self				:       int     ,							*SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							**SCREAMING_SNAKE_CASE__				:       int     )		->			BatchEncoding:
             a_					:		Dict							=  kwargs.get('is_split_into_words'     ,							SCREAMING_SNAKE_CASE__     )

             if is_split_into_words and not self.add_prefix_space:
                    raise ValueError(
                        F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
                        'to use it with pretokenized inputs.'     )

             return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE__     ,							**SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Dict     ,							*SCREAMING_SNAKE_CASE__				:       Dict     ,							**SCREAMING_SNAKE_CASE__				:       Optional[int]     )		->			BatchEncoding:
             a_					:		Union[str, Any]							=  kwargs.get('is_split_into_words'     ,							SCREAMING_SNAKE_CASE__     )

             if is_split_into_words and not self.add_prefix_space:
                    raise ValueError(
                        F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
                        'to use it with pretokenized inputs.'     )

             return super()._encode_plus(*SCREAMING_SNAKE_CASE__     ,							**SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     ,							SCREAMING_SNAKE_CASE__				:       str     ,							SCREAMING_SNAKE_CASE__				:       Optional[str] = None     )		->			Tuple[str]:
             a_					:		List[Any]							=  self._tokenizer.model.save(SCREAMING_SNAKE_CASE__     ,							name=SCREAMING_SNAKE_CASE__     )
             return tuple(SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]=None     )		->			Union[str, Any]:
             a_					:		Dict							=  [self.bos_token_id] + token_ids_a + [self.eos_token_id]
             if token_ids_a is None:
                    return output

             return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]

      def        SCREAMING_SNAKE_CASE							(       self				:       int     ,							SCREAMING_SNAKE_CASE__				:       List[int]     ,							SCREAMING_SNAKE_CASE__				:       Optional[List[int]] = None     )		->			List[int]:
             a_					:		Optional[int]							=  [self.sep_token_id]
             a_					:		Union[str, Any]							=  [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 + sep + token_ids_a + sep     ) * [0]








import os
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 SPIECE_UNDERLINE, logging


SCREAMING_SNAKE_CASE__       :      Optional[Any]  =   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__       :      Tuple  =   {'vocab_file': 'spiece.model'}

SCREAMING_SNAKE_CASE__       :      int  =   {
    'vocab_file': {
        'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model',
        'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model',
    }
}

SCREAMING_SNAKE_CASE__       :      str  =   {
    'xlnet-base-cased': None,
    'xlnet-large-cased': None,
}

# Segments (not really needed)
SCREAMING_SNAKE_CASE__       :      Dict  =   0
SCREAMING_SNAKE_CASE__       :      Tuple  =   1
SCREAMING_SNAKE_CASE__       :      Optional[int]  =   2
SCREAMING_SNAKE_CASE__       :      List[str]  =   3
SCREAMING_SNAKE_CASE__       :      Optional[int]  =   4




class 		UpperCamelCase__	(lowerCAmelCase__     ):

    '''simple docstring'''



    lowerCamelCase_      :	Dict	     =      VOCAB_FILES_NAMES
    lowerCamelCase_      :	Optional[Any]	     =      PRETRAINED_VOCAB_FILES_MAP
    lowerCamelCase_      :	Optional[int]	     =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowerCamelCase_      :	List[str]	     =      """left"""







    def __init__(    self     ,  UpperCamelCase__     ,  UpperCamelCase__=False     ,  UpperCamelCase__=True     ,  UpperCamelCase__=False     ,  UpperCamelCase__="<s>"     ,  UpperCamelCase__="</s>"     ,  UpperCamelCase__="<unk>"     ,  UpperCamelCase__="<sep>"     ,  UpperCamelCase__="<pad>"     ,  UpperCamelCase__="<cls>"     ,  UpperCamelCase__="<mask>"     ,  UpperCamelCase__=["<eop>", "<eod>"]     ,  UpperCamelCase__ = None     ,  **UpperCamelCase__     ,  )     ->      None:
           # Mask token behave like a normal word, i.e. include the space before it
           lowerCamelCase   :      str			 =					AddedToken(UpperCamelCase__     ,  lstrip=UpperCamelCase__     ,  rstrip=UpperCamelCase__     ) if isinstance(UpperCamelCase__     ,  UpperCamelCase__     ) else mask_token

           lowerCamelCase   :      Dict			 =					{} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               do_lower_case=UpperCamelCase__     ,  remove_space=UpperCamelCase__     ,  keep_accents=UpperCamelCase__     ,  bos_token=UpperCamelCase__     ,  eos_token=UpperCamelCase__     ,  unk_token=UpperCamelCase__     ,  sep_token=UpperCamelCase__     ,  pad_token=UpperCamelCase__     ,  cls_token=UpperCamelCase__     ,  mask_token=UpperCamelCase__     ,  additional_special_tokens=UpperCamelCase__     ,  sp_model_kwargs=self.sp_model_kwargs     ,  **UpperCamelCase__     ,  )

           lowerCamelCase   :      Any			 =					3

           lowerCamelCase   :      Optional[Any]			 =					do_lower_case
           lowerCamelCase   :      List[Any]			 =					remove_space
           lowerCamelCase   :      str			 =					keep_accents
           lowerCamelCase   :      List[Any]			 =					vocab_file

           lowerCamelCase   :      int			 =					spm.SentencePieceProcessor(**self.sp_model_kwargs     )
           self.sp_model.Load(UpperCamelCase__     )







    @property
    def     _lowercase     (    self     )     ->      Optional[Any]:
           return len(self.sp_model     )







    def     _lowercase     (    self     )     ->      Optional[int]:
           lowerCamelCase   :      int			 =					{self.convert_ids_to_tokens(UpperCamelCase__     ): i for i in range(self.vocab_size     )}
           vocab.update(self.added_tokens_encoder     )
           return vocab







    def __getstate__(    self     )     ->      Optional[Any]:
           lowerCamelCase   :      Optional[int]			 =					self.__dict__.copy()
           lowerCamelCase   :      Union[str, Any]			 =					None
           return state







    def __setstate__(    self     ,  UpperCamelCase__     )     ->      int:
           lowerCamelCase   :      int			 =					d

           # for backward compatibility
           if not hasattr(self     ,  "sp_model_kwargs"     ):
                  lowerCamelCase   :      Any			 =					{}

           lowerCamelCase   :      Optional[int]			 =					spm.SentencePieceProcessor(**self.sp_model_kwargs     )
           self.sp_model.Load(self.vocab_file     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Any:
           if self.remove_space:
                  lowerCamelCase   :      Dict			 =					" ".join(inputs.strip().split()     )
           else:
                  lowerCamelCase   :      Union[str, Any]			 =					inputs
           lowerCamelCase   :      Optional[Any]			 =					outputs.replace("``"     ,  "\""     ).replace("''"     ,  "\""     )

           if not self.keep_accents:
                  lowerCamelCase   :      Optional[int]			 =					unicodedata.normalize("NFKD"     ,  UpperCamelCase__     )
                  lowerCamelCase   :      List[Any]			 =					"".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__     )]     )
           if self.do_lower_case:
                  lowerCamelCase   :      List[str]			 =					outputs.lower()

           return outputs







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      List[str]:
           lowerCamelCase   :      Optional[Any]			 =					self.preprocess_text(UpperCamelCase__     )
           lowerCamelCase   :      Dict			 =					self.sp_model.encode(UpperCamelCase__     ,  out_type=UpperCamelCase__     )
           lowerCamelCase   :      Dict			 =					[]
           for piece in pieces:
                  if len(UpperCamelCase__     ) > 1 and piece[-1] == str(","     ) and piece[-2].isdigit():
                         lowerCamelCase   :      List[Any]			 =					self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__     ,  ""     )     )
                         if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                                if len(cur_pieces[0]     ) == 1:
                                       lowerCamelCase   :      Union[str, Any]			 =					cur_pieces[1:]
                                else:
                                       lowerCamelCase   :      Optional[int]			 =					cur_pieces[0][1:]
                         cur_pieces.append(piece[-1]     )
                         new_pieces.extend(UpperCamelCase__     )
                  else:
                         new_pieces.append(UpperCamelCase__     )

           return new_pieces







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      int:
           return self.sp_model.PieceToId(UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      Tuple:
           return self.sp_model.IdToPiece(UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      List[str]:
           lowerCamelCase   :      Union[str, Any]			 =					"".join(UpperCamelCase__     ).replace(UpperCamelCase__     ,  " "     ).strip()
           return out_string







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = False     ,  UpperCamelCase__ = None     ,  UpperCamelCase__ = True     ,  **UpperCamelCase__     ,  )     ->      str:
           lowerCamelCase   :      Optional[int]			 =					kwargs.pop("use_source_tokenizer"     ,  UpperCamelCase__     )

           lowerCamelCase   :      Optional[int]			 =					self.convert_ids_to_tokens(UpperCamelCase__     ,  skip_special_tokens=UpperCamelCase__     )

           # 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
           lowerCamelCase   :      Any			 =					[]
           lowerCamelCase   :      Any			 =					[]
           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(UpperCamelCase__     )     )
                                lowerCamelCase   :      int			 =					[]
                         sub_texts.append(UpperCamelCase__     )
                  else:
                         current_sub_text.append(UpperCamelCase__     )
           if current_sub_text:
                  sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__     )     )

           # Mimic the behavior of the Rust tokenizer:
           # By default, there are no spaces between special tokens
           lowerCamelCase   :      Union[str, Any]			 =					"".join(UpperCamelCase__     )

           lowerCamelCase   :      Tuple			 =					(
               clean_up_tokenization_spaces
               if clean_up_tokenization_spaces is not None
               else self.clean_up_tokenization_spaces
           )
           if clean_up_tokenization_spaces:
                  lowerCamelCase   :      int			 =					self.clean_up_tokenization(UpperCamelCase__     )
                  return clean_text
           else:
                  return text







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      List[int]:
           lowerCamelCase   :      str			 =					[self.sep_token_id]
           lowerCamelCase   :      Optional[int]			 =					[self.cls_token_id]
           if token_ids_a is None:
                  return token_ids_a + sep + cls
           return token_ids_a + sep + token_ids_a + sep + cls







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     ,  UpperCamelCase__ = False     )     ->      List[int]:

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

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







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      List[int]:
           lowerCamelCase   :      Any			 =					[self.sep_token_id]
           lowerCamelCase   :      List[str]			 =					[2]

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







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__ = None     )     ->      Tuple[str]:
           if not os.path.isdir(UpperCamelCase__     ):
                  logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
                  return
           lowerCamelCase   :      Union[str, Any]			 =					os.path.join(
               UpperCamelCase__     ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]     )

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

           return (out_vocab_file,)






