

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 						UpperCamelCase_		(      self				:    List[str]		)   ->					Optional[Any]:
        _snake_case						=							self.config_class(**self.inputs_dict		)
        self.parent.assertTrue(hasattr(A__      , '''embed_dim'''		)		)
        self.parent.assertTrue(hasattr(A__      , '''num_heads'''		)		)



class   lowercase_   :



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



      def 						UpperCamelCase_		(      self				:    str		)   ->					Union[str, Any]:
        _snake_case						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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



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







      def 						UpperCamelCase_		(      self				:    Any		)   ->					str:
        _snake_case						=							self.prepare_config_and_inputs()
        _snake_case,					_snake_case,					_snake_case						=							config_and_inputs
        _snake_case						=							{'''pixel_values''': pixel_values}
        return config, inputs_dict



@require_tf
class   lowercase_   (  __lowercase       ,							__lowercase       ,							unittest.TestCase					):
      UpperCamelCase_      :		List[str]										=    (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
      UpperCamelCase_      :		int										=    (
          {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
          if is_tf_available()
          else {}
      )
      UpperCamelCase_      :		List[Any]										=    False
      UpperCamelCase_      :		List[str]										=    False
      UpperCamelCase_      :		Tuple										=    False
      UpperCamelCase_      :		Any										=    False
      UpperCamelCase_      :		Dict										=    False



      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					Optional[int]:
        _snake_case						=							TFCvtModelTester(self		)
        _snake_case						=							TFCvtConfigTester(self      , config_class=A__      , has_text_modality=A__      , hidden_size=37		)



      def 						UpperCamelCase_		(      self				:    int		)   ->					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 						UpperCamelCase_		(      self				:    List[str]		)   ->					Optional[Any]:
        pass



      @unittest.skip(reason='''Cvt does not use inputs_embeds'''		)
      def 						UpperCamelCase_		(      self				:    Tuple		)   ->					Optional[int]:
        pass



      @unittest.skip(reason='''Cvt does not support input and output embeddings'''		)
      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					Optional[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 						UpperCamelCase_		(      self				:    Any		)   ->					List[str]:
        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				:    str		)   ->					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 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Tuple:
        _snake_case						=							tf.keras.mixed_precision.Policy('''mixed_float16'''		)
        tf.keras.mixed_precision.set_global_policy(A__		)
        super().test_keras_fit()
        tf.keras.mixed_precision.set_global_policy('''float32'''		)



      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					int:
        _snake_case,					_snake_case						=							self.model_tester.prepare_config_and_inputs_for_common()

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

          _snake_case						=							['''pixel_values''']
          self.assertListEqual(arg_names[:1]      , A__		)



      def 						UpperCamelCase_		(      self				:    Optional[int]		)   ->					Union[str, Any]:
        def check_hidden_states_output(A__				:    Union[str, Any]      , A__				:    List[Any]      , A__				:    Optional[Any]		):
          _snake_case						=							model_class(A__		)

          _snake_case						=							model(**self._prepare_for_class(A__      , A__		)		)
          _snake_case						=							outputs.hidden_states

          _snake_case						=							len(self.model_tester.depth		)
          self.assertEqual(len(A__		)      , A__		)

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

        _snake_case,					_snake_case						=							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          _snake_case						=							True
          check_hidden_states_output(A__      , A__      , A__		)

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

          check_hidden_states_output(A__      , A__      , A__		)



      def 						UpperCamelCase_		(      self				:    Optional[int]		)   ->					Any:
        _snake_case						=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A__		)



      def 						UpperCamelCase_		(      self				:    int		)   ->					List[str]:
        _snake_case						=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*A__		)







      @slow
      def 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Optional[int]:
        for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _snake_case						=							TFCvtModel.from_pretrained(A__		)
          self.assertIsNotNone(A__		)



def 				snake_case_()							->     List[str]:



  """simple docstring"""






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



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



      @cached_property
      def 						UpperCamelCase_		(      self				:    Tuple		)   ->					Tuple:
        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)







      @slow
      def 						UpperCamelCase_		(      self				:    Dict		)   ->					Optional[Any]:
        _snake_case						=							TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

        _snake_case						=							self.default_image_processor
        _snake_case						=							prepare_img()
        _snake_case						=							image_processor(images=A__      , return_tensors='''tf'''		)

        # forward pass
        _snake_case						=							model(**A__		)

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

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




import warnings

from ...utils import logging
from .image_processing_deformable_detr import DeformableDetrImageProcessor


__A      		=     logging.get_logger(__name__)



class   lowercase_   (  __lowercase					):



      def __init__(      self				:    Optional[Any]      , *A__				:    List[Any]      , **A__				:    int		)   ->					None:
        warnings.warn(
            '''The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
            ''' Please use DeformableDetrImageProcessor instead.'''      , A__      , )
        super().__init__(*A__      , **A__		)

