'''simple docstring'''




import json
from typing import Dict, List, Optional, Tuple, Union

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer


_A								=   logging.get_logger(__name__)


_A								=   {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

_A								=   {
    'vocab_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json',
    },
    'merges_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json',
    },
}

_A								=   {
    'allenai/led-base-16384': 1_6_3_8_4,
}


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   A							:       Optional[Any]     =    VOCAB_FILES_NAMES
   A							:       Optional[int]     =    PRETRAINED_VOCAB_FILES_MAP
   A							:       Union[str, Any]     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A							:       int     =    LEDTokenizer
   A							:       Optional[int]     =    ['''input_ids''', '''attention_mask''']
   def __init__(self       ,				_a=None       ,				_a=None       ,				_a=None       ,				_a="replace"       ,				_a="<s>"       ,				_a="</s>"       ,				_a="</s>"       ,				_a="<s>"       ,				_a="<unk>"       ,				_a="<pad>"       ,				_a="<mask>"       ,				_a=False       ,				_a=True       ,				**_a       ,				)    ->     int:
        super().__init__(
            _a       ,				_a       ,				tokenizer_file=_a       ,				errors=_a       ,				bos_token=_a       ,				eos_token=_a       ,				sep_token=_a       ,				cls_token=_a       ,				unk_token=_a       ,				pad_token=_a       ,				mask_token=_a       ,				add_prefix_space=_a       ,				trim_offsets=_a       ,				**_a       ,				)

        lowercase_					:       Tuple     				=					json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()				)
        if pre_tok_state.get('add_prefix_space'       ,				_a				) != add_prefix_space:
             lowercase_					:       int     				=					getattr(_a       ,				pre_tok_state.pop('type'				)				)
             lowercase_					:       Any     				=					add_prefix_space
             lowercase_					:       List[Any]     				=					pre_tok_class(**_a				)

        lowercase_					:       Optional[int]     				=					add_prefix_space

        # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
        lowercase_					:       str     				=					'post_processor'
        lowercase_					:       List[str]     				=					getattr(self.backend_tokenizer       ,				_a       ,				_a				)
        if tokenizer_component_instance:
             lowercase_					:       Union[str, Any]     				=					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:
                  lowercase_					:       Any     				=					tuple(state['sep']				)
             if "cls" in state:
                  lowercase_					:       Tuple     				=					tuple(state['cls']				)

             lowercase_					:       Any     				=					False

             if state.get('add_prefix_space'       ,				_a				) != add_prefix_space:
                  lowercase_					:       int     				=					add_prefix_space
                  lowercase_					:       Dict     				=					True

             if state.get('trim_offsets'       ,				_a				) != trim_offsets:
                  lowercase_					:       List[Any]     				=					trim_offsets
                  lowercase_					:       Dict     				=					True

             if changes_to_apply:
                  lowercase_					:       Union[str, Any]     				=					getattr(_a       ,				state.pop('type'				)				)
                  lowercase_					:       int     				=					component_class(**_a				)
                  setattr(self.backend_tokenizer       ,				_a       ,				_a				)
   @property
   # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
   def 		_lowerCamelCase (self				)    ->     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 		_lowerCamelCase (self       ,				_a				)    ->     Dict:
        lowercase_					:       Optional[Any]     				=					AddedToken(_a       ,				lstrip=_a       ,				rstrip=_a				) if isinstance(_a       ,				_a				) else value
        lowercase_					:       int     				=					value
   def 		_lowerCamelCase (self       ,				*_a       ,				**_a				)    ->     BatchEncoding:
        lowercase_					:       Any     				=					kwargs.get('is_split_into_words'       ,				_a				)

        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(*_a       ,				**_a				)
   def 		_lowerCamelCase (self       ,				*_a       ,				**_a				)    ->     BatchEncoding:
        lowercase_					:       List[str]     				=					kwargs.get('is_split_into_words'       ,				_a				)

        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(*_a       ,				**_a				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     Tuple[str]:
        lowercase_					:       Any     				=					self._tokenizer.model.save(_a       ,				name=_a				)
        return tuple(_a				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Tuple:
        lowercase_					:       Tuple     				=					[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 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     List[int]:
        lowercase_					:       str     				=					[self.sep_token_id]
        lowercase_					:       Optional[int]     				=					[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]





   def 		_lowerCamelCase (self       ,				_a       ,				_a = None       ,				_a = PaddingStrategy.DO_NOT_PAD       ,				_a = None       ,				_a = None       ,				)    ->     dict:
        lowercase_					:       Tuple     				=					super()._pad(
            encoded_inputs=_a       ,				max_length=_a       ,				padding_strategy=_a       ,				pad_to_multiple_of=_a       ,				return_attention_mask=_a       ,				)

        # Load from model defaults
        if return_attention_mask is None:
             lowercase_					:       Optional[int]     				=					'attention_mask' in self.model_input_names

        if return_attention_mask and "global_attention_mask" in encoded_inputs:
             lowercase_					:       List[Any]     				=					encoded_inputs[self.model_input_names[0]]
             # `global_attention_mask` need to have the same length as other (sequential) inputs.
             lowercase_					:       Any     				=					len(encoded_inputs['global_attention_mask']				) != len(_a				)

             if needs_to_be_padded:
                  lowercase_					:       Union[str, Any]     				=					len(_a				) - len(encoded_inputs['global_attention_mask']				)

                  if self.padding_side == "right":
                       # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
                       lowercase_					:       int     				=					(
                           encoded_inputs['global_attention_mask'] + [-1] * difference
                       )
                  elif self.padding_side == "left":
                       lowercase_					:       str     				=					[-1] * difference + encoded_inputs[
                           'global_attention_mask'
                       ]
                  else:
                       raise ValueError('Invalid padding strategy:' + str(self.padding_side				)				)

        return encoded_inputs





'''simple docstring'''




import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


_A								=   logging.get_logger(__name__)

_A								=   '▁'

_A								=   {'vocab_file': 'vocab.txt', 'sentencepiece_model_ckpt': 'sentencepiece.bpe.model'}

_A								=   {
    'sentencepiece_model_file': 'sentencepiece.bpe.model',
    'vocab_file': 'vocab.txt',
}

_A								=   {
    'vocab_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
    },
    'sentencepiece_model_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
    },
}

_A								=   {
    'ernie-m-base': 5_1_4,
    'ernie-m-large': 5_1_4,
}

_A								=   {
    'ernie-m-base': {'do_lower_case': False},
    'ernie-m-large': {'do_lower_case': False},
}


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   A							:       List[str]     =    ["input_ids"]

   A							:       Optional[Any]     =    VOCAB_FILES_NAMES
   A							:       Dict     =    PRETRAINED_INIT_CONFIGURATION
   A							:       int     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A							:       List[str]     =    PRETRAINED_VOCAB_FILES_MAP
   A							:       Any     =    RESOURCE_FILES_NAMES
   def __init__(self       ,				_a       ,				_a=None       ,				_a=False       ,				_a="utf8"       ,				_a="[UNK]"       ,				_a="[SEP]"       ,				_a="[PAD]"       ,				_a="[CLS]"       ,				_a="[MASK]"       ,				_a = None       ,				**_a       ,				)    ->     None:
        # Mask token behave like a normal word, i.e. include the space before it and
        # is included in the raw text, there should be a match in a non-normalized sentence.

        lowercase_					:       Optional[Any]     				=					{} if sp_model_kwargs is None else sp_model_kwargs
        super().__init__(
            do_lower_case=_a       ,				unk_token=_a       ,				sep_token=_a       ,				pad_token=_a       ,				cls_token=_a       ,				mask_token=_a       ,				vocab_file=_a       ,				encoding=_a       ,				sp_model_kwargs=self.sp_model_kwargs       ,				**_a       ,				)
        lowercase_					:       int     				=					do_lower_case
        lowercase_					:       str     				=					sentencepiece_model_ckpt
        lowercase_					:       Tuple     				=					spm.SentencePieceProcessor(**self.sp_model_kwargs				)
        self.sp_model.Load(_a				)

        # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
        if vocab_file is not None:
             lowercase_					:       Union[str, Any]     				=					self.load_vocab(filepath=_a				)
        else:
             lowercase_					:       Any     				=					{self.sp_model.id_to_piece(_a				): id for id in range(self.sp_model.get_piece_size()				)}
        lowercase_					:       Optional[int]     				=					{v: k for k, v in self.vocab.items()}
   def 		_lowerCamelCase (self       ,				_a				)    ->     Any:
        if text is None:
             return None

        lowercase_					:       Dict     				=					self.tokenize(_a				)
        lowercase_				,lowercase_					:       Dict     				=					'', []

        for i, ch in enumerate(_a				):
             if ch in self.SP_CHAR_MAPPING:
                  lowercase_					:       str     				=					self.SP_CHAR_MAPPING.get(_a				)
             else:
                  lowercase_					:       List[str]     				=					unicodedata.normalize('NFKC'       ,				_a				)
             if self.is_whitespace(_a				):
                  continue
             normalized_text += ch
             char_mapping.extend([i] * len(_a				)				)

        lowercase_				,lowercase_				,lowercase_					:       int     				=					normalized_text, [], 0

        if self.do_lower_case:
             lowercase_					:       Optional[Any]     				=					text.lower()

        for token in split_tokens:
             if token[:1] == "▁":
                  lowercase_					:       Tuple     				=					token[1:]
             lowercase_					:       List[str]     				=					text[offset:].index(_a				) + offset
             lowercase_					:       Any     				=					start + len(_a				)

             token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)				)
             lowercase_					:       Tuple     				=					end
        return token_mapping
   @property
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        return len(self.vocab				)
   def 		_lowerCamelCase (self				)    ->     int:
        return dict(self.vocab       ,				**self.added_tokens_encoder				)
   def __getstate__(self				)    ->     Optional[Any]:
        lowercase_					:       Dict     				=					self.__dict__.copy()
        lowercase_					:       List[str]     				=					None
        return state
   def __setstate__(self       ,				_a				)    ->     Any:
        lowercase_					:       Optional[int]     				=					d

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

        lowercase_					:       Optional[int]     				=					spm.SentencePieceProcessor(**self.sp_model_kwargs				)
        self.sp_model.Load(self.sentencepiece_model_ckpt				)
   def 		_lowerCamelCase (self       ,				_a				)    ->     str:
        return "".join((self.SP_CHAR_MAPPING.get(_a       ,				_a				) for c in text)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=False       ,				_a=64       ,				_a=0.1				)    ->     Optional[int]:

        if self.sp_model_kwargs.get('enable_sampling'				) is True:
             lowercase_					:       Optional[int]     				=					True
        if self.sp_model_kwargs.get('alpha'				) is not None:
             lowercase_					:       Union[str, Any]     				=					self.sp_model_kwargs.get('alpha'				)
        if self.sp_model_kwargs.get('nbest_size'				) is not None:
             lowercase_					:       Optional[int]     				=					self.sp_model_kwargs.get('nbest_size'				)

        if not enable_sampling:
             lowercase_					:       Optional[Any]     				=					self.sp_model.EncodeAsPieces(_a				)
        else:
             lowercase_					:       List[Any]     				=					self.sp_model.SampleEncodeAsPieces(_a       ,				_a       ,				_a				)
        lowercase_					:       int     				=					[]
        for pi, piece in enumerate(_a				):
             if piece == SPIECE_UNDERLINE:
                  if not pieces[pi + 1].startswith(_a				) and pi != 0:
                       new_pieces.append(_a				)
                       continue
                  else:
                       continue
             lowercase_					:       Optional[Any]     				=					0
             for i, chunk in enumerate(_a				):
                  if chunk == SPIECE_UNDERLINE:
                       continue
                  if self.is_ch_char(_a				) or self.is_punct(_a				):
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       new_pieces.append(_a				)
                       lowercase_					:       List[Any]     				=					i + 1
                  elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       lowercase_					:       Optional[Any]     				=					i
                  elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       lowercase_					:       int     				=					i
             if len(_a				) > lst_i:
                  new_pieces.append(piece[lst_i:]				)
        return new_pieces
   def 		_lowerCamelCase (self       ,				_a				)    ->     Union[str, Any]:
        lowercase_					:       Optional[Any]     				=					''.join(_a				).replace(_a       ,				' '				).strip()
        return out_string
   def 		_lowerCamelCase (self       ,				_a				)    ->     Optional[int]:
        lowercase_					:       Optional[Any]     				=					self.convert_ids_to_tokens(_a				)
        lowercase_					:       Tuple     				=					''.join(_a				).replace(_a       ,				' '				).strip()
        return out_string
   def 		_lowerCamelCase (self       ,				_a				)    ->     Optional[int]:
        return self.vocab.get(_a       ,				self.vocab.get(self.unk_token				)				)
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        return self.reverse_vocab.get(_a       ,				self.unk_token				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Any:
        if token_ids_a is None:
             return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        lowercase_					:       Tuple     				=					[self.cls_token_id]
        lowercase_					:       int     				=					[self.sep_token_id]
        return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Optional[Any]:
        if offset_mapping_a is None:
             return [(0, 0)] + offset_mapping_a + [(0, 0)]

        return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None       ,				_a=False				)    ->     Union[str, Any]:

        if already_has_special_tokens:
             if token_ids_a is not None:
                  raise ValueError(
                      'You should not supply a second sequence if the provided sequence of '
                      'ids is already formatted with special tokens for the model.'				)
             return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

        if token_ids_a is not None:
             return [1] + ([0] * len(_a				)) + [1, 1] + ([0] * len(_a				)) + [1]
        return [1] + ([0] * len(_a				)) + [1]
   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     List[int]:
        # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
        if token_ids_a is None:
             # [CLS] X [SEP]
             return (len(_a				) + 2) * [0]

        # [CLS] A [SEP] [SEP] B [SEP]
        return [0] * (len(_a				) + 1) + [1] * (len(_a				) + 3)
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        if "\u4e00" <= char <= "\u9fff":
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     List[str]:
        if ("a" <= char <= "z") or ("A" <= char <= "Z"):
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        if char in ",;:.?!~，；：。？！《》【】":
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     List[Any]:
        if char == " " or char == "\t" or char == "\n" or char == "\r":
             return True
        if len(_a				) == 1:
             lowercase_					:       Optional[Any]     				=					unicodedata.category(_a				)
             if cat == "Zs":
                  return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     Tuple:
        lowercase_					:       List[Any]     				=					{}
        with io.open(_a       ,				'r'       ,				encoding='utf-8'				) as f:
             for index, line in enumerate(_a				):
                  lowercase_					:       Dict     				=					line.rstrip('\n'				)
                  lowercase_					:       Dict     				=					int(_a				)

        return token_to_idx





   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     Tuple[str]:
        lowercase_					:       Tuple     				=					0
        if os.path.isdir(_a				):
             lowercase_					:       Any     				=					os.path.join(
                 _a       ,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']				)
        else:
             lowercase_					:       Tuple     				=					(filename_prefix + '-' if filename_prefix else '') + save_directory
        with open(_a       ,				'w'       ,				encoding='utf-8'				) as writer:
             for token, token_index in sorted(self.vocab.items()       ,				key=lambda _a				: kv[1]				):
                  if index != token_index:
                       logger.warning(
                           f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
                           ' Please check that the vocabulary is not corrupted!'				)
                       lowercase_					:       Tuple     				=					token_index
                  writer.write(token + '\n'				)
                  index += 1

        lowercase_					:       List[str]     				=					os.path.join(_a       ,				'sentencepiece.bpe.model'				)
        with open(_a       ,				'wb'				) as fi:
             lowercase_					:       Tuple     				=					self.sp_model.serialized_model_proto()
             fi.write(_a				)

        return (vocab_file,)




