






"""simple docstring"""





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      _lowercase :


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





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    Any  			=image_size
            __snake_case      :    int  			=patch_size
            __snake_case      :    List[str]  			=num_channels
            __snake_case      :    List[Any]  			=is_training
            __snake_case      :    Tuple  			=use_labels
            __snake_case      :    Tuple  			=hidden_size
            __snake_case      :    str  			=num_hidden_layers
            __snake_case      :    List[Any]  			=num_attention_heads
            __snake_case      :    Optional[int]  			=intermediate_size
            __snake_case      :    Dict  			=hidden_act
            __snake_case      :    str  			=hidden_dropout_prob
            __snake_case      :    str  			=attention_probs_dropout_prob
            __snake_case      :    Optional[Any]  			=type_sequence_label_size
            __snake_case      :    Any  			=initializer_range
            __snake_case      :    List[str]  			=scope

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


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

            __snake_case      :    Union[str, Any]  			=None
            if self.use_labels:
                  __snake_case      :    List[str]  			=ids_tensor([self.batch_size]							,   self.type_sequence_label_size						)

            __snake_case      :    Union[str, Any]  			=self.get_config()

            return config, pixel_values, labels


      def _UpperCamelCase						(    self				:	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=UpperCAmelCase__							,   initializer_range=self.initializer_range							,   )


      def _UpperCamelCase						(    self				:	Union[str, Any]							,   a				:	Tuple							,   a				:	List[Any]							,   a				:	Optional[Any]						):





            """simple docstring"""







            __snake_case      :    str  			=TFViTModel(config=UpperCAmelCase__						)
            __snake_case      :    Tuple  			=model(UpperCAmelCase__							,   training=UpperCAmelCase__						)
            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.
            __snake_case      :    str  			=self.image_size // 2
            __snake_case      :    List[Any]  			=pixel_values[:, :, :image_size, :image_size]
            __snake_case      :    Tuple  			=model(UpperCAmelCase__							,   interpolate_pos_encoding=UpperCAmelCase__							,   training=UpperCAmelCase__						)
            __snake_case      :    Optional[Any]  			=(image_size // self.patch_size) ** 2 + 1
            self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, seq_length, self.hidden_size)						)


      def _UpperCamelCase						(    self				:	int							,   a				:	int							,   a				:	List[Any]							,   a				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.type_sequence_label_size
            __snake_case      :    str  			=TFViTForImageClassification(UpperCAmelCase__						)
            __snake_case      :    Union[str, Any]  			=model(UpperCAmelCase__							,   labels=UpperCAmelCase__							,   training=UpperCAmelCase__						)
            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.
            __snake_case      :    Dict  			=self.image_size // 2
            __snake_case      :    Optional[Any]  			=pixel_values[:, :, :image_size, :image_size]
            __snake_case      :    List[str]  			=model(UpperCAmelCase__							,   interpolate_pos_encoding=UpperCAmelCase__							,   training=UpperCAmelCase__						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.type_sequence_label_size)						)

            # test greyscale images
            __snake_case      :    List[str]  			=1
            __snake_case      :    Tuple  			=TFViTForImageClassification(UpperCAmelCase__						)
            __snake_case      :    Union[str, Any]  			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
            __snake_case      :    Any  			=model(UpperCAmelCase__						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.type_sequence_label_size)						)







      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            __snake_case      :    Any  			=self.prepare_config_and_inputs()
            __snake_case			,				__snake_case			,				__snake_case      :    str  			=config_and_inputs
            __snake_case      :    int  			={'''pixel_values''': pixel_values}
            return config, inputs_dict



@require_tf
class      _lowercase (     lowerCAmelCase		,  lowerCAmelCase		,  unittest.TestCase						):
      _a   :     int								=   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      _a   :     Tuple								=   (
          {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

      _a   :     Any								=   False
      _a   :     Dict								=   False
      _a   :     Any								=   False


      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            __snake_case      :    int  			=TFViTModelTester(self						)
            __snake_case      :    Dict  			=ConfigTester(self							,   config_class=UpperCAmelCase__							,   has_text_modality=UpperCAmelCase__							,   hidden_size=3_7						)


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            self.config_tester.run_common_tests()


      @unittest.skip(reason='''ViT does not use inputs_embeds'''						)
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            pass


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





            """simple docstring"""







            pass


      def _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Any  			=self.model_tester.prepare_config_and_inputs_for_common()

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


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Any  			=self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __snake_case      :    Tuple  			=model_class(UpperCAmelCase__						)
                  __snake_case      :    List[str]  			=inspect.signature(model.call						)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  __snake_case      :    Optional[Any]  			=[*signature.parameters.keys()]

                  __snake_case      :    Dict  			=['''pixel_values''']
                  self.assertListEqual(arg_names[:1]							,   UpperCAmelCase__						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Union[str, Any]  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*UpperCAmelCase__						)


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            __snake_case      :    str  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__						)







      @slow
      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=TFViTModel.from_pretrained('''google/vit-base-patch16-224'''						)
            self.assertIsNotNone(UpperCAmelCase__						)



def     __lowercase					(    )					->					Union[str, Any]:
      __snake_case      :    Any  			=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
      return image


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


      @cached_property
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







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







      @slow
      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            __snake_case      :    str  			=TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''						)

            __snake_case      :    int  			=self.default_image_processor
            __snake_case      :    List[str]  			=prepare_img()
            __snake_case      :    Optional[Any]  			=image_processor(images=UpperCAmelCase__							,   return_tensors='''tf'''						)

            # forward pass
            __snake_case      :    Any  			=model(**UpperCAmelCase__						)

            # verify the logits
            __snake_case      :    str  			=tf.TensorShape((1, 1_0_0_0)						)
            self.assertEqual(outputs.logits.shape							,   UpperCAmelCase__						)

            __snake_case      :    Optional[int]  			=tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]						)

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










"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import DonutImageProcessor


class      _lowercase (     unittest.TestCase						):


      def __init__(    self				:	List[Any]							,   a				:	int							,   a				:	Dict=7							,   a				:	int=3							,   a				:	int=1_8							,   a				:	Dict=3_0							,   a				:	Dict=4_0_0							,   a				:	Optional[Any]=True							,   a				:	Dict=None							,   a				:	int=True							,   a				:	Dict=False							,   a				:	int=True							,   a				:	str=True							,   a				:	List[str]=[0.5, 0.5, 0.5]							,   a				:	Optional[Any]=[0.5, 0.5, 0.5]							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    Dict  			=image_size
            __snake_case      :    str  			=min_resolution
            __snake_case      :    Tuple  			=max_resolution
            __snake_case      :    str  			=do_resize
            __snake_case      :    Any  			=size if size is not None else {'''height''': 1_8, '''width''': 2_0}
            __snake_case      :    List[Any]  			=do_thumbnail
            __snake_case      :    Tuple  			=do_align_axis
            __snake_case      :    Any  			=do_pad
            __snake_case      :    Dict  			=do_normalize
            __snake_case      :    List[Any]  			=image_mean
            __snake_case      :    Any  			=image_std







      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_thumbnail": self.do_thumbnail,
                "do_align_long_axis": self.do_align_axis,
                "do_pad": self.do_pad,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }



@require_torch
@require_vision
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   DonutImageProcessor if is_vision_available() else None


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=DonutImageProcessingTester(self						)


      @property
      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            self.assertTrue(hasattr(a							,   '''do_resize'''						)						)
            self.assertTrue(hasattr(a							,   '''size'''						)						)
            self.assertTrue(hasattr(a							,   '''do_thumbnail'''						)						)
            self.assertTrue(hasattr(a							,   '''do_align_long_axis'''						)						)
            self.assertTrue(hasattr(a							,   '''do_pad'''						)						)
            self.assertTrue(hasattr(a							,   '''do_normalize'''						)						)
            self.assertTrue(hasattr(a							,   '''image_mean'''						)						)
            self.assertTrue(hasattr(a							,   '''image_std'''						)						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class.from_dict(self.image_processor_dict						)
            self.assertEqual(image_processor.size							,   {'''height''': 1_8, '''width''': 2_0}						)

            __snake_case      :    List[Any]  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=4_2						)
            self.assertEqual(image_processor.size							,   {'''height''': 4_2, '''width''': 4_2}						)

            # Previous config had dimensions in (width, height) order
            __snake_case      :    Tuple  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=(4_2, 8_4)						)
            self.assertEqual(image_processor.size							,   {'''height''': 8_4, '''width''': 4_2}						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @is_flaky()
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PIL images
            __snake_case      :    List[Any]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   Image.Image						)

            # Test not batched input
            __snake_case      :    str  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


      @is_flaky()
      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.image_processing_class(**self.image_processor_dict						)
            # create random numpy tensors
            __snake_case      :    Optional[int]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   numpify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   np.ndarray						)

            # Test not batched input
            __snake_case      :    List[Any]  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    int  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )







      @is_flaky()
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PyTorch tensors
            __snake_case      :    Dict  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   torchify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   torch.Tensor						)

            # Test not batched input
            __snake_case      :    Dict  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


