






"""simple docstring"""

from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
					from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor


class 						__lowerCamelCase							(					snake_case__     ):





		'''simple docstring'''






		def   lowerCamelCase			(  self				:      List[str]      ):
				lowerCAmelCase_  :				Union[str, Any]   							=     self.config_class(**self.inputs_dict      )
				self.parent.assertTrue(hasattr(__lowercase		,     "embed_dim"      )      )
				self.parent.assertTrue(hasattr(__lowercase		,     "num_heads"      )      )







class 						__lowerCamelCase							:





		'''simple docstring'''






		def __init__(  self				:      Tuple		,     a_				:      Dict		,     a_				:      Optional[int]=13		,     a_				:      Any=64		,     a_				:      str=3		,     a_				:      Optional[Any]=[16, 48, 96]		,     a_				:      Any=[1, 3, 6]		,     a_				:      Optional[int]=[1, 2, 10]		,     a_				:      List[str]=[7, 3, 3]		,     a_				:      str=[4, 2, 2]		,     a_				:      List[str]=[2, 1, 1]		,     a_				:      Optional[int]=[2, 2, 2]		,     a_				:      Union[str, Any]=[False, False, True]		,     a_				:      str=[0.0, 0.0, 0.0]		,     a_				:      Any=0.02		,     a_				:      int=1e-1_2		,     a_				:      Union[str, Any]=True		,     a_				:      Optional[int]=True		,     a_				:      Dict=2		,     ):
				lowerCAmelCase_  :				Tuple   							=     parent
				lowerCAmelCase_  :				Union[str, Any]   							=     batch_size
				lowerCAmelCase_  :				Optional[Any]   							=     image_size
				lowerCAmelCase_  :				Optional[int]   							=     patch_sizes
				lowerCAmelCase_  :				Dict   							=     patch_stride
				lowerCAmelCase_  :				Optional[Any]   							=     patch_padding
				lowerCAmelCase_  :				Union[str, Any]   							=     is_training
				lowerCAmelCase_  :				str   							=     use_labels
				lowerCAmelCase_  :				List[str]   							=     num_labels
				lowerCAmelCase_  :				Any   							=     num_channels
				lowerCAmelCase_  :				Any   							=     embed_dim
				lowerCAmelCase_  :				List[Any]   							=     num_heads
				lowerCAmelCase_  :				Optional[int]   							=     stride_kv
				lowerCAmelCase_  :				Tuple   							=     depth
				lowerCAmelCase_  :				Any   							=     cls_token
				lowerCAmelCase_  :				str   							=     attention_drop_rate
				lowerCAmelCase_  :				Optional[Any]   							=     initializer_range
				lowerCAmelCase_  :				List[Any]   							=     layer_norm_eps





		def   lowerCamelCase			(  self				:      List[str]      ):
				lowerCAmelCase_  :				Optional[int]   							=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

				lowerCAmelCase_  :				str   							=     None
				if self.use_labels:
						# create a random int32 tensor of given shape
						lowerCAmelCase_  :				List[str]   							=     ids_tensor([self.batch_size]		,     self.num_labels      )

				lowerCAmelCase_  :				str   							=     self.get_config()
				return config, pixel_values, labels





		def   lowerCamelCase			(  self				:      Dict      ):
				return CvtConfig(
				    image_size=self.image_size		,     num_labels=self.num_labels		,     num_channels=self.num_channels		,     embed_dim=self.embed_dim		,     num_heads=self.num_heads		,     patch_sizes=self.patch_sizes		,     patch_padding=self.patch_padding		,     patch_stride=self.patch_stride		,     stride_kv=self.stride_kv		,     depth=self.depth		,     cls_token=self.cls_token		,     attention_drop_rate=self.attention_drop_rate		,     initializer_range=self.initializer_range		,     )





		def   lowerCamelCase			(  self				:      Tuple		,     a_				:      Optional[Any]		,     a_				:      Tuple		,     a_				:      Union[str, Any]      ):
				lowerCAmelCase_  :				Optional[Any]   							=     TFCvtModel(config=__lowercase      )
				lowerCAmelCase_  :				Optional[int]   							=     model(__lowercase		,     training=__lowercase      )
				lowerCAmelCase_  :				Tuple   							=     (self.image_size, self.image_size)
				lowerCAmelCase_  :				List[Any]   							=     image_size[0], image_size[1]
				for i in range(len(self.depth      )      ):
						lowerCAmelCase_  :				Dict   							=     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1      )
						lowerCAmelCase_  :				Any   							=     floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1      )
				self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.embed_dim[-1], height, width)      )





		def   lowerCamelCase			(  self				:      Optional[Any]		,     a_				:      Optional[int]		,     a_				:      Optional[Any]		,     a_				:      Union[str, Any]      ):
				lowerCAmelCase_  :				List[Any]   							=     self.num_labels
				lowerCAmelCase_  :				Tuple   							=     TFCvtForImageClassification(__lowercase      )
				lowerCAmelCase_  :				Any   							=     model(__lowercase		,     labels=__lowercase		,     training=__lowercase      )
				self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)      )





		def   lowerCamelCase			(  self				:      Optional[int]      ):
				lowerCAmelCase_  :				Optional[int]   							=     self.prepare_config_and_inputs()
				lowerCAmelCase_  :				int   							=     config_and_inputs
				lowerCAmelCase_  :				int   							=     {'''pixel_values''': pixel_values}
				return config, inputs_dict







@require_tf
class 						__lowerCamelCase							(					snake_case__					,				snake_case__					,				unittest.TestCase     ):





		'''simple docstring'''






		a_      :							Dict  =				(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
		a_      :							Union[str, Any]  =				(
		    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
		    if is_tf_available()
		    else {}
		)
		a_      :							Optional[int]  =				False
		a_      :							List[Any]  =				False
		a_      :							Optional[int]  =				False
		a_      :							str  =				False
		a_      :							Dict  =				False





		def   lowerCamelCase			(  self				:      List[Any]      ):
				lowerCAmelCase_  :				Tuple   							=     TFCvtModelTester(self      )
				lowerCAmelCase_  :				Optional[int]   							=     TFCvtConfigTester(self		,     config_class=__lowercase		,     has_text_modality=__lowercase		,     hidden_size=37      )





		def   lowerCamelCase			(  self				:      Any      ):
				self.config_tester.create_and_test_config_common_properties()
				self.config_tester.create_and_test_config_to_json_string()
				self.config_tester.create_and_test_config_to_json_file()
				self.config_tester.create_and_test_config_from_and_save_pretrained()
				self.config_tester.create_and_test_config_with_num_labels()
				self.config_tester.check_config_can_be_init_without_params()
				self.config_tester.check_config_arguments_init()





		@unittest.skip(reason="Cvt does not output attentions"      )
		def   lowerCamelCase			(  self				:      Optional[Any]      ):
				pass





		@unittest.skip(reason="Cvt does not use inputs_embeds"      )
		def   lowerCamelCase			(  self				:      Any      ):
				pass





		@unittest.skip(reason="Cvt does not support input and output embeddings"      )
		def   lowerCamelCase			(  self				:      Tuple      ):
				pass





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU"      )      ) == 0		,     reason="TF does not support backprop for grouped convolutions on CPU."		,     )
		def   lowerCamelCase			(  self				:      Any      ):
				super().test_dataset_conversion()





		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices("GPU"      )      ) == 0		,     reason="TF does not support backprop for grouped convolutions on CPU."		,     )
		@slow
		def   lowerCamelCase			(  self				:      Dict      ):
				super().test_keras_fit()





		@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"      )
		def   lowerCamelCase			(  self				:      int      ):
				lowerCAmelCase_  :				int   							=     tf.keras.mixed_precision.Policy("mixed_float16"      )
				tf.keras.mixed_precision.set_global_policy(__lowercase      )
				super().test_keras_fit()
				tf.keras.mixed_precision.set_global_policy("float32"      )





		def   lowerCamelCase			(  self				:      Dict      ):
				lowerCAmelCase_  :				Dict   							=     self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowerCAmelCase_  :				int   							=     model_class(__lowercase      )
						lowerCAmelCase_  :				Optional[int]   							=     inspect.signature(model.call      )
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						lowerCAmelCase_  :				Union[str, Any]   							=     [*signature.parameters.keys()]

						lowerCAmelCase_  :				Dict   							=     ['''pixel_values''']
						self.assertListEqual(arg_names[:1]		,     __lowercase      )





		def   lowerCamelCase			(  self				:      List[str]      ):
				def check_hidden_states_output(a_				:      Any		,     a_				:      List[Any]		,     a_				:      Union[str, Any]      ):
						lowerCAmelCase_  :				Optional[Any]   							=     model_class(__lowercase      )

						lowerCAmelCase_  :				Optional[int]   							=     model(**self._prepare_for_class(__lowercase		,     __lowercase      )      )
						lowerCAmelCase_  :				Tuple   							=     outputs.hidden_states

						lowerCAmelCase_  :				List[str]   							=     len(self.model_tester.depth      )
						self.assertEqual(len(__lowercase      )		,     __lowercase      )

						# verify the first hidden states (first block)
						self.assertListEqual(
						    list(hidden_states[0].shape[-3:]      )		,     [
						        self.model_tester.embed_dim[0],
						        self.model_tester.image_size // 4,
						        self.model_tester.image_size // 4,
						    ]		,     )

				lowerCAmelCase_  :				Any   							=     self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowerCAmelCase_  :				str   							=     True
						check_hidden_states_output(__lowercase		,     __lowercase		,     __lowercase      )

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						lowerCAmelCase_  :				Dict   							=     True

						check_hidden_states_output(__lowercase		,     __lowercase		,     __lowercase      )





		def   lowerCamelCase			(  self				:      List[Any]      ):
				lowerCAmelCase_  :				Optional[int]   							=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__lowercase      )





		def   lowerCamelCase			(  self				:      List[str]      ):
				lowerCAmelCase_  :				Dict   							=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*__lowercase      )





		@slow
		def   lowerCamelCase			(  self				:      List[Any]      ):
				for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowerCAmelCase_  :				int   							=     TFCvtModel.from_pretrained(__lowercase      )
						self.assertIsNotNone(__lowercase      )







def 						__lowerCamelCase      (    )		->       Union[str, Any]:

		"""simple docstring"""







		lowerCAmelCase_  :				Optional[int]   							=     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
		return image



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





		'''simple docstring'''






		@cached_property
		def   lowerCamelCase			(  self				:      List[str]      ):
				return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )





		@slow
		def   lowerCamelCase			(  self				:      List[Any]      ):
				lowerCAmelCase_  :				str   							=     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

				lowerCAmelCase_  :				List[Any]   							=     self.default_image_processor
				lowerCAmelCase_  :				Union[str, Any]   							=     prepare_img()
				lowerCAmelCase_  :				List[Any]   							=     image_processor(images=__lowercase		,     return_tensors="tf"      )

				# forward pass
				lowerCAmelCase_  :				Optional[int]   							=     model(**__lowercase      )

				# verify the logits
				lowerCAmelCase_  :				Union[str, Any]   							=     tf.TensorShape((1, 10_00)      )
				self.assertEqual(outputs.logits.shape		,     __lowercase      )

				lowerCAmelCase_  :				List[Any]   							=     tf.constant([0.9285, 0.9015, -0.3150]      )
				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()		,     __lowercase		,     atol=1e-4      )      )







"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_UpperCamelCase					      =   {
    'configuration_pix2struct': [
        'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'Pix2StructConfig',
        'Pix2StructTextConfig',
        'Pix2StructVisionConfig',
    ],
    'processing_pix2struct': ['Pix2StructProcessor'],
}

try:
							if not is_vision_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							_UpperCamelCase					      =   ['Pix2StructImageProcessor']


try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							_UpperCamelCase					      =   [
							    'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST',
							    'Pix2StructPreTrainedModel',
							    'Pix2StructForConditionalGeneration',
							    'Pix2StructVisionModel',
							    'Pix2StructTextModel',
							]

if TYPE_CHECKING:
							from .configuration_pixastruct import (
							    PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
							    PixaStructConfig,
							    PixaStructTextConfig,
							    PixaStructVisionConfig,
							)
							from .processing_pixastruct import PixaStructProcessor

							try:
														if not is_vision_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .image_processing_pixastruct import PixaStructImageProcessor

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_pixastruct import (
														    PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    PixaStructForConditionalGeneration,
														    PixaStructPreTrainedModel,
														    PixaStructTextModel,
														    PixaStructVisionModel,
														)

else:
							import sys

							_UpperCamelCase					      =   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




