



'''simple docstring'''






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_longformer import LongformerTokenizer


A_				:					Any							=      logging.get_logger(__name__)

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

A_				:					Optional[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"""
        ),
    },
    """tokenizer_file""": {
        """allenai/longformer-base-4096""": (
            """https://huggingface.co/allenai/longformer-base-4096/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/tokenizer.json"""
        ),
    },
}

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



class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    VOCAB_FILES_NAMES
 UpperCAmelCase		      =    PRETRAINED_VOCAB_FILES_MAP
 UpperCAmelCase		      =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 UpperCAmelCase		      =    ["""input_ids""", """attention_mask"""]
 UpperCAmelCase		      =    LongformerTokenizer







 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_    ,)						->  str:
        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_    ,)

        _UpperCAmelCase    :		Any     	=					json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()				)
        if pre_tok_state.get("""add_prefix_space"""    ,a_				) != add_prefix_space:
               _UpperCAmelCase    :		List[str]     	=					getattr(a_    ,pre_tok_state.pop("""type"""				)				)
               _UpperCAmelCase    :		List[str]     	=					add_prefix_space
               _UpperCAmelCase    :		int     	=					pre_tok_class(**a_				)

        _UpperCAmelCase    :		Union[str, Any]     	=					add_prefix_space

        _UpperCAmelCase    :		Union[str, Any]     	=					"""post_processor"""
        _UpperCAmelCase    :		Optional[Any]     	=					getattr(self.backend_tokenizer    ,a_    ,a_				)
        if tokenizer_component_instance:
               _UpperCAmelCase    :		Tuple     	=					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:
                      _UpperCAmelCase    :		str     	=					tuple(state["""sep"""]				)
               if "cls" in state:
                      _UpperCAmelCase    :		str     	=					tuple(state["""cls"""]				)

               _UpperCAmelCase    :		int     	=					False

               if state.get("""add_prefix_space"""    ,a_				) != add_prefix_space:
                      _UpperCAmelCase    :		Dict     	=					add_prefix_space
                      _UpperCAmelCase    :		Optional[int]     	=					True

               if state.get("""trim_offsets"""    ,a_				) != trim_offsets:
                      _UpperCAmelCase    :		Optional[Any]     	=					trim_offsets
                      _UpperCAmelCase    :		str     	=					True

               if changes_to_apply:
                      _UpperCAmelCase    :		Dict     	=					getattr(a_    ,state.pop("""type"""				)				)
                      _UpperCAmelCase    :		Dict     	=					component_class(**a_				)
                      setattr(self.backend_tokenizer    ,a_    ,a_				)







 @property
 def _snake_case					(				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 _snake_case					(				self    ,a_				)						->  List[str]:
        _UpperCAmelCase    :		Tuple     	=					AddedToken(a_    ,lstrip=a_    ,rstrip=a_				) if isinstance(a_    ,a_				) else value
        _UpperCAmelCase    :		List[Any]     	=					value







 def _snake_case					(				self    ,*a_    ,**a_				)						->  BatchEncoding:
        _UpperCAmelCase    :		int     	=					kwargs.get("""is_split_into_words"""    ,a_				)
        assert self.add_prefix_space or not is_split_into_words, (
            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 _snake_case					(				self    ,*a_    ,**a_				)						->  BatchEncoding:
        _UpperCAmelCase    :		int     	=					kwargs.get("""is_split_into_words"""    ,a_				)

        assert self.add_prefix_space or not is_split_into_words, (
            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 _snake_case					(				self    ,a_    ,a_ = None				)						->  Tuple[str]:
        _UpperCAmelCase    :		Any     	=					self._tokenizer.model.save(a_    ,name=a_				)
        return tuple(a_				)







 def _snake_case					(				self    ,a_    ,a_=None				)						->  Optional[int]:
        _UpperCAmelCase    :		str     	=					[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 _snake_case					(				self    ,a_    ,a_ = None				)						->  List[int]:
        _UpperCAmelCase    :		Dict     	=					[self.sep_token_id]
        _UpperCAmelCase    :		Dict     	=					[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]







from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available
def 				UpperCamelCase_	(					__snake_case      :    Dict  )->   str:




						'''simple docstring'''
						if is_torch_available():
												import torch

												if isinstance(__snake_case						,      torch.Tensor  ):
																		return True

						return isinstance(__snake_case						,      np.ndarray  )




class      __snake_case				(   _UpperCAmelCase):
					def 	a			(						self       :						Optional[Any]  )							->					Optional[Any]:



											'''simple docstring'''





											__magic_name__					=      fields(self  )

											# Safety and consistency checks
											if not len(_lowerCAmelCase  ):
																	raise ValueError(F'''{self.__class__.__name__} has no fields.'''  )

											__magic_name__					=      getattr(self	,      class_fields[0].name  )
											__magic_name__					=      all(getattr(self	,      field.name  ) is None for field in class_fields[1:]  )

											if other_fields_are_none and isinstance(_lowerCAmelCase	,      _lowerCAmelCase  ):
																	for key, value in first_field.items():
																							__magic_name__					=      value
											else:
																	for field in class_fields:
																							__magic_name__					=      getattr(self	,      field.name  )
																							if v is not None:
																													__magic_name__					=      v
					def __delitem__(						self       :						Dict	,      *_lowerCAmelCase       :						List[str]	,      **_lowerCAmelCase       :						List[str]  )							->					List[str]:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Optional[int]	,      *_lowerCAmelCase       :						Optional[Any]	,      **_lowerCAmelCase       :						Optional[Any]  )							->					str:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Union[str, Any]	,      *_lowerCAmelCase       :						List[str]	,      **_lowerCAmelCase       :						Any  )							->					str:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Any	,      *_lowerCAmelCase       :						str	,      **_lowerCAmelCase       :						Optional[int]  )							->					List[Any]:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''  )
					def __getitem__(						self       :						Optional[Any]	,      _lowerCAmelCase       :						Any  )							->					Tuple:



											'''simple docstring'''





											if isinstance(_lowerCAmelCase	,      _lowerCAmelCase  ):
																	__magic_name__					=      dict(self.items()  )
																	return inner_dict[k]
											else:
																	return self.to_tuple()[k]
					def __setattr__(						self       :						str	,      _lowerCAmelCase       :						Optional[Any]	,      _lowerCAmelCase       :						Optional[int]  )							->					int:



											'''simple docstring'''





											if name in self.keys() and value is not None:
																	# Don't call self.__setitem__ to avoid recursion errors
																	super().__setitem__(_lowerCAmelCase	,      _lowerCAmelCase  )
											super().__setattr__(_lowerCAmelCase	,      _lowerCAmelCase  )
					def __setitem__(						self       :						Optional[Any]	,      _lowerCAmelCase       :						Optional[Any]	,      _lowerCAmelCase       :						List[str]  )							->					Optional[int]:



											'''simple docstring'''





											super().__setitem__(_lowerCAmelCase	,      _lowerCAmelCase  )
											# Don't call self.__setattr__ to avoid recursion errors
											super().__setattr__(_lowerCAmelCase	,      _lowerCAmelCase  )







					def 	a			(						self       :						str  )							->					Tuple[Any]:



											'''simple docstring'''





											return tuple(self[k] for k in self.keys()  )

