






'''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 _lowercase     (    _lowercase		):




       def 		lowerCamelCase_    (							self:    Any					):
              lowerCamelCase__ :     List[str]	  =	self.config_class(**self.inputs_dict					)
              self.parent.assertTrue(hasattr(UpperCamelCase__      ,							"""embed_dim"""					)					)
              self.parent.assertTrue(hasattr(UpperCamelCase__      ,							"""num_heads"""					)					)



class _lowercase     :




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




       def 		lowerCamelCase_    (							self:    Union[str, Any]					):
              lowerCamelCase__ :     List[Any]	  =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

              lowerCamelCase__ :     Union[str, Any]	  =	self.get_config()
              return config, pixel_values, labels




       def 		lowerCamelCase_    (							self:    Tuple					):
              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      ,							UpperCamelCase__:    Dict      ,							UpperCamelCase__:    Union[str, Any]      ,							UpperCamelCase__:    Union[str, Any]					):
              lowerCamelCase__ :     Union[str, Any]	  =	TFCvtModel(config=UpperCamelCase__					)
              lowerCamelCase__ :     int	  =	model(UpperCamelCase__      ,							training=UpperCamelCase__					)
              lowerCamelCase__ :     Dict	  =	(self.image_size, self.image_size)
              lowerCamelCase__ :     List[str]	  =	image_size[0], image_size[1]
              for i in range(len(self.depth					)					):
                     lowerCamelCase__ :     Tuple	  =	floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
                     lowerCamelCase__ :     List[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:    List[str]      ,							UpperCamelCase__:    List[str]      ,							UpperCamelCase__:    List[Any]      ,							UpperCamelCase__:    Any					):
              lowerCamelCase__ :     Optional[int]	  =	self.num_labels
              lowerCamelCase__ :     List[str]	  =	TFCvtForImageClassification(UpperCamelCase__					)
              lowerCamelCase__ :     List[Any]	  =	model(UpperCamelCase__      ,							labels=UpperCamelCase__      ,							training=UpperCamelCase__					)
              self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.num_labels)					)




       def 		lowerCamelCase_    (							self:    int					):
              lowerCamelCase__ :     Union[str, Any]	  =	self.prepare_config_and_inputs()
              lowerCamelCase__ :     int	  =	config_and_inputs
              lowerCamelCase__ :     Optional[int]	  =	{"""pixel_values""": pixel_values}
              return config, inputs_dict



@require_tf
class _lowercase     (    _lowercase    ,				_lowercase    ,				unittest.TestCase		):
       a    				=	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
       a    				=	(
           {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
           if is_tf_available()
           else {}
       )
       a    				=	False
       a    				=	False
       a    				=	False
       a    				=	False
       a    				=	False




       def 		lowerCamelCase_    (							self:    Dict					):
              lowerCamelCase__ :     Dict	  =	TFCvtModelTester(self					)
              lowerCamelCase__ :     List[Any]	  =	TFCvtConfigTester(self      ,							config_class=UpperCamelCase__      ,							has_text_modality=UpperCamelCase__      ,							hidden_size=37					)




       def 		lowerCamelCase_    (							self:    List[str]					):
              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:    str					):
              pass




       @unittest.skip(reason="""Cvt does not use inputs_embeds"""					)
       def 		lowerCamelCase_    (							self:    Union[str, Any]					):
              pass




       @unittest.skip(reason="""Cvt does not support input and output embeddings"""					)
       def 		lowerCamelCase_    (							self:    int					):
              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:    Optional[int]					):
              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:    str					):
              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:    Tuple					):
              lowerCamelCase__ :     Dict	  =	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 		lowerCamelCase_    (							self:    int					):
              lowerCamelCase__ :     Optional[Any]	  =	self.model_tester.prepare_config_and_inputs_for_common()

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

                     lowerCamelCase__ :     Tuple	  =	["""pixel_values"""]
                     self.assertListEqual(arg_names[:1]      ,							UpperCamelCase__					)




       def 		lowerCamelCase_    (							self:    Tuple					):
              def check_hidden_states_output(UpperCamelCase__:    int      ,							UpperCamelCase__:    Optional[Any]      ,							UpperCamelCase__:    Optional[int]					):
                     lowerCamelCase__ :     int	  =	model_class(UpperCamelCase__					)

                     lowerCamelCase__ :     Dict	  =	model(**self._prepare_for_class(UpperCamelCase__      ,							UpperCamelCase__					)					)
                     lowerCamelCase__ :     Any	  =	outputs.hidden_states

                     lowerCamelCase__ :     Union[str, Any]	  =	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,
                         ]      ,							)

              lowerCamelCase__ :     Union[str, Any]	  =	self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowerCamelCase__ :     Any	  =	True
                     check_hidden_states_output(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)

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

                     check_hidden_states_output(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)




       def 		lowerCamelCase_    (							self:    List[Any]					):
              lowerCamelCase__ :     Union[str, Any]	  =	self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*UpperCamelCase__					)




       def 		lowerCamelCase_    (							self:    Any					):
              lowerCamelCase__ :     Tuple	  =	self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__					)




       @slow
       def 		lowerCamelCase_    (							self:    int					):
              for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowerCamelCase__ :     List[str]	  =	TFCvtModel.from_pretrained(UpperCamelCase__					)
                     self.assertIsNotNone(UpperCamelCase__					)





def 			SCREAMING_SNAKE_CASE_	()				->	List[Any]:
       lowerCamelCase__ :     str	  =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
       return image



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




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




       @slow
       def 		lowerCamelCase_    (							self:    Tuple					):
              lowerCamelCase__ :     Tuple	  =	TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

              lowerCamelCase__ :     Tuple	  =	self.default_image_processor
              lowerCamelCase__ :     int	  =	prepare_img()
              lowerCamelCase__ :     Any	  =	image_processor(images=UpperCamelCase__      ,							return_tensors="""tf"""					)

              # forward pass
              lowerCamelCase__ :     Tuple	  =	model(**UpperCamelCase__					)

              # verify the logits
              lowerCamelCase__ :     List[str]	  =	tf.TensorShape((1, 1_000)					)
              self.assertEqual(outputs.logits.shape      ,							UpperCamelCase__					)

              lowerCamelCase__ :     Optional[int]	  =	tf.constant([0.9_285, 0.9_015, -0.3_150]					)
              self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,							UpperCamelCase__      ,							atol=1e-4					)					)









'''simple docstring'''







import numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

_A     :      int   					=imread(r'''digital_image_processing/image_data/lena_small.jpg''')
_A     :      Optional[Any]   					=cvtColor(img, COLOR_BGR2GRAY)





def 			SCREAMING_SNAKE_CASE_	()				->	Any:
							lowerCamelCase__ :     int	  =	cn.convert_to_negative(UpperCamelCase				)
							# assert negative_img array for at least one True
							assert negative_img.any()





def 			SCREAMING_SNAKE_CASE_	()				->	Optional[int]:
							with Image.open("""digital_image_processing/image_data/lena_small.jpg"""				) as img:
														# Work around assertion for response
														assert str(cc.change_contrast(UpperCamelCase    ,      110				)				).startswith(
														    """<PIL.Image.Image image mode=RGB size=100x100 at"""				)





def 			SCREAMING_SNAKE_CASE_	()				->	Union[str, Any]:
							lowerCamelCase__ :     Optional[int]	  =	canny.gen_gaussian_kernel(9    ,      sigma=1.4				)
							# Assert ambiguous array
							assert resp.all()





def 			SCREAMING_SNAKE_CASE_	()				->	str:
							lowerCamelCase__ :     int	  =	imread("""digital_image_processing/image_data/lena_small.jpg"""    ,      0				)
							# assert ambiguous array for all == True
							assert canny_img.all()
							lowerCamelCase__ :     Union[str, Any]	  =	canny.canny(UpperCamelCase				)
							# assert canny array for at least one True
							assert canny_array.any()





def 			SCREAMING_SNAKE_CASE_	()				->	str:
							assert gg.gaussian_filter(UpperCamelCase    ,      5    ,      sigma=0.9				).all()





def 			SCREAMING_SNAKE_CASE_	()				->	int:
							# laplace diagonals
							lowerCamelCase__ :     int	  =	array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]				)
							lowerCamelCase__ :     int	  =	conv.img_convolve(UpperCamelCase    ,      UpperCamelCase				).astype(UpperCamelCase				)
							assert res.any()





def 			SCREAMING_SNAKE_CASE_	()				->	Any:
							assert med.median_filter(UpperCamelCase    ,      3				).any()





def 			SCREAMING_SNAKE_CASE_	()				->	Any:
							lowerCamelCase__  ,		lowerCamelCase__ :     Optional[Any]	  =	sob.sobel_filter(UpperCamelCase				)
							assert grad.any() and theta.any()





def 			SCREAMING_SNAKE_CASE_	()				->	Tuple:
							lowerCamelCase__ :     Union[str, Any]	  =	sp.make_sepia(UpperCamelCase    ,      20				)
							assert sepia.all()





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg"				)				->	Optional[Any]:
							lowerCamelCase__ :     Union[str, Any]	  =	bs.Burkes(imread(UpperCamelCase    ,      1				)    ,      120				)
							burkes.process()
							assert burkes.output_img.any()





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg"    ,      )				->	Optional[Any]:
							lowerCamelCase__ :     int	  =	rs.NearestNeighbour(imread(UpperCamelCase    ,      1				)    ,      400    ,      200				)
							nn.process()
							assert nn.output.any()





def 			SCREAMING_SNAKE_CASE_	()				->	Optional[int]:
							lowerCamelCase__ :     Union[str, Any]	  =	"""digital_image_processing/image_data/lena.jpg"""

							# Reading the image and converting it to grayscale.
							lowerCamelCase__ :     Tuple	  =	imread(UpperCamelCase    ,      0				)

							# Test for get_neighbors_pixel function() return not None
							lowerCamelCase__ :     int	  =	0
							lowerCamelCase__ :     Dict	  =	0
							lowerCamelCase__ :     Optional[Any]	  =	image[x_coordinate][y_coordinate]

							lowerCamelCase__ :     str	  =	lbp.get_neighbors_pixel(
							    UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase				)

							assert neighbors_pixels is not None

							# Test for local_binary_pattern function()
							# Create a numpy array as the same height and width of read image
							lowerCamelCase__ :     List[str]	  =	np.zeros((image.shape[0], image.shape[1])				)

							# Iterating through the image and calculating the local binary pattern value
							# for each pixel.
							for i in range(0    ,      image.shape[0]				):
														for j in range(0    ,      image.shape[1]				):
																					lowerCamelCase__ :     List[str]	  =	lbp.local_binary_value(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase				)

							assert lbp_image.any()

