






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 (      __a):





	"""simple docstring"""






	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.config_class(**self.inputs_dict    )
							self.parent.assertTrue(hasattr(UpperCAmelCase       ,    'embed_dim'    )    )
							self.parent.assertTrue(hasattr(UpperCAmelCase       ,    'num_heads'    )    )





class __lowerCamelCase :





	"""simple docstring"""






	def __init__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase=13       ,    UpperCAmelCase=64       ,    UpperCAmelCase=3       ,    UpperCAmelCase=[16, 48, 96]       ,    UpperCAmelCase=[1, 3, 6]       ,    UpperCAmelCase=[1, 2, 10]       ,    UpperCAmelCase=[7, 3, 3]       ,    UpperCAmelCase=[4, 2, 2]       ,    UpperCAmelCase=[2, 1, 1]       ,    UpperCAmelCase=[2, 2, 2]       ,    UpperCAmelCase=[False, False, True]       ,    UpperCAmelCase=[0.0, 0.0, 0.0]       ,    UpperCAmelCase=0.02       ,    UpperCAmelCase=1e-12       ,    UpperCAmelCase=True       ,    UpperCAmelCase=True       ,    UpperCAmelCase=2       ,    ):
							"""simple docstring"""







							_UpperCAmelCase									=			parent
							_UpperCAmelCase									=			batch_size
							_UpperCAmelCase									=			image_size
							_UpperCAmelCase									=			patch_sizes
							_UpperCAmelCase									=			patch_stride
							_UpperCAmelCase									=			patch_padding
							_UpperCAmelCase									=			is_training
							_UpperCAmelCase									=			use_labels
							_UpperCAmelCase									=			num_labels
							_UpperCAmelCase									=			num_channels
							_UpperCAmelCase									=			embed_dim
							_UpperCAmelCase									=			num_heads
							_UpperCAmelCase									=			stride_kv
							_UpperCAmelCase									=			depth
							_UpperCAmelCase									=			cls_token
							_UpperCAmelCase									=			attention_drop_rate
							_UpperCAmelCase									=			initializer_range
							_UpperCAmelCase									=			layer_norm_eps

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

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

							_UpperCAmelCase									=			self.get_config()
							return config, pixel_values, labels

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFCvtModel(config=UpperCAmelCase    )
							_UpperCAmelCase									=			model(UpperCAmelCase       ,    training=UpperCAmelCase    )
							_UpperCAmelCase									=			(self.image_size, self.image_size)
							_UpperCAmelCase					, _UpperCAmelCase									=			image_size[0], image_size[1]
							for i in range(len(self.depth    )    ):
													_UpperCAmelCase									=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
													_UpperCAmelCase									=			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        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.num_labels
							_UpperCAmelCase									=			TFCvtForImageClassification(UpperCAmelCase    )
							_UpperCAmelCase									=			model(UpperCAmelCase       ,    labels=UpperCAmelCase       ,    training=UpperCAmelCase    )
							self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_labels)    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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





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





	"""simple docstring"""






	UpperCamelCase__								=      (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	UpperCamelCase__								=      (
	    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFCvtModelTester(self    )
							_UpperCAmelCase									=			TFCvtConfigTester(self       ,    config_class=UpperCAmelCase       ,    has_text_modality=UpperCAmelCase       ,    hidden_size=37    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip(reason='Cvt does not use inputs_embeds'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip(reason='Cvt does not support input and output embeddings'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			tf.keras.mixed_precision.Policy('mixed_float16'    )
							tf.keras.mixed_precision.set_global_policy(UpperCAmelCase    )
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('float32'    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCAmelCase									=			['pixel_values']
													self.assertListEqual(arg_names[:1]       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							def check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )

													_UpperCAmelCase									=			model(**self._prepare_for_class(UpperCAmelCase       ,    UpperCAmelCase    )    )
													_UpperCAmelCase									=			outputs.hidden_states

													_UpperCAmelCase									=			len(self.model_tester.depth    )
													self.assertEqual(len(UpperCAmelCase    )       ,    UpperCAmelCase    )

													# 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,
													    ]       ,    )

							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCAmelCase									=			True
													check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_UpperCAmelCase									=			True

													check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase    )

	@slow
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCAmelCase									=			TFCvtModel.from_pretrained(UpperCAmelCase    )
													self.assertIsNotNone(UpperCAmelCase    )



def __A    (      )->  Any:





						"""simple docstring"""



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





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





	"""simple docstring"""






	@cached_property
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

	@slow
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

							_UpperCAmelCase									=			self.default_image_processor
							_UpperCAmelCase									=			prepare_img()
							_UpperCAmelCase									=			image_processor(images=UpperCAmelCase       ,    return_tensors='tf'    )

							# forward pass
							_UpperCAmelCase									=			model(**UpperCAmelCase    )

							# verify the logits
							_UpperCAmelCase									=			tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape       ,    UpperCAmelCase    )

							_UpperCAmelCase									=			tf.constant([0.92_85, 0.90_15, -0.31_50]    )
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,    UpperCAmelCase       ,    atol=1e-4    )    )






'''simple docstring'''







from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
   import torch


A     =logging.get_logger(__name__)


class 			_a  (	__a ):
       __a				:     str   				=					["""pixel_values"""]
       def __init__(	self						:	Optional[int]   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Dict[str, int]] = None   ,				lowercase						:	PILImageResampling = PILImageResampling.BILINEAR   ,				lowercase						:	bool = True   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	bool = True   ,				lowercase						:	Union[int, float] = 1 / 255   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)
           UpperCAmelCase			       =		size if size is not None else {'''shortest_edge''': 256}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_resize
           UpperCAmelCase			       =		size
           UpperCAmelCase			       =		resample
           UpperCAmelCase			       =		do_center_crop
           UpperCAmelCase			       =		crop_size
           UpperCAmelCase			       =		do_rescale
           UpperCAmelCase			       =		rescale_factor
           UpperCAmelCase			       =		do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
           UpperCAmelCase			       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Any   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           if "shortest_edge" not in size:
               raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"				)
           UpperCAmelCase			       =		get_resize_output_image_size(lowercase   ,				size=size['''shortest_edge''']   ,				default_to_square=lowercase				)
           return resize(lowercase   ,				size=lowercase   ,				resample=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	int   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase				)
           if "height" not in size or "width" not in size:
               raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"				)
           return center_crop(lowercase   ,				size=(size['''height'''], size['''width'''])   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Tuple   ,				lowercase						:	np.ndarray   ,				lowercase						:	float   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

           return rescale(lowercase   ,				scale=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           return normalize(lowercase   ,				mean=lowercase   ,				std=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	ImageInput   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	PILImageResampling = None   ,				lowercase						:	bool = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[float] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[str, TensorType]] = None   ,				lowercase						:	Union[str, ChannelDimension] = ChannelDimension.FIRST   ,				**lowercase						:	Dict   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		do_resize if do_resize is not None else self.do_resize
           UpperCAmelCase			       =		size if size is not None else self.size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		resample if resample is not None else self.resample
           UpperCAmelCase			       =		do_center_crop if do_center_crop is not None else self.do_center_crop
           UpperCAmelCase			       =		crop_size if crop_size is not None else self.crop_size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_rescale if do_rescale is not None else self.do_rescale
           UpperCAmelCase			       =		rescale_factor if rescale_factor is not None else self.rescale_factor
           UpperCAmelCase			       =		do_normalize if do_normalize is not None else self.do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else self.image_mean
           UpperCAmelCase			       =		image_std if image_std is not None else self.image_std

           UpperCAmelCase			       =		make_list_of_images(lowercase				)

           if not valid_images(lowercase				):
               raise ValueError(
                   '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                   '''torch.Tensor, tf.Tensor or jax.ndarray.'''				)

           if do_resize and size is None:
               raise ValueError('''Size must be specified if do_resize is True.'''				)

           if do_center_crop and crop_size is None:
               raise ValueError('''Crop size must be specified if do_center_crop is True.'''				)

           if do_rescale and rescale_factor is None:
               raise ValueError('''Rescale factor must be specified if do_rescale is True.'''				)

           if do_normalize and (image_mean is None or image_std is None):
               raise ValueError('''Image mean and std must be specified if do_normalize is True.'''				)

           # All transformations expect numpy arrays.
           UpperCAmelCase			       =		[to_numpy_array(lowercase				) for image in images]

           if do_resize:
               UpperCAmelCase			       =		[self.resize(image=lowercase   ,				size=lowercase   ,				resample=lowercase				) for image in images]

           if do_center_crop:
               UpperCAmelCase			       =		[self.center_crop(image=lowercase   ,				size=lowercase				) for image in images]

           if do_rescale:
               UpperCAmelCase			       =		[self.rescale(image=lowercase   ,				scale=lowercase				) for image in images]

           if do_normalize:
               UpperCAmelCase			       =		[self.normalize(image=lowercase   ,				mean=lowercase   ,				std=lowercase				) for image in images]

           UpperCAmelCase			       =		[to_channel_dimension_format(lowercase   ,				lowercase				) for image in images]

           UpperCAmelCase			       =		{'''pixel_values''': images}
           return BatchFeature(data=lowercase   ,				tensor_type=lowercase				)







       def     A      (	self						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	List[Tuple] = None				):



           '''simple docstring'''

           UpperCAmelCase			       =		outputs.logits

           # Resize logits and compute semantic segmentation maps
           if target_sizes is not None:
               if len(lowercase				) != len(lowercase				):
                   raise ValueError(
                       '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

               if is_torch_tensor(lowercase				):
                   UpperCAmelCase			       =		target_sizes.numpy()

               UpperCAmelCase			       =		[]

               for idx in range(len(lowercase				)				):
                   UpperCAmelCase			       =		torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0				)   ,				size=target_sizes[idx]   ,				mode='''bilinear'''   ,				align_corners=lowercase				)
                   UpperCAmelCase			       =		resized_logits[0].argmax(dim=0				)
                   semantic_segmentation.append(lowercase				)
           else:
               UpperCAmelCase			       =		logits.argmax(dim=1				)
               UpperCAmelCase			       =		[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

           return semantic_segmentation




