


import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

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


_lowerCamelCase     :		Tuple								=       logging.get_logger(__name__)


_lowerCamelCase     :		str								=       {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""}

_lowerCamelCase     :		Union[str, Any]								=       {
    """vocab_file""": {
        """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json""",
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json"""
        ),
    },
    """merges_file""": {
        """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt""",
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt"""
        ),
    },
}

_lowerCamelCase     :		int								=       {
    """allenai/longformer-base-4096""": 4096,
    """allenai/longformer-large-4096""": 4096,
    """allenai/longformer-large-4096-finetuned-triviaqa""": 4096,
    """allenai/longformer-base-4096-extra.pos.embd.only""": 4096,
    """allenai/longformer-large-4096-extra.pos.embd.only""": 4096,
}







@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def SCREAMING_SNAKE_CASE    (	)       ->	Any:



       """simple docstring"""

       A__							=   (
           list(range(ord('''!'''						)			,    ord('''~'''						) + 1						)						) + list(range(ord('''¡'''						)			,    ord('''¬'''						) + 1						)						) + list(range(ord('''®'''						)			,    ord('''ÿ'''						) + 1						)						)
       )
       A__							=   bs[:]
       A__							=   0
       for b in range(2**8						):
              if b not in bs:
                     bs.append(__a						)
                     cs.append(2**8 + n						)
                     n += 1
       A__							=   [chr(__a						) for n in cs]
       return dict(zip(__a			,    __a						)						)







def SCREAMING_SNAKE_CASE    (	lowercase_						)       ->	Dict:



       """simple docstring"""

       A__							=   set()
       A__							=   word[0]
       for char in word[1:]:
              pairs.add((prev_char, char)						)
              A__							=   char
       return pairs


class     UpperCamelCase_   (			__lowercase					):

    '''simple docstring'''






    UpperCAmelCase__							  =				VOCAB_FILES_NAMES
    UpperCAmelCase__							  =				PRETRAINED_VOCAB_FILES_MAP
    UpperCAmelCase__							  =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    UpperCAmelCase__							  =				['''input_ids''', '''attention_mask''']


    def __init__(      self				:     Dict ,			UpperCAmelCase__				:     List[Any] ,			UpperCAmelCase__				:     Tuple ,			UpperCAmelCase__				:     List[str]="replace" ,			UpperCAmelCase__				:     Union[str, Any]="<s>" ,			UpperCAmelCase__				:     Union[str, Any]="</s>" ,			UpperCAmelCase__				:     Optional[Any]="</s>" ,			UpperCAmelCase__				:     Optional[Any]="<s>" ,			UpperCAmelCase__				:     Union[str, Any]="<unk>" ,			UpperCAmelCase__				:     str="<pad>" ,			UpperCAmelCase__				:     Any="<mask>" ,			UpperCAmelCase__				:     Optional[Any]=False ,			**UpperCAmelCase__				:     List[str] ,			)						->Tuple:





           '''simple docstring'''

           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else bos_token
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else eos_token
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else sep_token
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else cls_token
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else unk_token
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else pad_token

           # Mask token behave like a normal word, i.e. include the space before it
           A__							=   AddedToken(_a ,			lstrip=_a ,			rstrip=_a) if isinstance(_a ,			_a) else mask_token

           super().__init__(
               errors=_a ,			bos_token=_a ,			eos_token=_a ,			unk_token=_a ,			sep_token=_a ,			cls_token=_a ,			pad_token=_a ,			mask_token=_a ,			add_prefix_space=_a ,			**_a ,			)

           with open(_a ,			encoding='''utf-8''') as vocab_handle:
                  A__							=   json.load(_a)
           A__							=   {v: k for k, v in self.encoder.items()}
           A__							=   errors  # how to handle errors in decoding
           A__							=   bytes_to_unicode()
           A__							=   {v: k for k, v in self.byte_encoder.items()}
           with open(_a ,			encoding='''utf-8''') as merges_handle:
                  A__							=   merges_handle.read().split('''\n''')[1:-1]
           A__							=   [tuple(merge.split()) for merge in bpe_merges]
           A__							=   dict(zip(_a ,			range(len(_a))))
           A__							=   {}
           A__							=   add_prefix_space

           # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
           A__							=   re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''')


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





           '''simple docstring'''

           return len(self.encoder)


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any])						->Optional[Any]:





           '''simple docstring'''

           return dict(self.encoder ,			**self.added_tokens_encoder)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple ,			UpperCAmelCase__				:     Dict)						->int:





           '''simple docstring'''

           if token in self.cache:
                  return self.cache[token]
           A__							=   tuple(_a)
           A__							=   get_pairs(_a)

           if not pairs:
                  return token

           while True:
                  A__							=   min(_a ,			key=lambda UpperCAmelCase__: self.bpe_ranks.get(_a ,			float('''inf''')))
                  if bigram not in self.bpe_ranks:
                         break
                  A__			,							A__							=   bigram
                  A__							=   []
                  A__							=   0
                  while i < len(_a):
                         try:
                                A__							=   word.index(_a ,			_a)
                         except ValueError:
                                new_word.extend(word[i:])
                                break
                         else:
                                new_word.extend(word[i:j])
                                A__							=   j

                         if word[i] == first and i < len(_a) - 1 and word[i + 1] == second:
                                new_word.append(first + second)
                                i += 2
                         else:
                                new_word.append(word[i])
                                i += 1
                  A__							=   tuple(_a)
                  A__							=   new_word
                  if len(_a) == 1:
                         break
                  else:
                         A__							=   get_pairs(_a)
           A__							=   ''' '''.join(_a)
           A__							=   word
           return word


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any] ,			UpperCAmelCase__				:     Any)						->Tuple:





           '''simple docstring'''

           A__							=   []
           for token in re.findall(self.pat ,			_a):
                  A__							=   ''''''.join(
                      self.byte_encoder[b] for b in token.encode('''utf-8'''))  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
                  bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a).split(''' '''))
           return bpe_tokens


    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     List[str])						->int:





           '''simple docstring'''

           return self.encoder.get(_a ,			self.encoder.get(self.unk_token))


    def 	SCREAMING_SNAKE_CASE							(      self				:     Union[str, Any] ,			UpperCAmelCase__				:     Optional[Any])						->Any:





           '''simple docstring'''

           return self.decoder.get(_a)


    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     List[str])						->List[Any]:





           '''simple docstring'''

           A__							=   ''''''.join(_a)
           A__							=   bytearray([self.byte_decoder[c] for c in text]).decode('''utf-8''' ,			errors=self.errors)
           return text


    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[int] ,			UpperCAmelCase__				:     Any ,			UpperCAmelCase__				:     Union[str, Any] = 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'''])
           A__							=   os.path.join(
               _a ,			(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''])

           with open(_a ,			'''w''' ,			encoding='''utf-8''') as f:
                  f.write(json.dumps(self.encoder ,			indent=2 ,			sort_keys=_a ,			ensure_ascii=_a) + '''\n''')

           A__							=   0
           with open(_a ,			'''w''' ,			encoding='''utf-8''') as writer:
                  writer.write('''#version: 0.2\n''')
                  for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,			key=lambda UpperCAmelCase__: kv[1]):
                         if index != token_index:
                                logger.warning(
                                    f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                                    ''' Please check that the tokenizer is not corrupted!''')
                                A__							=   token_index
                         writer.write(''' '''.join(_a) + '''\n''')
                         index += 1

           return vocab_file, merge_file


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any ,			UpperCAmelCase__				:     Dict ,			UpperCAmelCase__				:     Any = None)						->List[int]:





           '''simple docstring'''

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


    def 	SCREAMING_SNAKE_CASE							(      self				:     Union[str, Any] ,			UpperCAmelCase__				:     Any ,			UpperCAmelCase__				:     List[str] = None ,			UpperCAmelCase__				:     Any = 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 None:
                  return [1] + ([0] * len(_a)) + [1]
           return [1] + ([0] * len(_a)) + [1, 1] + ([0] * len(_a)) + [1]


    def 	SCREAMING_SNAKE_CASE							(      self				:     int ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     Any = 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 + sep + token_ids_a + sep) * [0]





    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any] ,			UpperCAmelCase__				:     List[str] ,			UpperCAmelCase__				:     List[str]=False ,			**UpperCAmelCase__				:     Optional[Any])						->Tuple:





           '''simple docstring'''

           A__							=   kwargs.pop('''add_prefix_space''' ,			self.add_prefix_space)
           if (is_split_into_words or add_prefix_space) and (len(_a) > 0 and not text[0].isspace()):
                  A__							=   ''' ''' + text
           return (text, kwargs)








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


_lowerCamelCase     :		Union[str, Any]								=       """▁"""

_lowerCamelCase     :		Optional[Any]								=       {"""vocab_file""": """spiece.model"""}

_lowerCamelCase     :		str								=       {
    """vocab_file""": {"""google/pegasus-xsum""": """https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"""}
}

_lowerCamelCase     :		List[str]								=       {
    """google/pegasus-xsum""": 512,
}


_lowerCamelCase     :		int								=       logging.get_logger(__name__)


class     UpperCamelCase_   (			UpperCAmelCase__					):

    '''simple docstring'''






    UpperCAmelCase__							  =				VOCAB_FILES_NAMES

    UpperCAmelCase__							  =				VOCAB_FILES_NAMES
    UpperCAmelCase__							  =				PRETRAINED_VOCAB_FILES_MAP
    UpperCAmelCase__							  =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    UpperCAmelCase__							  =				['''input_ids''', '''attention_mask''']


    def __init__(      self				:     Optional[int] ,			UpperCAmelCase__				:     Tuple ,			UpperCAmelCase__				:     str="<pad>" ,			UpperCAmelCase__				:     Optional[Any]="</s>" ,			UpperCAmelCase__				:     Any="<unk>" ,			UpperCAmelCase__				:     Union[str, Any]="<mask_2>" ,			UpperCAmelCase__				:     List[str]="<mask_1>" ,			UpperCAmelCase__				:     Dict=None ,			UpperCAmelCase__				:     Optional[Any]=103 ,			UpperCAmelCase__				:     Optional[Dict[str, Any]] = None ,			**UpperCAmelCase__				:     Dict ,			)						->None:





           '''simple docstring'''

           A__							=   offset
           if additional_special_tokens is not None:
                  if not isinstance(UpperCAmelCase__ ,			UpperCAmelCase__):
                         raise TypeError(
                             f"""additional_special_tokens should be of type {type(UpperCAmelCase__)}, but is"""
                             f""" {type(UpperCAmelCase__)}""")

                  A__							=   (
                      ([mask_token_sent] + additional_special_tokens)
                      if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
                      else additional_special_tokens
                  )
                  # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
                  additional_special_tokens_extended += [
                      f"""<unk_{i}>""" for i in range(len(UpperCAmelCase__) ,			self.offset - 1)
                  ]

                  if len(set(UpperCAmelCase__)) != len(UpperCAmelCase__):
                         raise ValueError(
                             '''Please make sure that the provided additional_special_tokens do not contain an incorrectly'''
                             f""" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.""")
                  A__							=   additional_special_tokens_extended
           else:
                  A__							=   [mask_token_sent] if mask_token_sent is not None else []
                  additional_special_tokens += [f"""<unk_{i}>""" for i in range(2 ,			self.offset)]

           A__							=   {} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               eos_token=UpperCAmelCase__ ,			unk_token=UpperCAmelCase__ ,			mask_token=UpperCAmelCase__ ,			pad_token=UpperCAmelCase__ ,			mask_token_sent=UpperCAmelCase__ ,			offset=UpperCAmelCase__ ,			additional_special_tokens=UpperCAmelCase__ ,			sp_model_kwargs=self.sp_model_kwargs ,			**UpperCAmelCase__ ,			)
           A__							=   mask_token_sent
           A__							=   vocab_file
           A__							=   spm.SentencePieceProcessor(**self.sp_model_kwargs)
           self.sp_model.Load(UpperCAmelCase__)

           # add special tokens to encoder dict
           A__							=   {
               0: self.pad_token,
               1: self.eos_token,
           }

           if self.mask_token_sent is not None:
                  self.encoder.update(
                      {
                          2: self.mask_token_sent,
                          3: self.mask_token,
                      })

           if self.offset > 0:
                  # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102
                  # mask_token_sent is already added to list -> so start at 1
                  self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 ,			self.offset - 1)})

           A__							=   {v: k for k, v in self.encoder.items()}


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





           '''simple docstring'''

           return len(self.sp_model) + self.offset


    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any])						->Dict[str, int]:





           '''simple docstring'''

           A__							=   {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				:     Any)						->Union[str, Any]:





           '''simple docstring'''

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


    def __setstate__(      self				:     int ,			UpperCAmelCase__				:     Optional[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 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     str)						->List[str]:





           '''simple docstring'''

           return self.sp_model.encode(UpperCAmelCase__ ,			out_type=UpperCAmelCase__)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any ,			UpperCAmelCase__				:     str)						->int:





           '''simple docstring'''

           if token in self.decoder:
                  return self.decoder[token]
           elif token in self.added_tokens_decoder:
                  return self.added_tokens_decoder[token]
           A__							=   self.sp_model.piece_to_id(UpperCAmelCase__)
           return sp_id + self.offset


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any] ,			UpperCAmelCase__				:     int)						->str:





           '''simple docstring'''

           if index in self.encoder:
                  return self.encoder[index]
           elif index in self.added_tokens_encoder:
                  return self.added_tokens_encoder[index]
           else:
                  A__							=   self.sp_model.IdToPiece(index - self.offset)
           return token


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[str] ,			UpperCAmelCase__				:     int)						->Optional[int]:





           '''simple docstring'''

           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(UpperCAmelCase__) + token
                         A__							=   []
                  else:
                         current_sub_tokens.append(UpperCAmelCase__)
           out_string += self.sp_model.decode(UpperCAmelCase__)
           return out_string.strip()


    def 	SCREAMING_SNAKE_CASE							(      self				:     Union[str, Any] ,			UpperCAmelCase__				:     Optional[int]=False)						->Union[str, Any]:





           '''simple docstring'''

           return 1


    def 	SCREAMING_SNAKE_CASE							(      self				:     int ,			UpperCAmelCase__				:     Union[str, Any])						->Optional[Any]:





           '''simple docstring'''

           A__							=   set(self.all_special_ids)  # call it once instead of inside list comp
           all_special_ids.remove(self.unk_token_id)  # <unk> is only sometimes special

           return [1 if x in all_special_ids else 0 for x in seq]


    def 	SCREAMING_SNAKE_CASE							(      self				:     int ,			UpperCAmelCase__				:     List ,			UpperCAmelCase__				:     Optional[List] = None ,			UpperCAmelCase__				:     bool = False)						->List[int]:





           '''simple docstring'''

           if already_has_special_tokens:
                  return self._special_token_mask(UpperCAmelCase__)
           elif token_ids_a is None:
                  return self._special_token_mask(UpperCAmelCase__) + [1]
           else:
                  return self._special_token_mask(token_ids_a + token_ids_a) + [1]


    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple ,			UpperCAmelCase__				:     List[str] ,			UpperCAmelCase__				:     List[str]=None)						->List[int]:





           '''simple docstring'''

           if token_ids_a is None:
                  return token_ids_a + [self.eos_token_id]
           # We don't expect to process pairs, but leave the pair logic for API consistency
           return token_ids_a + token_ids_a + [self.eos_token_id]





    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     str ,			UpperCAmelCase__				:     Optional[str] = None)						->Tuple[str]:





           '''simple docstring'''

           if not os.path.isdir(UpperCAmelCase__):
                  logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
                  return
           A__							=   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:
                         A__							=   self.sp_model.serialized_model_proto()
                         fi.write(UpperCAmelCase__)

           return (out_vocab_file,)


