




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


lowercase__				:     str 		=						logging.get_logger(__name__)


lowercase__				:     Optional[int] 		=						{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

lowercase__				:     Dict 		=						{
    "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",
    },
}

lowercase__				:     Union[str, Any] 		=						{
    "allenai/led-base-16384": 1_6384,
}
class 		UpperCAmelCase   (				_UpperCAmelCase			):







						'''simple docstring'''





						lowerCAmelCase_     		=   VOCAB_FILES_NAMES
						lowerCAmelCase_     		=   PRETRAINED_VOCAB_FILES_MAP
						lowerCAmelCase_     		=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						lowerCAmelCase_     		=   LEDTokenizer
						lowerCAmelCase_     		=   ['''input_ids''', '''attention_mask''']






						def __init__(						self							:     List[Any]       ,	__lowercase							:     Dict=None       ,	__lowercase							:     Optional[int]=None       ,	__lowercase							:     Any=None       ,	__lowercase							:     Optional[int]="replace"       ,	__lowercase							:     List[Any]="<s>"       ,	__lowercase							:     int="</s>"       ,	__lowercase							:     List[str]="</s>"       ,	__lowercase							:     str="<s>"       ,	__lowercase							:     str="<unk>"       ,	__lowercase							:     Dict="<pad>"       ,	__lowercase							:     str="<mask>"       ,	__lowercase							:     List[Any]=False       ,	__lowercase							:     Tuple=True       ,	**__lowercase							:     Optional[Any]       ,	):






							"""simple docstring"""






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

							snake_case_		    =     json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()						)
							if pre_tok_state.get("add_prefix_space"       ,	lowercase_						) != add_prefix_space:
								snake_case_		    =     getattr(lowercase_       ,	pre_tok_state.pop("type"						)						)
								snake_case_		    =     add_prefix_space
								snake_case_		    =     pre_tok_class(**lowercase_						)

							snake_case_		    =     add_prefix_space

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

								snake_case_		    =     False

								if state.get("add_prefix_space"       ,	lowercase_						) != add_prefix_space:
									snake_case_		    =     add_prefix_space
									snake_case_		    =     True

								if state.get("trim_offsets"       ,	lowercase_						) != trim_offsets:
									snake_case_		    =     trim_offsets
									snake_case_		    =     True

								if changes_to_apply:
									snake_case_		    =     getattr(lowercase_       ,	state.pop("type"						)						)
									snake_case_		    =     component_class(**lowercase_						)
									setattr(self.backend_tokenizer       ,	lowercase_       ,	lowercase_						)






						@property
						# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
						def        snake_case__						(						self							:     Any						):






							"""simple docstring"""






							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							:     Tuple       ,	__lowercase							:     Tuple						):






							"""simple docstring"""






							snake_case_		    =     AddedToken(lowercase_       ,	lstrip=lowercase_       ,	rstrip=lowercase_						) if isinstance(lowercase_       ,	lowercase_						) else value
							snake_case_		    =     value






						def        snake_case__						(						self							:     Union[str, Any]       ,	*__lowercase							:     Union[str, Any]       ,	**__lowercase							:     List[Any]						):






							"""simple docstring"""






							snake_case_		    =     kwargs.get("is_split_into_words"       ,	lowercase_						)

							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(*lowercase_       ,	**lowercase_						)






						def        snake_case__						(						self							:     List[Any]       ,	*__lowercase							:     int       ,	**__lowercase							:     List[Any]						):






							"""simple docstring"""






							snake_case_		    =     kwargs.get("is_split_into_words"       ,	lowercase_						)

							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(*lowercase_       ,	**lowercase_						)






						def        snake_case__						(						self							:     Union[str, Any]       ,	__lowercase							:     str       ,	__lowercase							:     Optional[str] = None						):






							"""simple docstring"""






							snake_case_		    =     self._tokenizer.model.save(lowercase_       ,	name=lowercase_						)
							return tuple(lowercase_						)






						def        snake_case__						(						self							:     List[str]       ,	__lowercase							:     str       ,	__lowercase							:     Any=None						):






							"""simple docstring"""






							snake_case_		    =     [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							:     Optional[Any]       ,	__lowercase							:     List[int]       ,	__lowercase							:     Optional[List[int]] = None						):






							"""simple docstring"""






							snake_case_		    =     [self.sep_token_id]
							snake_case_		    =     [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        snake_case__						(						self							:     str       ,	__lowercase							:     Union[Dict[str, EncodedInput], BatchEncoding]       ,	__lowercase							:     Optional[int] = None       ,	__lowercase							:     PaddingStrategy = PaddingStrategy.DO_NOT_PAD       ,	__lowercase							:     Optional[int] = None       ,	__lowercase							:     Optional[bool] = None       ,	):






							"""simple docstring"""






							snake_case_		    =     super()._pad(
							    encoded_inputs=lowercase_       ,	max_length=lowercase_       ,	padding_strategy=lowercase_       ,	pad_to_multiple_of=lowercase_       ,	return_attention_mask=lowercase_       ,	)

							# Load from model defaults
							if return_attention_mask is None:
								snake_case_		    =     "attention_mask" in self.model_input_names

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

								if needs_to_be_padded:
									snake_case_		    =     len(lowercase_						) - 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`
										snake_case_		    =     (
										    encoded_inputs["global_attention_mask"] + [-1] * difference
										)
									elif self.padding_side == "left":
										snake_case_		    =     [-1] * difference + encoded_inputs[
										    "global_attention_mask"
										]
									else:
										raise ValueError("Invalid padding strategy:" + str(self.padding_side						)						)

							return encoded_inputs



from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor


class  A						:







    """simple docstring"""





    def __init__(      self :       Union[str, Any],lowercase_ :       Any,lowercase_ :       Union[str, Any]=1_3,lowercase_ :       Tuple=3_0,lowercase_ :       List[Any]=2,lowercase_ :       Optional[int]=3,lowercase_ :       Union[str, Any]=True,lowercase_ :       Tuple=True,lowercase_ :       Any=3_2,lowercase_ :       List[str]=2,lowercase_ :       Optional[int]=4,lowercase_ :       Union[str, Any]=3_7,lowercase_ :       Tuple="gelu",lowercase_ :       str=0.1,lowercase_ :       Tuple=0.1,lowercase_ :       Union[str, Any]=1_0,lowercase_ :       int=0.02,lowercase_ :       List[Any]=3,lowercase_ :       Any=None,)->    Dict:





        '''simple docstring'''







        A__          =   parent
        A__          =   batch_size
        A__          =   image_size
        A__          =   patch_size
        A__          =   num_channels
        A__          =   is_training
        A__          =   use_labels
        A__          =   hidden_size
        A__          =   num_hidden_layers
        A__          =   num_attention_heads
        A__          =   intermediate_size
        A__          =   hidden_act
        A__          =   hidden_dropout_prob
        A__          =   attention_probs_dropout_prob
        A__          =   type_sequence_label_size
        A__          =   initializer_range
        A__          =   scope

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        A__          =   (image_size // patch_size) ** 2
        A__          =   num_patches + 1


    def 						snake_case__     (      self :       int		)->    List[str]:





        '''simple docstring'''







        A__          =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        A__          =   None
        if self.use_labels:
            A__          =   ids_tensor([self.batch_size],self.type_sequence_label_size		)

        A__          =   self.get_config()

        return config, pixel_values, labels


    def 						snake_case__     (      self :       Tuple		)->    List[Any]:





        '''simple docstring'''







        return ViTConfig(
            image_size=self.image_size,patch_size=self.patch_size,num_channels=self.num_channels,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,is_decoder=lowercase_,initializer_range=self.initializer_range,)


    def 						snake_case__     (      self :       List[str],lowercase_ :       int,lowercase_ :       Union[str, Any],lowercase_ :       Tuple		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   TFViTModel(config=lowercase_		)
        A__          =   model(lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)		)

        # Test with an image with different size than the one specified in config.
        A__          =   self.image_size // 2
        A__          =   pixel_values[:, :, :image_size, :image_size]
        A__          =   model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_		)
        A__          =   (image_size // self.patch_size) ** 2 + 1
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, seq_length, self.hidden_size)		)


    def 						snake_case__     (      self :       List[Any],lowercase_ :       List[Any],lowercase_ :       List[Any],lowercase_ :       List[Any]		)->    Dict:





        '''simple docstring'''







        A__          =   self.type_sequence_label_size
        A__          =   TFViTForImageClassification(lowercase_		)
        A__          =   model(lowercase_,labels=lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)

        # Test with an image with different size than the one specified in config.
        A__          =   self.image_size // 2
        A__          =   pixel_values[:, :, :image_size, :image_size]
        A__          =   model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)

        # test greyscale images
        A__          =   1
        A__          =   TFViTForImageClassification(lowercase_		)
        A__          =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
        A__          =   model(lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)


    def 						snake_case__     (      self :       Any		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.prepare_config_and_inputs()
        A__      ,						A__      ,						A__          =   config_and_inputs
        A__          =   {'pixel_values': pixel_values}
        return config, inputs_dict




@require_tf
class  A						(							_UpperCAmelCase    ,							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
    lowerCamelCase			=							(
        {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
        if is_tf_available()
        else {}
    )

    lowerCamelCase			=							False
    lowerCamelCase			=							False
    lowerCamelCase			=							False


    def 						snake_case__     (      self :       int		)->    List[Any]:





        '''simple docstring'''







        A__          =   TFViTModelTester(self		)
        A__          =   ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_,hidden_size=3_7		)


    def 						snake_case__     (      self :       Any		)->    Optional[Any]:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    @unittest.skip(reason='ViT does not use inputs_embeds'		)
    def 						snake_case__     (      self :       Optional[Any]		)->    str:





        '''simple docstring'''







        pass


    @unittest.skip(reason='ViT does not use inputs_embeds'		)
    def 						snake_case__     (      self :       Any		)->    int:





        '''simple docstring'''







        pass


    def 						snake_case__     (      self :       str		)->    Dict:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A__          =   model_class(lowercase_		)
            self.assertIsInstance(model.get_input_embeddings(),(tf.keras.layers.Layer)		)
            A__          =   model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(lowercase_,tf.keras.layers.Layer		)		)


    def 						snake_case__     (      self :       int		)->    List[str]:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A__          =   model_class(lowercase_		)
            A__          =   inspect.signature(model.call		)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            A__          =   [*signature.parameters.keys()]

            A__          =   ['pixel_values']
            self.assertListEqual(arg_names[:1],lowercase_		)


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





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase_		)


    def 						snake_case__     (      self :       Optional[Any]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase_		)


    @slow
    def 						snake_case__     (      self :       Union[str, Any]		)->    Union[str, Any]:





        '''simple docstring'''







        A__          =   TFViTModel.from_pretrained('google/vit-base-patch16-224'		)
        self.assertIsNotNone(lowercase_		)




def 						_snake_case(    )							->      str:





    '''simple docstring'''






    A__          =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
    return image


@require_tf
@require_vision
class  A						(							unittest.TestCase ):







    """simple docstring"""





    @cached_property
    def 						snake_case__     (      self :       List[Any]		)->    str:





        '''simple docstring'''







        return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'		) if is_vision_available() else None


    @slow
    def 						snake_case__     (      self :       Any		)->    Dict:





        '''simple docstring'''







        A__          =   TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'		)

        A__          =   self.default_image_processor
        A__          =   prepare_img()
        A__          =   image_processor(images=lowercase_,return_tensors='tf'		)

        # forward pass
        A__          =   model(**lowercase_		)

        # verify the logits
        A__          =   tf.TensorShape((1, 1_0_0_0)		)
        self.assertEqual(outputs.logits.shape,lowercase_		)

        A__          =   tf.constant([-0.2_744, 0.8_215, -0.0_836]		)

        tf.debugging.assert_near(outputs.logits[0, :3],lowercase_,atol=1E-4		)

