





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      __SCREAMING_SNAKE_CASE    (						UpperCamelCase__   ):







  '''simple docstring'''


  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				int:
        _UpperCamelCase      :	List[Any]						=       self.config_class(**self.inputs_dict	)
        self.parent.assertTrue(hasattr(_a					,   "embed_dim"	)	)
        self.parent.assertTrue(hasattr(_a					,   "num_heads"	)	)





class      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Dict:
        _UpperCamelCase      :	Optional[Any]						=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

        _UpperCamelCase      :	List[str]						=       self.get_config()
        return config, pixel_values, labels

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


  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Tuple:
        _UpperCamelCase      :	List[Any]						=       self.prepare_config_and_inputs()
        _UpperCamelCase      :	Tuple						=       config_and_inputs
        _UpperCamelCase      :	Any						=       {"""pixel_values""": pixel_values}
        return config, inputs_dict





@require_tf
class      __SCREAMING_SNAKE_CASE    (						UpperCamelCase__		,  UpperCamelCase__		,  unittest.TestCase   ):







  '''simple docstring'''


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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				List[Any]:
        _UpperCamelCase      :	Union[str, Any]						=       TFCvtModelTester(self	)
        _UpperCamelCase      :	str						=       TFCvtConfigTester(self					,   config_class=_a					,   has_text_modality=_a					,   hidden_size=37	)

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

  @unittest.skip(reason="Cvt does not use inputs_embeds"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				List[Any]:
        pass

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

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

              _UpperCamelCase      :	Dict						=       ["""pixel_values"""]
              self.assertListEqual(arg_names[:1]					,   _a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Optional[Any]:
        def check_hidden_states_output(__a   :       List[Any]					,   __a   :       Union[str, Any]					,   __a   :       Any	):
              _UpperCamelCase      :	Union[str, Any]						=       model_class(_a	)

              _UpperCamelCase      :	Union[str, Any]						=       model(**self._prepare_for_class(_a					,   _a	)	)
              _UpperCamelCase      :	Optional[int]						=       outputs.hidden_states

              _UpperCamelCase      :	Optional[Any]						=       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,
                  ]					,   )

        _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Any						=       True
              check_hidden_states_output(_a					,   _a					,   _a	)

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

              check_hidden_states_output(_a					,   _a					,   _a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Dict:
        _UpperCamelCase      :	str						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Tuple:
        _UpperCamelCase      :	str						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_a	)


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Any:
        for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Optional[Any]						=       TFCvtModel.from_pretrained(_a	)
              self.assertIsNotNone(_a	)





def 					lowercase__    (					)					->		Optional[int]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
      return image



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







  '''simple docstring'''


  @cached_property
  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				int:
        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				Tuple:
        _UpperCamelCase      :	Dict						=       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

        _UpperCamelCase      :	Optional[Any]						=       self.default_image_processor
        _UpperCamelCase      :	Tuple						=       prepare_img()
        _UpperCamelCase      :	Optional[Any]						=       image_processor(images=_a					,   return_tensors="tf"	)

        # forward pass
        _UpperCamelCase      :	int						=       model(**_a	)

        # verify the logits
        _UpperCamelCase      :	Dict						=       tf.TensorShape((1, 1000)	)
        self.assertEqual(outputs.logits.shape					,   _a	)

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







"""simple docstring"""


def 					lowercase__    (					lowercase_		,lowercase_			)					->		None:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       len(lowercase_			)
      print("The following activities are selected:"			)

      # The first activity is always selected
      _UpperCamelCase      :	List[Any]						=       0
      print(lowercase_		,end=","			)

      # Consider rest of the activities
      for j in range(lowercase_			):
            # If this activity has start time greater than
            # or equal to the finish time of previously
            # selected activity, then select it
            if start[j] >= finish[i]:
                  print(lowercase_		,end=","			)
                  _UpperCamelCase      :	Optional[Any]						=       j


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  lowerCamelCase__				  =   [1, 3, 0, 5, 8, 5]
  lowerCamelCase__				  =   [2, 4, 6, 7, 9, 9]
  print_max_activities(start, finish)
