


'''simple docstring'''







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 	UpperCamelCase__					:



     """simple docstring"""






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

            '''simple docstring'''

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







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Dict   			=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

            _lowerCAmelCase    :							Optional[int]   			=       None
            if self.use_labels:
                   _lowerCAmelCase    :							List[Any]   			=       ids_tensor([self.batch_size]      ,	self.num_labels   )

            _lowerCAmelCase    :							int   			=       self.get_config()
            return config, pixel_values, labels







     def a	( 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 a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       TFRegNetModel(config=snake_case__   )
            _lowerCAmelCase    :							List[Any]   			=       model(snake_case__      ,	training=snake_case__   )
            # 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 a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[Any]   			=       self.num_labels
            _lowerCAmelCase    :							int   			=       TFRegNetForImageClassification(snake_case__   )
            _lowerCAmelCase    :							int   			=       model(snake_case__      ,	labels=snake_case__      ,	training=snake_case__   )
            self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.num_labels)   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       self.prepare_config_and_inputs()
            _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase    :							List[Any]   			=       config_and_inputs
            _lowerCAmelCase    :							Optional[int]   			=       {'pixel_values': pixel_values}
            return config, inputs_dict
@require_tf
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_    ,					SCREAMING_SNAKE_CASE_    ,					unittest.TestCase	):



     """simple docstring"""






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

     __magic_name__    			=    False
     __magic_name__    			=    False
     __magic_name__    			=    False
     __magic_name__    			=    False
     __magic_name__    			=    False







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       TFRegNetModelTester(self   )
            _lowerCAmelCase    :							Tuple   			=       ConfigTester(self      ,	config_class=snake_case__      ,	has_text_modality=snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            return







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

            '''simple docstring'''

            super().test_keras_fit()







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

            '''simple docstring'''

            pass







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							Dict   			=       self.model_tester.prepare_config_and_inputs_for_common()

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

                   _lowerCAmelCase    :							Tuple   			=       ['pixel_values']
                   self.assertListEqual(arg_names[:1]      ,	snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							str   			=       self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            def check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   ):
                   _lowerCAmelCase    :							List[str]   			=       model_class(snake_case__   )
                   _lowerCAmelCase    :							str   			=       model(**self._prepare_for_class(snake_case__      ,	snake_case__   )      ,	training=snake_case__   )

                   _lowerCAmelCase    :							Tuple   			=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                   _lowerCAmelCase    :							Tuple   			=       self.model_tester.num_stages
                   self.assertEqual(len(snake_case__   )      ,	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    :							Optional[int]   			=       self.model_tester.prepare_config_and_inputs_for_common()
            _lowerCAmelCase    :							Any   			=       ['basic', 'bottleneck']
            for model_class in self.all_model_classes:
                   for layer_type in layers_type:
                          _lowerCAmelCase    :							Any   			=       layer_type
                          _lowerCAmelCase    :							Dict   			=       True
                          check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   )

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

                          check_hidden_states_output(snake_case__      ,	snake_case__      ,	snake_case__   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase			,     _lowerCAmelCase    :							Dict   			=       self.model_tester.prepare_config_and_inputs_for_common()

            def check_equivalence(snake_case__      ,	snake_case__      ,	snake_case__      ,	snake_case__={}   ):
                   _lowerCAmelCase    :							List[Any]   			=       model(snake_case__      ,	return_dict=snake_case__      ,	**snake_case__   )
                   _lowerCAmelCase    :							Tuple   			=       model(snake_case__      ,	return_dict=snake_case__      ,	**snake_case__   ).to_tuple()

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

                          recursive_check(snake_case__      ,	snake_case__   )

            for model_class in self.all_model_classes:
                   _lowerCAmelCase    :							Optional[int]   			=       model_class(snake_case__   )

                   _lowerCAmelCase    :							str   			=       self._prepare_for_class(snake_case__      ,	snake_case__   )
                   _lowerCAmelCase    :							Optional[int]   			=       self._prepare_for_class(snake_case__      ,	snake_case__   )
                   check_equivalence(snake_case__      ,	snake_case__      ,	snake_case__   )

                   _lowerCAmelCase    :							Tuple   			=       self._prepare_for_class(snake_case__      ,	snake_case__      ,	return_labels=snake_case__   )
                   _lowerCAmelCase    :							Optional[int]   			=       self._prepare_for_class(snake_case__      ,	snake_case__      ,	return_labels=snake_case__   )
                   check_equivalence(snake_case__      ,	snake_case__      ,	snake_case__   )

                   _lowerCAmelCase    :							Union[str, Any]   			=       self._prepare_for_class(snake_case__      ,	snake_case__   )
                   _lowerCAmelCase    :							List[Any]   			=       self._prepare_for_class(snake_case__      ,	snake_case__   )
                   check_equivalence(snake_case__      ,	snake_case__      ,	snake_case__      ,	{'output_hidden_states': True}   )

                   _lowerCAmelCase    :							List[str]   			=       self._prepare_for_class(snake_case__      ,	snake_case__      ,	return_labels=snake_case__   )
                   _lowerCAmelCase    :							Any   			=       self._prepare_for_class(snake_case__      ,	snake_case__      ,	return_labels=snake_case__   )
                   check_equivalence(snake_case__      ,	snake_case__      ,	snake_case__      ,	{'output_hidden_states': True}   )







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*snake_case__   )







     @slow
     def a	( self   ):

            '''simple docstring'''

            for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCAmelCase    :							List[Any]   			=       TFRegNetModel.from_pretrained(snake_case__   )
                   self.assertIsNotNone(snake_case__   )






def 			lowercase				():







       """simple docstring"""







       _lowerCAmelCase    :							Union[str, Any]   			=       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
       return image
@require_tf
@require_vision
class 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     @cached_property
     def a	( self   ):

            '''simple docstring'''

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







     @slow
     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

            _lowerCAmelCase    :							List[str]   			=       self.default_image_processor
            _lowerCAmelCase    :							Tuple   			=       prepare_img()
            _lowerCAmelCase    :							Any   			=       image_processor(images=snake_case__      ,	return_tensors='tf'   )

            # forward pass
            _lowerCAmelCase    :							List[Any]   			=       model(**snake_case__      ,	training=snake_case__   )

            # verify the logits
            _lowerCAmelCase    :							str   			=       tf.TensorShape((1, 1000)   )
            self.assertEqual(outputs.logits.shape      ,	snake_case__   )

            _lowerCAmelCase    :							Dict   			=       tf.constant([-0.4180, -1.5051, -3.4836]   )

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





'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


lowerCAmelCase    :     int					=						{
    """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
    """processing_trocr""": ["""TrOCRProcessor"""],
}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCAmelCase    :     Optional[Any]					=						[
           """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """TrOCRForCausalLM""",
           """TrOCRPreTrainedModel""",
       ]


if TYPE_CHECKING:
       from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
       from .processing_trocr import TrOCRProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
       import sys

       lowerCAmelCase    :     Any					=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

