





"""simple docstring"""


import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
   import jax
   import jax.numpy as jnp

   from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor



class   lowercase_					(  unittest.TestCase				):

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






        '''simple docstring'''

        snake_case__     				=					parent
        snake_case__     				=					batch_size
        snake_case__     				=					image_size
        snake_case__     				=					num_channels
        snake_case__     				=					embeddings_size
        snake_case__     				=					hidden_sizes
        snake_case__     				=					depths
        snake_case__     				=					is_training
        snake_case__     				=					use_labels
        snake_case__     				=					hidden_act
        snake_case__     				=					num_labels
        snake_case__     				=					scope
        snake_case__     				=					len(__SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        snake_case__     				=					self.get_config()

        return config, pixel_values

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        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 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					FlaxResNetModel(config=__SCREAMING_SNAKE_CASE  )
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE  )

        # Output shape (b, c, h, w)
        self.parent.assertEqual(
            result.last_hidden_state.shape ,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,       )

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					self.num_labels
        snake_case__     				=					FlaxResNetForImageClassification(config=__SCREAMING_SNAKE_CASE  )
        snake_case__     				=					model(__SCREAMING_SNAKE_CASE  )
        self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					self.prepare_config_and_inputs()
        snake_case__				, snake_case__     				=					config_and_inputs
        snake_case__     				=					{"pixel_values": pixel_values}
        return config, inputs_dict



@require_flax
class   lowercase_					(  __lowerCAmelCase					,unittest.TestCase				):
       snake_case__					:				List[Any]									=  (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

       snake_case__					:				Optional[int]									=  False
       snake_case__					:				Union[str, Any]									=  False
       snake_case__					:				Tuple									=  False

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					FlaxResNetModelTester(self  )
        snake_case__     				=					ConfigTester(self ,       config_class=__SCREAMING_SNAKE_CASE ,       has_text_modality=__SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        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 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        return

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE  )

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






        '''simple docstring'''

        pass

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






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__				, snake_case__     				=					self.model_tester.prepare_config_and_inputs_for_common()

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

         snake_case__     				=					["pixel_values"]
         self.assertListEqual(arg_names[:1] ,       __SCREAMING_SNAKE_CASE  )

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        def check_hidden_states_output(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
         snake_case__     				=					model_class(__SCREAMING_SNAKE_CASE  )

         snake_case__     				=					model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )  )

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

         snake_case__     				=					self.model_tester.num_stages
         self.assertEqual(len(__SCREAMING_SNAKE_CASE  ) ,       expected_num_stages + 1  )

       @unittest.skip(reason="ResNet does not use feedforward chunking"  )
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        pass

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__				, snake_case__     				=					self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__  ):
          snake_case__     				=					self._prepare_for_class(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )
          snake_case__     				=					model_class(__SCREAMING_SNAKE_CASE  )

          @jax.jit
          def model_jitted(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):
           return model(pixel_values=__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )

          with self.subTest("JIT Enabled"  ):
           snake_case__     				=					model_jitted(**__SCREAMING_SNAKE_CASE  ).to_tuple()

          with self.subTest("JIT Disabled"  ):
           with jax.disable_jit():
            snake_case__     				=					model_jitted(**__SCREAMING_SNAKE_CASE  ).to_tuple()

          self.assertEqual(len(__SCREAMING_SNAKE_CASE  ) ,       len(__SCREAMING_SNAKE_CASE  )  )
          for jitted_output, output in zip(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
           self.assertEqual(jitted_output.shape ,       output.shape  )





def 				a__      (	)     ->	int:

 '''simple docstring'''






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



@require_flax
class   lowercase_					(  unittest.TestCase				):

       @cached_property
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        return AutoImageProcessor.from_pretrained("microsoft/resnet-50"  ) if is_vision_available() else None

       @slow
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					FlaxResNetForImageClassification.from_pretrained("microsoft/resnet-50"  )

        snake_case__     				=					self.default_image_processor
        snake_case__     				=					prepare_img()
        snake_case__     				=					image_processor(images=__SCREAMING_SNAKE_CASE ,       return_tensors="np"  )

        snake_case__     				=					model(**__SCREAMING_SNAKE_CASE  )

        # verify the logits
        snake_case__     				=					(1, 1000)
        self.assertEqual(outputs.logits.shape ,       __SCREAMING_SNAKE_CASE  )

        snake_case__     				=					jnp.array([-11.1069, -9.7877, -8.3777]  )

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








"""simple docstring"""


import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


a__       :  Any       		=					logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
a__       :  List[Any]       		=					direct_transformers_import(Path(__file__).parent)


a__       :  Optional[Any]       		=					{
    """AutoTokenizer""": """PreTrainedTokenizerBase""",
    """AutoFeatureExtractor""": """FeatureExtractionMixin""",
    """AutoImageProcessor""": """ImageProcessingMixin""",
}



class   lowercase_					(  __lowerCAmelCase				):
       snake_case__					:				Tuple									=  ["""feature_extractor""", """tokenizer"""]
       # Names need to be attr_class for attr in attributes
       snake_case__					:				Tuple									=  None
       snake_case__					:				Dict									=  None
       snake_case__					:				int									=  None

       def __init__(      self ,       *__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        for key in kwargs:
         if key not in self.attributes:
          raise TypeError(F"Unexpected keyword argument {key}."  )
        for arg, attribute_name in zip(__SCREAMING_SNAKE_CASE ,       self.attributes  ):
         if attribute_name in kwargs:
          raise TypeError(F"Got multiple values for argument {attribute_name}."  )
         else:
          snake_case__     				=					arg

        if len(__SCREAMING_SNAKE_CASE  ) != len(self.attributes  ):
         raise ValueError(
             F"This processor requires {len(self.attributes  )} arguments: {', '.join(self.attributes  )}. Got "
             F"{len(__SCREAMING_SNAKE_CASE  )} arguments instead."  )

        # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
        for attribute_name, arg in kwargs.items():
         snake_case__     				=					getattr(self ,       F"{attribute_name}_class"  )
         # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
         snake_case__     				=					AUTO_TO_BASE_CLASS_MAPPING.get(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )
         if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
          snake_case__     				=					tuple(getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) for n in class_name if n is not None  )
         else:
          snake_case__     				=					getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

         if not isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
          raise ValueError(
              F"Received a {type(__SCREAMING_SNAKE_CASE  ).__name__} for argument {attribute_name}, but a {class_name} was expected."  )

         setattr(self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

       def __repr__(      self  ):






        '''simple docstring'''

        snake_case__     				=					[F"- {name}: {repr(getattr(self ,       __SCREAMING_SNAKE_CASE  )  )}" for name in self.attributes]
        snake_case__     				=					"\n".join(__SCREAMING_SNAKE_CASE  )
        return F"{self.__class__.__name__}:\n{attributes_repr}"

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE = False ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        os.makedirs(__SCREAMING_SNAKE_CASE ,       exist_ok=__SCREAMING_SNAKE_CASE  )

        if push_to_hub:
         snake_case__     				=					kwargs.pop("commit_message" ,       __SCREAMING_SNAKE_CASE  )
         snake_case__     				=					kwargs.pop("repo_id" ,       save_directory.split(os.path.sep  )[-1]  )
         snake_case__     				=					self._create_repo(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )
         snake_case__     				=					self._get_files_timestamps(__SCREAMING_SNAKE_CASE  )
        # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
        # loaded from the Hub.
        if self._auto_class is not None:
         snake_case__     				=					[getattr(self ,       __SCREAMING_SNAKE_CASE  ) for attribute_name in self.attributes]
         snake_case__     				=					[(a.init_kwargs if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) else a) for a in attrs]
         custom_object_save(self ,       __SCREAMING_SNAKE_CASE ,       config=__SCREAMING_SNAKE_CASE  )

        for attribute_name in self.attributes:
         snake_case__     				=					getattr(self ,       __SCREAMING_SNAKE_CASE  )
         # Include the processor class in the attribute config so this processor can then be reloaded with the
         # `AutoProcessor` API.
         if hasattr(__SCREAMING_SNAKE_CASE ,       "_set_processor_class"  ):
          attribute._set_processor_class(self.__class__.__name__  )
         attribute.save_pretrained(__SCREAMING_SNAKE_CASE  )

        if self._auto_class is not None:
         # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
         for attribute_name in self.attributes:
          snake_case__     				=					getattr(self ,       __SCREAMING_SNAKE_CASE  )
          if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
           del attribute.init_kwargs["auto_map"]

        if push_to_hub:
         self._upload_modified_files(
             __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE ,       commit_message=__SCREAMING_SNAKE_CASE ,       token=kwargs.get("use_auth_token"  ) ,       )

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE = None ,       __SCREAMING_SNAKE_CASE = False ,       __SCREAMING_SNAKE_CASE = False ,       __SCREAMING_SNAKE_CASE = None ,       __SCREAMING_SNAKE_CASE = "main" ,       **__SCREAMING_SNAKE_CASE ,       ):






        '''simple docstring'''

        snake_case__     				=					cache_dir
        snake_case__     				=					force_download
        snake_case__     				=					local_files_only
        snake_case__     				=					revision

        snake_case__     				=					kwargs.pop("use_auth_token" ,       __SCREAMING_SNAKE_CASE  )
        if use_auth_token is not None:
         warnings.warn(
             "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers." ,       __SCREAMING_SNAKE_CASE  )
         if token is not None:
          raise ValueError(
              "`token` and `use_auth_token` are both specified. Please set only the argument `token`."  )
         snake_case__     				=					use_auth_token

        if token is not None:
         # change to `token` in a follow-up PR
         snake_case__     				=					token

        snake_case__     				=					cls._get_arguments_from_pretrained(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )
        return cls(*__SCREAMING_SNAKE_CASE  )

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE="AutoProcessor"  ):






        '''simple docstring'''

        if not isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
         snake_case__     				=					auto_class.__name__

        import transformers.models.auto as auto_module

        if not hasattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
         raise ValueError(F"{auto_class} is not a valid auto class."  )

        snake_case__     				=					auto_class

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					[]
        for attribute_name in cls.attributes:
         snake_case__     				=					getattr(cls ,       F"{attribute_name}_class"  )
         if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
          snake_case__     				=					tuple(getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) if n is not None else None for n in class_name  )
          snake_case__     				=					kwargs.get("use_fast" ,       __SCREAMING_SNAKE_CASE  )
          if use_fast and classes[1] is not None:
           snake_case__     				=					classes[1]
          else:
           snake_case__     				=					classes[0]
         else:
          snake_case__     				=					getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

         args.append(attribute_class.from_pretrained(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )  )
        return args

       @property
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        snake_case__     				=					getattr(self ,       self.attributes[0]  )
        return getattr(__SCREAMING_SNAKE_CASE ,       "model_input_names" ,       __SCREAMING_SNAKE_CASE  )
a__       :  Dict       		=					copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
   a__       :  Any       		=					ProcessorMixin.push_to_hub.__doc__.format(
       object="""processor""", object_class="""AutoProcessor""", object_files="""processor files"""
   )

