




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

     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		,     )						->							Any:
           _A							:     Tuple			=						parent
           _A							:     int			=						batch_size
           _A							:     int			=						image_size
           _A							:     List[str]			=						num_channels
           _A							:     Optional[int]			=						embeddings_size
           _A							:     int			=						hidden_sizes
           _A							:     Any			=						depths
           _A							:     Dict			=						is_training
           _A							:     Union[str, Any]			=						use_labels
           _A							:     List[str]			=						hidden_act
           _A							:     Any			=						num_labels
           _A							:     int			=						scope
           _A							:     Any			=						len(_a				)

     def 					a__	(  self				)						->							Tuple:
           _A							:     Union[str, Any]			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

           _A							:     Optional[Any]			=						None
           if self.use_labels:
                 _A							:     Tuple			=						ids_tensor([self.batch_size]		,     self.num_labels				)

           _A							:     Union[str, Any]			=						self.get_config()
           return config, pixel_values, labels

     def 					a__	(  self				)						->							List[str]:
           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		,     _a		,     _a		,     _a				)						->							str:
           _A							:     List[str]			=						TFRegNetModel(config=_a				)
           _A							:     Optional[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 					a__	(  self		,     _a		,     _a		,     _a				)						->							Dict:
           _A							:     List[str]			=						self.num_labels
           _A							:     str			=						TFRegNetForImageClassification(_a				)
           _A							:     List[Any]			=						model(_a		,     labels=_a		,     training=_a				)
           self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)				)



     def 					a__	(  self				)						->							Optional[Any]:
           _A							:     int			=						self.prepare_config_and_inputs()
           _A			,   _A			,   _A							:     List[str]			=						config_and_inputs
           _A							:     List[Any]			=						{"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_tf
class 						lowercase							(   UpperCamelCase__,UpperCamelCase__,unittest.TestCase		):
     _a							 =						(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
     _a							 =						(
         {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
         if is_tf_available()
         else {}
     )

     _a							 =						False
     _a							 =						False
     _a							 =						False
     _a							 =						False
     _a							 =						False

     def 					a__	(  self				)						->							Optional[Any]:
           _A							:     Optional[int]			=						TFRegNetModelTester(self				)
           _A							:     str			=						ConfigTester(self		,     config_class=_a		,     has_text_modality=_a				)

     def 					a__	(  self				)						->							Union[str, Any]:
           return

     @unittest.skip(reason="""RegNet does not use inputs_embeds"""				)
     def 					a__	(  self				)						->							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."""		,     )
     @slow
     def 					a__	(  self				)						->							List[Any]:
           super().test_keras_fit()

     @unittest.skip(reason="""RegNet does not support input and output embeddings"""				)
     def 					a__	(  self				)						->							Any:
           pass

     def 					a__	(  self				)						->							str:
           _A			,   _A							:     Union[str, Any]			=						self.model_tester.prepare_config_and_inputs_for_common()

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

                 _A							:     Union[str, Any]			=						["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]		,     _a				)

     def 					a__	(  self				)						->							Dict:
           _A							:     Any			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_a				)

     def 					a__	(  self				)						->							Dict:
           def check_hidden_states_output(_a		,     _a		,     _a				):
                 _A							:     int			=						model_class(_a				)
                 _A							:     Optional[Any]			=						model(**self._prepare_for_class(_a		,     _a				)		,     training=_a				)

                 _A							:     List[str]			=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

           _A			,   _A							:     Tuple			=						self.model_tester.prepare_config_and_inputs_for_common()
           _A							:     Dict			=						["""basic""", """bottleneck"""]
           for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                       _A							:     Tuple			=						layer_type
                       _A							:     str			=						True
                       check_hidden_states_output(_a		,     _a		,     _a				)

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

                       check_hidden_states_output(_a		,     _a		,     _a				)

     def 					a__	(  self				)						->							Dict:
           _A			,   _A							:     Dict			=						self.model_tester.prepare_config_and_inputs_for_common()

           def check_equivalence(_a		,     _a		,     _a		,     _a={}				):
                 _A							:     Dict			=						model(_a		,     return_dict=_a		,     **_a				)
                 _A							:     int			=						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:
                 _A							:     Dict			=						model_class(_a				)

                 _A							:     str			=						self._prepare_for_class(_a		,     _a				)
                 _A							:     Dict			=						self._prepare_for_class(_a		,     _a				)
                 check_equivalence(_a		,     _a		,     _a				)

                 _A							:     Optional[Any]			=						self._prepare_for_class(_a		,     _a		,     return_labels=_a				)
                 _A							:     List[str]			=						self._prepare_for_class(_a		,     _a		,     return_labels=_a				)
                 check_equivalence(_a		,     _a		,     _a				)

                 _A							:     Optional[Any]			=						self._prepare_for_class(_a		,     _a				)
                 _A							:     List[Any]			=						self._prepare_for_class(_a		,     _a				)
                 check_equivalence(_a		,     _a		,     _a		,     {"""output_hidden_states""": True}				)

                 _A							:     int			=						self._prepare_for_class(_a		,     _a		,     return_labels=_a				)
                 _A							:     List[Any]			=						self._prepare_for_class(_a		,     _a		,     return_labels=_a				)
                 check_equivalence(_a		,     _a		,     _a		,     {"""output_hidden_states""": True}				)

     def 					a__	(  self				)						->							List[Any]:
           _A							:     List[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_a				)



     @slow
     def 					a__	(  self				)						->							Optional[int]:
           for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _A							:     List[Any]			=						TFRegNetModel.from_pretrained(_a				)
                 self.assertIsNotNone(_a				)







def 				lowerCAmelCase_	(     ):
      _A							:     Any			=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
      return image







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

     @cached_property
     def 					a__	(  self				)						->							str:
           return (
               AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
               if is_vision_available()
               else None
           )



     @slow
     def 					a__	(  self				)						->							Dict:
           _A							:     Optional[int]			=						TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

           _A							:     str			=						self.default_image_processor
           _A							:     Dict			=						prepare_img()
           _A							:     int			=						image_processor(images=_a		,     return_tensors="""tf"""				)

           # forward pass
           _A							:     Any			=						model(**_a		,     training=_a				)

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

           _A							:     str			=						tf.constant([-0.4180, -1.5051, -3.4836]				)

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


"""simple docstring"""




import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
				from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
				from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
				from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__lowerCamelCase							 =     DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__lowerCamelCase							 =     "main"
# Default branch name
__lowerCamelCase							 =     "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
__lowerCamelCase							 =     "aaaaaaa"
# This commit does not exist, so we should 404.

__lowerCamelCase							 =     "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
__lowerCamelCase							 =     "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Welcome!' )
							yield
							print('Bye!' )






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Bonjour!' )
							yield
							print('Au revoir!' )
class 			UpperCamelCase__(	unittest.TestCase       ):





						def  snake_case__		(				self   )    -> List[str]:
													# If the spec is missing, importlib would not be able to import the module dynamically.
													assert transformers.__spec__ is not None
													assert importlib.util.find_spec('transformers'   ) is not None






class 			UpperCamelCase__(	unittest.TestCase       ):





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													with ContextManagers([]   ):
																				print('Transformers are awesome!'   )
													# The print statement adds a new line at the end of the output
													self.assertEqual(mock_stdout.getvalue()						,'Transformers are awesome!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> List[str]:
													with ContextManagers([context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Welcome!\nTransformers are awesome!\nBye!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Any:
													with ContextManagers([context_fr(), context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English and French welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n'   )





						@require_torch
						def  snake_case__		(				self   )    -> Union[str, Any]:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_tf
						def  snake_case__		(				self   )    -> str:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_flax
						def  snake_case__		(				self   )    -> List[Any]:
													# Flax models don't have labels
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )





