

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 				A_					(						unittest.TestCase   ):


     def __init__(				self     :						Union[str, Any]     ,    UpperCAmelCase     :						List[Any]     ,    UpperCAmelCase     :						Tuple=3     ,    UpperCAmelCase     :						str=3_2     ,    UpperCAmelCase     :						List[str]=3     ,    UpperCAmelCase     :						int=1_0     ,    UpperCAmelCase     :						List[Any]=[1_0, 2_0, 3_0, 4_0]     ,    UpperCAmelCase     :						Dict=[1, 1, 2, 1]     ,    UpperCAmelCase     :						Any=True     ,    UpperCAmelCase     :						Any=True     ,    UpperCAmelCase     :						List[str]="relu"     ,    UpperCAmelCase     :						int=3     ,    UpperCAmelCase     :						Optional[Any]=None     ,    )				->      str:
      __lowerCAmelCase:  Optional[Any]        = parent
      __lowerCAmelCase:  int        = batch_size
      __lowerCAmelCase:  Any        = image_size
      __lowerCAmelCase:  Optional[int]        = num_channels
      __lowerCAmelCase:  Optional[Any]        = embeddings_size
      __lowerCAmelCase:  List[Any]        = hidden_sizes
      __lowerCAmelCase:  Optional[Any]        = depths
      __lowerCAmelCase:  Optional[Any]        = is_training
      __lowerCAmelCase:  Any        = use_labels
      __lowerCAmelCase:  str        = hidden_act
      __lowerCAmelCase:  List[Any]        = num_labels
      __lowerCAmelCase:  Tuple        = scope
      __lowerCAmelCase:  str        = len(_lowercase   )


     def     UpperCAmelCase    (				self     :						List[Any]   )				->      int:
      __lowerCAmelCase:  Optional[Any]        = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

      __lowerCAmelCase:  Optional[Any]        = self.get_config()

      return config, pixel_values


     def     UpperCAmelCase    (				self     :						Optional[Any]   )				->      Union[str, 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     UpperCAmelCase    (				self     :						List[str]     ,    UpperCAmelCase     :						Optional[int]     ,    UpperCAmelCase     :						Union[str, Any]   )				->      Optional[Any]:
      __lowerCAmelCase:  Union[str, Any]        = FlaxResNetModel(config=_lowercase   )
      __lowerCAmelCase:  Dict        = model(_lowercase   )

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


     def     UpperCAmelCase    (				self     :						Union[str, Any]     ,    UpperCAmelCase     :						List[Any]     ,    UpperCAmelCase     :						Union[str, Any]   )				->      int:
      __lowerCAmelCase:  Any        = self.num_labels
      __lowerCAmelCase:  Tuple        = FlaxResNetForImageClassification(config=_lowercase   )
      __lowerCAmelCase:  Optional[Any]        = model(_lowercase   )
      self.parent.assertEqual(result.logits.shape     ,    (self.batch_size, self.num_labels)   )


     def     UpperCAmelCase    (				self     :						Any   )				->      Any:
      __lowerCAmelCase:  Any        = self.prepare_config_and_inputs()
      __lowerCAmelCase      ,				__lowerCAmelCase:  str        = config_and_inputs
      __lowerCAmelCase:  List[str]        = {'pixel_values': pixel_values}
      return config, inputs_dict







@require_flax
class 				A_					(						__lowerCamelCase				,      unittest.TestCase   ):
     _lowercase     :	List[Any]        =      (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

     _lowercase     :	Dict        =      False
     _lowercase     :	str        =      False
     _lowercase     :	Any        =      False


     def     UpperCAmelCase    (				self     :						List[Any]   )				->      Optional[Any]:
      __lowerCAmelCase:  Dict        = FlaxResNetModelTester(self   )
      __lowerCAmelCase:  Dict        = ConfigTester(self     ,    config_class=_lowercase     ,    has_text_modality=_lowercase   )


     def     UpperCAmelCase    (				self     :						List[str]   )				->      int:
      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     UpperCAmelCase    (				self     :						str   )				->      Union[str, Any]:
      return


     def     UpperCAmelCase    (				self     :						List[Any]   )				->      List[Any]:
      __lowerCAmelCase:  Optional[Any]        = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_lowercase   )


     def     UpperCAmelCase    (				self     :						Any   )				->      Tuple:
      __lowerCAmelCase:  Union[str, Any]        = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_lowercase   )


     @unittest.skip(reason='ResNet does not use inputs_embeds'   )
     def     UpperCAmelCase    (				self     :						Any   )				->      Any:
      pass


     @unittest.skip(reason='ResNet does not support input and output embeddings'   )
     def     UpperCAmelCase    (				self     :						Optional[int]   )				->      Tuple:
      pass


     def     UpperCAmelCase    (				self     :						Any   )				->      Tuple:
      __lowerCAmelCase      ,				__lowerCAmelCase:  Tuple        = self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       __lowerCAmelCase:  Tuple        = model_class(_lowercase   )
       __lowerCAmelCase:  Optional[int]        = inspect.signature(model.__call__   )
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       __lowerCAmelCase:  str        = [*signature.parameters.keys()]

       __lowerCAmelCase:  List[str]        = ['pixel_values']
       self.assertListEqual(arg_names[:1]     ,    _lowercase   )


     def     UpperCAmelCase    (				self     :						Tuple   )				->      Any:
      def check_hidden_states_output(UpperCAmelCase     :						Optional[int]     ,    UpperCAmelCase     :						int     ,    UpperCAmelCase     :						int   ):
       __lowerCAmelCase:  List[str]        = model_class(_lowercase   )

       __lowerCAmelCase:  Optional[int]        = model(**self._prepare_for_class(_lowercase     ,    _lowercase   )   )

       __lowerCAmelCase:  List[Any]        = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

       __lowerCAmelCase:  Optional[Any]        = self.model_tester.num_stages
       self.assertEqual(len(_lowercase   )     ,    expected_num_stages + 1   )


     @unittest.skip(reason='ResNet does not use feedforward chunking'   )
     def     UpperCAmelCase    (				self     :						List[str]   )				->      Union[str, Any]:
      pass


     def     UpperCAmelCase    (				self     :						Union[str, Any]   )				->      Tuple:
      __lowerCAmelCase      ,				__lowerCAmelCase:  Optional[Any]        = self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       with self.subTest(model_class.__name__   ):
        __lowerCAmelCase:  str        = self._prepare_for_class(_lowercase     ,    _lowercase   )
        __lowerCAmelCase:  List[Any]        = model_class(_lowercase   )

        @jax.jit
        def model_jitted(UpperCAmelCase     :						int     ,    **UpperCAmelCase     :						Any   ):
         return model(pixel_values=_lowercase     ,    **_lowercase   )

        with self.subTest('JIT Enabled'   ):
         __lowerCAmelCase:  Union[str, Any]        = model_jitted(**_lowercase   ).to_tuple()

        with self.subTest('JIT Disabled'   ):
         with jax.disable_jit():
          __lowerCAmelCase:  Dict        = model_jitted(**_lowercase   ).to_tuple()

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







def _a					(			)       ->       List[Any]:

 """simple docstring"""






 __lowerCAmelCase:  Optional[int]        = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
 return image






@require_flax
class 				A_					(						unittest.TestCase   ):


     @cached_property
     def     UpperCAmelCase    (				self     :						Tuple   )				->      List[Any]:
      return AutoImageProcessor.from_pretrained('microsoft/resnet-50'   ) if is_vision_available() else None


     @slow
     def     UpperCAmelCase    (				self     :						Dict   )				->      int:
      __lowerCAmelCase:  Any        = FlaxResNetForImageClassification.from_pretrained('microsoft/resnet-50'   )

      __lowerCAmelCase:  List[Any]        = self.default_image_processor
      __lowerCAmelCase:  Optional[int]        = prepare_img()
      __lowerCAmelCase:  Optional[int]        = image_processor(images=_lowercase     ,    return_tensors='np'   )

      __lowerCAmelCase:  List[Any]        = model(**_lowercase   )

      # verify the logits
      __lowerCAmelCase:  Optional[Any]        = (1, 1_0_0_0)
      self.assertEqual(outputs.logits.shape     ,    _lowercase   )

      __lowerCAmelCase:  Tuple        = jnp.array([-11.1069, -9.7877, -8.3777]   )

      self.assertTrue(jnp.allclose(outputs.logits[0, :3]     ,    _lowercase     ,    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


UpperCamelCase_							:							Optional[int]				 =		logging.get_logger(__name__)

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


UpperCamelCase_							:							Optional[int]				 =		{
    """AutoTokenizer""": """PreTrainedTokenizerBase""",
    """AutoFeatureExtractor""": """FeatureExtractionMixin""",
    """AutoImageProcessor""": """ImageProcessingMixin""",
}


class       _lowercase		( __lowerCamelCase	):
				lowerCamelCase__							=							['feature_extractor', 'tokenizer']
				# Names need to be attr_class for attr in attributes
				lowerCamelCase__							=							None
				lowerCamelCase__							=							None
				lowerCamelCase__							=							None

				def __init__(  self							:     Any							,     *_lowercase							:     Optional[int]							,     **_lowercase							:     int  ):


										'''simple docstring'''
										# Sanitize args and kwargs
										for key in kwargs:
																if key not in self.attributes:
																						raise TypeError(f'Unexpected keyword argument {key}.'  )
										for arg, attribute_name in zip(_lowercase							,     self.attributes  ):
																if attribute_name in kwargs:
																						raise TypeError(f'Got multiple values for argument {attribute_name}.'  )
																else:
																						UpperCAmelCase__       						=		arg

										if len(_lowercase  ) != len(self.attributes  ):
																raise ValueError(
																    f'This processor requires {len(self.attributes  )} arguments: {", ".join(self.attributes  )}. Got '
																    f'{len(_lowercase  )} 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():
																UpperCAmelCase__       						=		getattr(self							,     f'{attribute_name}_class'  )
																# Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
																UpperCAmelCase__       						=		AUTO_TO_BASE_CLASS_MAPPING.get(_lowercase							,     _lowercase  )
																if isinstance(_lowercase							,     _lowercase  ):
																						UpperCAmelCase__       						=		tuple(getattr(_lowercase							,     _lowercase  ) for n in class_name if n is not None  )
																else:
																						UpperCAmelCase__       						=		getattr(_lowercase							,     _lowercase  )

																if not isinstance(_lowercase							,     _lowercase  ):
																						raise ValueError(
																						    f'Received a {type(_lowercase  ).__name__} for argument {attribute_name}, but a {class_name} was expected.'  )

																setattr(self							,     _lowercase							,     _lowercase  )

				def __repr__(  self							:     Tuple  ):


										'''simple docstring'''
										UpperCAmelCase__       						=		[f'- {name}: {repr(getattr(self							,     _lowercase  )  )}' for name in self.attributes]
										UpperCAmelCase__       						=		"""\n""".join(_lowercase  )
										return f'{self.__class__.__name__}:\n{attributes_repr}'

				def 							A			(  self							:     Tuple							,     _lowercase							:     Dict							,     _lowercase							:     bool = False							,     **_lowercase							:     List[str]  ):


										'''simple docstring'''
										os.makedirs(_lowercase							,     exist_ok=_lowercase  )

										if push_to_hub:
																UpperCAmelCase__       						=		kwargs.pop("""commit_message"""							,     _lowercase  )
																UpperCAmelCase__       						=		kwargs.pop("""repo_id"""							,     save_directory.split(os.path.sep  )[-1]  )
																UpperCAmelCase__       						=		self._create_repo(_lowercase							,     **_lowercase  )
																UpperCAmelCase__       						=		self._get_files_timestamps(_lowercase  )
										# 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:
																UpperCAmelCase__       						=		[getattr(self							,     _lowercase  ) for attribute_name in self.attributes]
																UpperCAmelCase__       						=		[(a.init_kwargs if isinstance(_lowercase							,     _lowercase  ) else a) for a in attrs]
																custom_object_save(self							,     _lowercase							,     config=_lowercase  )

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

										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:
																						UpperCAmelCase__       						=		getattr(self							,     _lowercase  )
																						if isinstance(_lowercase							,     _lowercase  ):
																												del attribute.init_kwargs["auto_map"]

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

				@classmethod
				def 							A			(  cls							:     Dict							,     _lowercase							:     Union[str, os.PathLike]							,     _lowercase							:     Optional[Union[str, os.PathLike]] = None							,     _lowercase							:     bool = False							,     _lowercase							:     bool = False							,     _lowercase							:     Optional[Union[str, bool]] = None							,     _lowercase							:     str = "main"							,     **_lowercase							:     Dict							,     ):


										'''simple docstring'''
										UpperCAmelCase__       						=		cache_dir
										UpperCAmelCase__       						=		force_download
										UpperCAmelCase__       						=		local_files_only
										UpperCAmelCase__       						=		revision

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

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

										UpperCAmelCase__       						=		cls._get_arguments_from_pretrained(_lowercase							,     **_lowercase  )
										return cls(*_lowercase  )

				@classmethod
				def 							A			(  cls							:     List[Any]							,     _lowercase							:     Dict="AutoProcessor"  ):


										'''simple docstring'''
										if not isinstance(_lowercase							,     _lowercase  ):
																UpperCAmelCase__       						=		auto_class.__name__

										import transformers.models.auto as auto_module

										if not hasattr(_lowercase							,     _lowercase  ):
																raise ValueError(f'{auto_class} is not a valid auto class.'  )

										UpperCAmelCase__       						=		auto_class

				@classmethod
				def 							A			(  cls							:     Any							,     _lowercase							:     Tuple							,     **_lowercase							:     List[Any]  ):


										'''simple docstring'''
										UpperCAmelCase__       						=		[]
										for attribute_name in cls.attributes:
																UpperCAmelCase__       						=		getattr(cls							,     f'{attribute_name}_class'  )
																if isinstance(_lowercase							,     _lowercase  ):
																						UpperCAmelCase__       						=		tuple(getattr(_lowercase							,     _lowercase  ) if n is not None else None for n in class_name  )
																						UpperCAmelCase__       						=		kwargs.get("""use_fast"""							,     _lowercase  )
																						if use_fast and classes[1] is not None:
																												UpperCAmelCase__       						=		classes[1]
																						else:
																												UpperCAmelCase__       						=		classes[0]
																else:
																						UpperCAmelCase__       						=		getattr(_lowercase							,     _lowercase  )

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

				@property
				def 							A			(  self							:     int  ):


										'''simple docstring'''
										UpperCAmelCase__       						=		getattr(self							,     self.attributes[0]  )
										return getattr(_lowercase							,     """model_input_names"""							,     _lowercase  )
UpperCamelCase_							:							List[Any]				 =		copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
						UpperCamelCase_							:							Dict				 =		ProcessorMixin.push_to_hub.__doc__.format(
						    object="""processor""", object_class="""AutoProcessor""", object_files="""processor files"""
						)

