





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor







class       __A							:




      """simple docstring"""







      def __init__(		self   ,				a__   ,				a__=3   ,				a__=32   ,				a__=3   ,				a__=10   ,				a__=[10, 20, 30, 40]   ,				a__=[1, 1, 2, 1]   ,				a__=True   ,				a__=True   ,				a__="relu"   ,				a__=3   ,				a__=None   ,				):



             """simple docstring"""





             _lowerCamelCase				:  Union[str, Any]						=		parent
             _lowerCamelCase				:  Dict						=		batch_size
             _lowerCamelCase				:  Dict						=		image_size
             _lowerCamelCase				:  Optional[Any]						=		num_channels
             _lowerCamelCase				:  Tuple						=		embeddings_size
             _lowerCamelCase				:  Optional[int]						=		hidden_sizes
             _lowerCamelCase				:  Tuple						=		depths
             _lowerCamelCase				:  Optional[int]						=		is_training
             _lowerCamelCase				:  Dict						=		use_labels
             _lowerCamelCase				:  Tuple						=		hidden_act
             _lowerCamelCase				:  Tuple						=		num_labels
             _lowerCamelCase				:  Optional[int]						=		scope
             _lowerCamelCase				:  Dict						=		len(a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

             _lowerCamelCase				:  int						=		None
             if self.use_labels:
                    _lowerCamelCase				:  int						=		ids_tensor([self.batch_size]   ,				self.num_labels)

             _lowerCamelCase				:  str						=		self.get_config()
             return config, pixel_values, labels


      def 					__snake_case      (		self):



             """simple docstring"""





             return RegNetConfig(
                 num_channels=self.num_channels   ,				embeddings_size=self.embeddings_size   ,				hidden_sizes=self.hidden_sizes   ,				depths=self.depths   ,				hidden_act=self.hidden_act   ,				num_labels=self.num_labels   ,				)


      def 					__snake_case      (		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		TFRegNetModel(config=a__)
             _lowerCamelCase				:  Union[str, Any]						=		model(a__   ,				training=a__)
             # expected last hidden states: B, C, H // 32, W // 32
             self.parent.assertEqual(
                 result.last_hidden_state.shape   ,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)   ,				)


      def 					__snake_case      (		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		self.num_labels
             _lowerCamelCase				:  Union[str, Any]						=		TFRegNetForImageClassification(a__)
             _lowerCamelCase				:  int						=		model(a__   ,				labels=a__   ,				training=a__)
             self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels))



      def 					__snake_case      (		self):



             """simple docstring"""





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







@require_tf
class       __A							(   lowerCamelCase__			,lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      UpperCAmelCase__							=   (
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      UpperCAmelCase__							=   False
      UpperCAmelCase__							=   False
      UpperCAmelCase__							=   False
      UpperCAmelCase__							=   False
      UpperCAmelCase__							=   False


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		TFRegNetModelTester(self)
             _lowerCamelCase				:  str						=		ConfigTester(self   ,				config_class=a__   ,				has_text_modality=a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             return


      @unittest.skip(reason='''RegNet does not use inputs_embeds''')
      def 					__snake_case      (		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.'''   ,				)
      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             super().test_keras_fit()


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



             """simple docstring"""





             pass


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  Optional[int]						=		self.model_tester.prepare_config_and_inputs_for_common()

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

                    _lowerCamelCase				:  Optional[int]						=		['''pixel_values''']
                    self.assertListEqual(arg_names[:1]   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             def check_hidden_states_output(a__   ,				a__   ,				a__):
                    _lowerCamelCase				:  Optional[Any]						=		model_class(a__)
                    _lowerCamelCase				:  str						=		model(**self._prepare_for_class(a__   ,				a__)   ,				training=a__)

                    _lowerCamelCase				:  str						=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                    _lowerCamelCase				:  List[str]						=		self.model_tester.num_stages
                    self.assertEqual(len(a__)   ,				expected_num_stages + 1)

                    # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
                    self.assertListEqual(
                        list(hidden_states[0].shape[-2:])   ,				[self.model_tester.image_size // 2, self.model_tester.image_size // 2]   ,				)

             _lowerCamelCase,	_lowerCamelCase				:  Tuple						=		self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase				:  int						=		['''basic''', '''bottleneck''']
             for model_class in self.all_model_classes:
                    for layer_type in layers_type:
                           _lowerCamelCase				:  Tuple						=		layer_type
                           _lowerCamelCase				:  str						=		True
                           check_hidden_states_output(a__   ,				a__   ,				a__)

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

                           check_hidden_states_output(a__   ,				a__   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  str						=		self.model_tester.prepare_config_and_inputs_for_common()

             def check_equivalence(a__   ,				a__   ,				a__   ,				a__={}):
                    _lowerCamelCase				:  str						=		model(a__   ,				return_dict=a__   ,				**a__)
                    _lowerCamelCase				:  Union[str, Any]						=		model(a__   ,				return_dict=a__   ,				**a__).to_tuple()

                    def recursive_check(a__   ,				a__):
                           if isinstance(a__   ,				(List, Tuple)):
                                  for tuple_iterable_value, dict_iterable_value in zip(a__   ,				a__):
                                         recursive_check(a__   ,				a__)
                           elif tuple_object is None:
                                  return
                           else:
                                  self.assertTrue(
                                      all(tf.equal(a__   ,				a__))   ,				msg=(
                                          '''Tuple and dict output are not equal. Difference:'''
                                          F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"""
                                      )   ,				)

                           recursive_check(a__   ,				a__)

             for model_class in self.all_model_classes:
                    _lowerCamelCase				:  Tuple						=		model_class(a__)

                    _lowerCamelCase				:  Dict						=		self._prepare_for_class(a__   ,				a__)
                    _lowerCamelCase				:  Tuple						=		self._prepare_for_class(a__   ,				a__)
                    check_equivalence(a__   ,				a__   ,				a__)

                    _lowerCamelCase				:  Optional[int]						=		self._prepare_for_class(a__   ,				a__   ,				return_labels=a__)
                    _lowerCamelCase				:  int						=		self._prepare_for_class(a__   ,				a__   ,				return_labels=a__)
                    check_equivalence(a__   ,				a__   ,				a__)

                    _lowerCamelCase				:  Tuple						=		self._prepare_for_class(a__   ,				a__)
                    _lowerCamelCase				:  List[Any]						=		self._prepare_for_class(a__   ,				a__)
                    check_equivalence(a__   ,				a__   ,				a__   ,				{'''output_hidden_states''': True})

                    _lowerCamelCase				:  Union[str, Any]						=		self._prepare_for_class(a__   ,				a__   ,				return_labels=a__)
                    _lowerCamelCase				:  Dict						=		self._prepare_for_class(a__   ,				a__   ,				return_labels=a__)
                    check_equivalence(a__   ,				a__   ,				a__   ,				{'''output_hidden_states''': True})


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*a__)



      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase				:  Any						=		TFRegNetModel.from_pretrained(a__)
                    self.assertIsNotNone(a__)




def  __UpperCAmelCase(   ):
       _lowerCamelCase				:  List[Any]						=		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):



             """simple docstring"""





             return (
                 AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
                 if is_vision_available()
                 else None
             )



      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Union[str, Any]						=		TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

             _lowerCamelCase				:  Tuple						=		self.default_image_processor
             _lowerCamelCase				:  str						=		prepare_img()
             _lowerCamelCase				:  Union[str, Any]						=		image_processor(images=a__   ,				return_tensors='''tf''')

             # forward pass
             _lowerCamelCase				:  Optional[Any]						=		model(**a__   ,				training=a__)

             # verify the logits
             _lowerCamelCase				:  Tuple						=		tf.TensorShape((1, 1000))
             self.assertEqual(outputs.logits.shape   ,				a__)

             _lowerCamelCase				:  int						=		tf.constant([-0.4180, -1.5051, -3.4836])

             tf.debugging.assert_near(outputs.logits[0, :3]   ,				a__   ,				atol=1e-4)








def  __UpperCAmelCase(   lowercase_			,     lowercase_   ):
       # "extended trapezoidal rule"
       # int(f) = dx/2 * (f1 + 2f2 + ... + fn)
       _lowerCamelCase				:  int						=		(boundary[1] - boundary[0]) / steps
       _lowerCamelCase				:  Any						=		boundary[0]
       _lowerCamelCase				:  Tuple						=		boundary[1]
       _lowerCamelCase				:  Optional[Any]						=		make_points(lowercase_			,     lowercase_			,     lowercase_   )
       _lowerCamelCase				:  Dict						=		0.0
       y += (h / 2.0) * f(lowercase_   )
       for i in x_i:
              # print(i)
              y += h * f(lowercase_   )
       y += (h / 2.0) * f(lowercase_   )
       return y




def  __UpperCAmelCase(   lowercase_			,     lowercase_			,     lowercase_   ):
       _lowerCamelCase				:  Dict						=		a + h
       while x < (b - h):
              yield x
              _lowerCamelCase				:  Dict						=		x + h




def  __UpperCAmelCase(   lowercase_   ):  # enter your function here
       _lowerCamelCase				:  List[str]						=		(x - 0) * (x - 0)
       return y




def  __UpperCAmelCase(   ):
       _lowerCamelCase				:  List[Any]						=		0.0  # Lower bound of integration
       _lowerCamelCase				:  Union[str, Any]						=		1.0  # Upper bound of integration
       _lowerCamelCase				:  Dict						=		1_0.0  # define number of steps or resolution
       _lowerCamelCase				:  Optional[int]						=		[a, b]  # define boundary of integration
       _lowerCamelCase				:  str						=		method_a(lowercase_			,     lowercase_   )
       print(F"""y = {y}"""   )


if __name__ == "__main__":
       main()

