"""simple docstring"""


from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class 							a					:


    def __init__(       self						:	Any ,					__lowerCAmelCase						:	List[str] ,					__lowerCAmelCase						:	Dict=3 ,					__lowerCAmelCase						:	Dict=32 ,					__lowerCAmelCase						:	str=3 ,					__lowerCAmelCase						:	Optional[int]=10 ,					__lowerCAmelCase						:	int=[10, 20, 30, 40] ,					__lowerCAmelCase						:	Optional[int]=[1, 1, 2, 1] ,					__lowerCAmelCase						:	Tuple=True ,					__lowerCAmelCase						:	Tuple=True ,					__lowerCAmelCase						:	int="relu" ,					__lowerCAmelCase						:	Optional[int]=3 ,					__lowerCAmelCase						:	Optional[Any]=None ,					):
      _UpperCAmelCase    			=   parent
      _UpperCAmelCase    			=   batch_size
      _UpperCAmelCase    			=   image_size
      _UpperCAmelCase    			=   num_channels
      _UpperCAmelCase    			=   embeddings_size
      _UpperCAmelCase    			=   hidden_sizes
      _UpperCAmelCase    			=   depths
      _UpperCAmelCase    			=   is_training
      _UpperCAmelCase    			=   use_labels
      _UpperCAmelCase    			=   hidden_act
      _UpperCAmelCase    			=   num_labels
      _UpperCAmelCase    			=   scope
      _UpperCAmelCase    			=   len(lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      _UpperCAmelCase    			=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

      _UpperCAmelCase    			=   self.get_config()

      return config, pixel_values, labels


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      return ResNetConfig(
          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 ,					image_size=self.image_size ,					)


    def   lowerCAmelCase_	(       self						:	Dict ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	Optional[Any]       ):
      _UpperCAmelCase    			=   TFResNetModel(config=lowerCamelCase_       )
      _UpperCAmelCase    			=   model(lowerCamelCase_       )
      # 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   lowerCAmelCase_	(       self						:	List[Any] ,					__lowerCAmelCase						:	str ,					__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	List[str]       ):
      _UpperCAmelCase    			=   self.num_labels
      _UpperCAmelCase    			=   TFResNetForImageClassification(lowerCamelCase_       )
      _UpperCAmelCase    			=   model(lowerCamelCase_ ,					labels=lowerCamelCase_       )
      self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)       )


    def   lowerCAmelCase_	(       self						:	List[Any]       ):
      _UpperCAmelCase    			=   self.prepare_config_and_inputs()
      _UpperCAmelCase    			=   config_and_inputs
      _UpperCAmelCase    			=   {'''pixel_values''': pixel_values}
      return config, inputs_dict



@require_tf
class 							a					(		lowerCAmelCase_						,				lowerCAmelCase_						,				unittest.TestCase ):
    _snake_case  :	Optional[int]  				=				(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    _snake_case  :	Tuple  				=				(
        {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    _snake_case  :	Optional[int]  				=				False
    _snake_case  :	Union[str, Any]  				=				False
    _snake_case  :	Union[str, Any]  				=				False
    _snake_case  :	Union[str, Any]  				=				False
    _snake_case  :	Any  				=				False


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      _UpperCAmelCase    			=   TFResNetModelTester(self       )
      _UpperCAmelCase    			=   ConfigTester(self ,					config_class=lowerCamelCase_ ,					has_text_modality=lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      self.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()


    def   lowerCAmelCase_	(       self						:	Optional[Any]       ):
      return


    @unittest.skip(reason="""ResNet does not use inputs_embeds"""       )
    def   lowerCAmelCase_	(       self						:	Tuple       ):
      pass


    @unittest.skip(reason="""ResNet does not support input and output embeddings"""       )
    def   lowerCAmelCase_	(       self						:	Dict       ):
      pass


    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs_for_common()

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

        _UpperCAmelCase    			=   ['''pixel_values''']
        self.assertListEqual(arg_names[:1] ,					lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	str       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	Dict       ):



      def check_hidden_states_output(__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	List[Any] ,					__lowerCAmelCase						:	int       ):
        _UpperCAmelCase    			=   model_class(lowerCamelCase_       )
        _UpperCAmelCase    			=   model(**self._prepare_for_class(lowerCamelCase_ ,					lowerCamelCase_       )       )

        _UpperCAmelCase    			=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        _UpperCAmelCase    			=   self.model_tester.num_stages
        self.assertEqual(len(lowerCamelCase_       ) ,					expected_num_stages + 1       )

        # ResNet'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 // 4, self.model_tester.image_size // 4] ,					)

      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs_for_common()
      _UpperCAmelCase    			=   ['''basic''', '''bottleneck''']
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          _UpperCAmelCase    			=   layer_type
          _UpperCAmelCase    			=   True
          check_hidden_states_output(lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_       )

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

          check_hidden_states_output(lowerCamelCase_ ,					lowerCamelCase_ ,					lowerCamelCase_       )


    def   lowerCAmelCase_	(       self						:	Tuple       ):
      _UpperCAmelCase    			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_       )


    @slow
    def   lowerCAmelCase_	(       self						:	Union[str, Any]       ):



      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _UpperCAmelCase    			=   TFResNetModel.from_pretrained(lowerCamelCase_       )
        self.assertIsNotNone(lowerCamelCase_       )






def      __UpperCAmelCase       (      ):







  """simple docstring"""
  _UpperCAmelCase    			=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
  return image


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


    @cached_property
    def   lowerCAmelCase_	(       self						:	Tuple       ):
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
          if is_vision_available()
          else None
      )


    @slow
    def   lowerCAmelCase_	(       self						:	Any       ):
      _UpperCAmelCase    			=   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

      _UpperCAmelCase    			=   self.default_image_processor
      _UpperCAmelCase    			=   prepare_img()
      _UpperCAmelCase    			=   image_processor(images=lowerCamelCase_ ,					return_tensors="""tf"""       )

      # forward pass
      _UpperCAmelCase    			=   model(**lowerCamelCase_       )

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

      _UpperCAmelCase    			=   tf.constant([-11.1_069, -9.7_877, -8.3_777]       )

      self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() ,					lowerCamelCase_ ,					atol=1e-4       )       )

'''simple docstring'''

import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


UpperCamelCase__  :						str					=      get_tests_dir('fixtures')


class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	mock.Mock()
         UpperCAmelCase__				:					Dict 					=	500
         UpperCAmelCase__				:					Optional[int] 					=	{}
         UpperCAmelCase__				:					List[str] 					=	HTTPError
         UpperCAmelCase__				:					Tuple 					=	{}

         # Download this model to make sure it's in the cache.
         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''				)
         # Under the mock environment we get a 500 error when trying to reach the model.
         with mock.patch('''requests.Session.request'''       ,return_value=lowerCamelCase_				) as mock_head:
            UpperCAmelCase__				:					Tuple 					=	ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''				)
            # This check we did call the fake head request
            mock_head.assert_called()




      def 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	ViTImageProcessor.from_pretrained(
             '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'''				)




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



         '''simple docstring'''



         with self.assertRaises(lowerCamelCase_				):
            # config is in subfolder, the following should not work without specifying the subfolder
            UpperCAmelCase__				:					int 					=	AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants'''				)

         UpperCAmelCase__				:					Optional[Any] 					=	AutoImageProcessor.from_pretrained(
             '''hf-internal-testing/stable-diffusion-all-variants'''       ,subfolder='''feature_extractor'''				)

         self.assertIsNotNone(lowerCamelCase_				)




@is_staging_test
class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	TOKEN
         HfFolder.save_token(lowerCamelCase_				)




      @classmethod
      def 		lowerCAmelCase__       (					cls				)      ->      List[str]:



         '''simple docstring'''



         try:
            delete_repo(token=cls._token       ,repo_id='''test-image-processor'''				)
         except HTTPError:
            pass

         try:
            delete_repo(token=cls._token       ,repo_id='''valid_org/test-image-processor-org'''				)
         except HTTPError:
            pass

         try:
            delete_repo(token=cls._token       ,repo_id='''test-dynamic-image-processor'''				)
         except HTTPError:
            pass




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



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	ViTImageProcessor.from_pretrained(lowerCamelCase_				)
         image_processor.push_to_hub('''test-image-processor'''       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)

         # Reset repo
         delete_repo(token=self._token       ,repo_id='''test-image-processor'''				)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(
                lowerCamelCase_       ,repo_id='''test-image-processor'''       ,push_to_hub=lowerCamelCase_       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					List[Any] 					=	ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)




      def 		lowerCAmelCase__       (					self				)      ->      List[Any]:



         '''simple docstring'''



         UpperCAmelCase__				:					Union[str, Any] 					=	ViTImageProcessor.from_pretrained(lowerCamelCase_				)
         image_processor.push_to_hub('''valid_org/test-image-processor'''       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''valid_org/test-image-processor'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)

         # Reset repo
         delete_repo(token=self._token       ,repo_id='''valid_org/test-image-processor'''				)

         # Push to hub via save_pretrained
         with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(
                lowerCamelCase_       ,repo_id='''valid_org/test-image-processor-org'''       ,push_to_hub=lowerCamelCase_       ,use_auth_token=self._token				)

         UpperCAmelCase__				:					Any 					=	ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org'''				)
         for k, v in image_processor.__dict__.items():
            self.assertEqual(lowerCamelCase_       ,getattr(lowerCamelCase_       ,lowerCamelCase_				)				)




      def 		lowerCAmelCase__       (					self				)      ->      str:



         '''simple docstring'''



         CustomImageProcessor.register_for_auto_class()
         UpperCAmelCase__				:					List[str] 					=	CustomImageProcessor.from_pretrained(lowerCamelCase_				)

         image_processor.push_to_hub('''test-dynamic-image-processor'''       ,use_auth_token=self._token				)

         # This has added the proper auto_map field to the config
         self.assertDictEqual(
             image_processor.auto_map       ,{'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''}       ,)

         UpperCAmelCase__				:					Any 					=	AutoImageProcessor.from_pretrained(
             f'''{USER}/test-dynamic-image-processor'''       ,trust_remote_code=lowerCamelCase_				)
         # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
         self.assertEqual(new_image_processor.__class__.__name__       ,'''CustomImageProcessor'''				)




