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     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.config_class(**self.inputs_dict)
        self.parent.assertTrue(hasattr(lowercase__      ,   'embed_dim'))
        self.parent.assertTrue(hasattr(lowercase__      ,   'num_heads'))






class     a_			:






 '''simple docstring'''






 def __init__(      self :  Any      ,   lowercase__ :  List[Any]      ,   lowercase__ :  List[Any]=13      ,   lowercase__ :  str=64      ,   lowercase__ :  Optional[int]=3      ,   lowercase__ :  int=[16, 48, 96]      ,   lowercase__ :  Optional[int]=[1, 3, 6]      ,   lowercase__ :  Optional[Any]=[1, 2, 10]      ,   lowercase__ :  List[Any]=[7, 3, 3]      ,   lowercase__ :  Any=[4, 2, 2]      ,   lowercase__ :  Tuple=[2, 1, 1]      ,   lowercase__ :  Optional[int]=[2, 2, 2]      ,   lowercase__ :  Optional[int]=[False, False, True]      ,   lowercase__ :  Tuple=[0.0, 0.0, 0.0]      ,   lowercase__ :  List[str]=0.02      ,   lowercase__ :  int=1e-12      ,   lowercase__ :  Dict=True      ,   lowercase__ :  List[Any]=True      ,   lowercase__ :  List[Any]=2      ,   ):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



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

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

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




 def 		__snake_case						(      self :  List[str]):







        '''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 		__snake_case						(      self :  List[str]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  int      ,   lowercase__ :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtModel(config=lowercase__)
        lowerCAmelCase__					     = model(lowercase__      ,   training=lowercase__)
        lowerCAmelCase__					     = (self.image_size, self.image_size)
        lowerCAmelCase__     , lowerCAmelCase__					     = image_size[0], image_size[1]
        for i in range(len(self.depth)):
               lowerCAmelCase__					     = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
               lowerCAmelCase__					     = 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 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  str      ,   lowercase__ :  List[Any]):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



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






@require_tf
class     a_			(						SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE	,					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 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtModelTester(self)
        lowerCAmelCase__					     = TFCvtConfigTester(self      ,   config_class=lowercase__      ,   has_text_modality=lowercase__      ,   hidden_size=37)




 def 		__snake_case						(      self :  Optional[Any]):







        '''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 		__snake_case						(      self :  Any):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Cvt does not use inputs_embeds')
 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Cvt does not support input and output embeddings')
 def 		__snake_case						(      self :  int):







        '''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 		__snake_case						(      self :  Dict):







        '''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 		__snake_case						(      self :  Optional[Any]):







        '''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 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = 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 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

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

               lowerCAmelCase__					     = ['pixel_values']
               self.assertListEqual(arg_names[:1]      ,   lowercase__)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        def check_hidden_states_output(lowercase__ :  str      ,   lowercase__ :  str      ,   lowercase__ :  Tuple):
               lowerCAmelCase__					     = model_class(lowercase__)

               lowerCAmelCase__					     = model(**self._prepare_for_class(lowercase__      ,   lowercase__))
               lowerCAmelCase__					     = outputs.hidden_states

               lowerCAmelCase__					     = 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__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = True
               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)

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

               check_hidden_states_output(lowercase__      ,   lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__)




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase__)




 @slow
 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



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






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = 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 :  Optional[int]):







        '''simple docstring'''



        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])




 @slow
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(images=lowercase__      ,   return_tensors='tf')

        # forward pass
        lowerCAmelCase__					     = model(**lowercase__)

        # verify the logits
        lowerCAmelCase__					     = tf.TensorShape((1, 1_000))
        self.assertEqual(outputs.logits.shape      ,   lowercase__)

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

lowerCAmelCase__     						=			'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       # Make sure the supplied data is a bytes-like object
       if not isinstance(lowerCAmelCase__     ,  lowerCAmelCase__     ):
              lowerCAmelCase__					     = F"""a bytes-like object is required, not '{data.__class__.__name__}'"""
              raise TypeError(lowerCAmelCase__     )

       lowerCAmelCase__					     = ''.join(bin(lowerCAmelCase__     )[2:].zfill(8     ) for byte in data     )

       lowerCAmelCase__					     = len(lowerCAmelCase__     ) % 6 != 0

       if padding_needed:
              # The padding that will be added later
              lowerCAmelCase__					     = b'=' * ((6 - len(lowerCAmelCase__     ) % 6) // 2)

              # Append binary_stream with arbitrary binary digits (0's by default) to make its
              # length a multiple of 6.
              binary_stream += "0" * (6 - len(lowerCAmelCase__     ) % 6)
       else:
              lowerCAmelCase__					     = b''

       # Encode every 6 binary digits to their corresponding Base64 character
       return (
           "".join(
               B64_CHARSET[int(binary_stream[index : index + 6]     ,  2     )]
               for index in range(0     ,  len(lowerCAmelCase__     )     ,  6     )     ).encode()
           + padding
       )






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       # Make sure encoded_data is either a string or a bytes-like object
       if not isinstance(lowerCAmelCase__     ,  lowerCAmelCase__     ) and not isinstance(lowerCAmelCase__     ,  lowerCAmelCase__     ):
              lowerCAmelCase__					     = (
                  'argument should be a bytes-like object or ASCII string, '
                  F"""not '{encoded_data.__class__.__name__}'"""
              )
              raise TypeError(lowerCAmelCase__     )

       # In case encoded_data is a bytes-like object, make sure it contains only
       # ASCII characters so we convert it to a string object
       if isinstance(lowerCAmelCase__     ,  lowerCAmelCase__     ):
              try:
                     lowerCAmelCase__					     = encoded_data.decode('utf-8'     )
              except UnicodeDecodeError:
                     raise ValueError('base64 encoded data should only contain ASCII characters'     )

       lowerCAmelCase__					     = encoded_data.count('='     )

       # Check if the encoded string contains non base64 characters
       if padding:
              assert all(
                  char in B64_CHARSET for char in encoded_data[:-padding]     ), "Invalid base64 character(s) found."
       else:
              assert all(
                  char in B64_CHARSET for char in encoded_data     ), "Invalid base64 character(s) found."

       # Check the padding
       assert len(lowerCAmelCase__     ) % 4 == 0 and padding < 3, "Incorrect padding"

       if padding:
              # Remove padding if there is one
              lowerCAmelCase__					     = encoded_data[:-padding]

              lowerCAmelCase__					     = ''.join(
                  bin(B64_CHARSET.index(lowerCAmelCase__     )     )[2:].zfill(6     ) for char in encoded_data     )[: -padding * 2]
       else:
              lowerCAmelCase__					     = ''.join(
                  bin(B64_CHARSET.index(lowerCAmelCase__     )     )[2:].zfill(6     ) for char in encoded_data     )

       lowerCAmelCase__					     = [
           int(binary_stream[index : index + 8]     ,  2     )
           for index in range(0     ,  len(lowerCAmelCase__     )     ,  8     )
       ]

       return bytes(lowerCAmelCase__     )


if __name__ == "__main__":
    import doctest

    doctest.testmod()
