

import inspect
import unittest

from transformers import RegNetConfig, 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.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor






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







			def __init__(	self							:       List[Any]					,					a							:       Dict					,					a							:       Tuple=3					,					a							:       Any=32					,					a							:       str=3					,					a							:       Optional[int]=10					,					a							:       Union[str, Any]=[10, 20, 30, 40]					,					a							:       Any=[1, 1, 2, 1]					,					a							:       str=True					,					a							:       Dict=True					,					a							:       Optional[Any]="relu"					,					a							:       List[Any]=3					,					a							:       Any=None					,					)							->				int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				parent
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				batch_size
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				image_size
				SCREAMING_SNAKE_CASE      :					str    =				num_channels
				SCREAMING_SNAKE_CASE      :					List[str]    =				embeddings_size
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				hidden_sizes
				SCREAMING_SNAKE_CASE      :					Tuple    =				depths
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				is_training
				SCREAMING_SNAKE_CASE      :					Tuple    =				use_labels
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				hidden_act
				SCREAMING_SNAKE_CASE      :					Any    =				num_labels
				SCREAMING_SNAKE_CASE      :					List[str]    =				scope
				SCREAMING_SNAKE_CASE      :					Any    =				len(a		)
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				self.get_config()

				return config, pixel_values
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				str:

				"""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					,					image_size=self.image_size					,					)
			def 							__UpperCamelCase       (	self							:       Optional[Any]					,					a							:       List[str]					,					a							:       int		)							->				int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Dict    =				FlaxRegNetModel(config=a		)
				SCREAMING_SNAKE_CASE      :					List[str]    =				model(a		)

				# 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 							__UpperCamelCase       (	self							:       List[Any]					,					a							:       List[Any]					,					a							:       int		)							->				Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.num_labels
				SCREAMING_SNAKE_CASE      :					List[Any]    =				FlaxRegNetForImageClassification(config=a		)
				SCREAMING_SNAKE_CASE      :					Tuple    =				model(a		)
				self.parent.assertEqual(result.logits.shape					,					(self.batch_size, self.num_labels)		)






			def 							__UpperCamelCase       (	self							:       Any		)							->				Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					int    =				self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Dict    =				config_and_inputs
				SCREAMING_SNAKE_CASE      :					str    =				{"pixel_values": pixel_values}
				return config, inputs_dict






@require_flax
class _UpperCamelCase							(							__A							,		unittest.TestCase      ):
			'''simple docstring'''







			lowerCamelCase__							=(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

			lowerCamelCase__							=False
			lowerCamelCase__							=False
			lowerCamelCase__							=False
			def 							__UpperCamelCase       (	self							:       Dict		)							->				None:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				FlaxRegNetModelTester(self		)
				SCREAMING_SNAKE_CASE      :					Dict    =				ConfigTester(self					,					config_class=a					,					has_text_modality=a		)
			def 							__UpperCamelCase       (	self							:       int		)							->				Any:

				"""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 							__UpperCamelCase       (	self							:       List[str]		)							->				Optional[int]:

				"""simple docstring"""

				return
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a		)
			def 							__UpperCamelCase       (	self							:       List[str]		)							->				Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*a		)
			@unittest.skip(reason="RegNet does not use inputs_embeds"		)
			def 							__UpperCamelCase       (	self							:       List[str]		)							->				Union[str, Any]:

				"""simple docstring"""

				pass
			@unittest.skip(reason="RegNet does not support input and output embeddings"		)
			def 							__UpperCamelCase       (	self							:       List[str]		)							->				List[str]:

				"""simple docstring"""

				pass
			def 							__UpperCamelCase       (	self							:       int		)							->				Tuple:

				"""simple docstring"""

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

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				model_class(a		)
					SCREAMING_SNAKE_CASE      :					int    =				inspect.signature(model.__call__		)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					SCREAMING_SNAKE_CASE      :					List[Any]    =				[*signature.parameters.keys()]

					SCREAMING_SNAKE_CASE      :					Any    =				["pixel_values"]
					self.assertListEqual(arg_names[:1]					,					a		)
			def 							__UpperCamelCase       (	self							:       Tuple		)							->				List[str]:

				"""simple docstring"""

				def check_hidden_states_output(a							:       List[str]					,					a							:       Tuple					,					a							:       Optional[int]		):
					SCREAMING_SNAKE_CASE      :					Dict    =				model_class(a		)

					SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				model(**self._prepare_for_class(a					,					a		)		)

					SCREAMING_SNAKE_CASE      :					Optional[int]    =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

					SCREAMING_SNAKE_CASE      :					int    =				self.model_tester.num_stages
					self.assertEqual(len(a		)					,					expected_num_stages + 1		)

				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					List[Any]    =				self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					List[Any]    =				True
					check_hidden_states_output(a					,					a					,					a		)

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

					check_hidden_states_output(a					,					a					,					a		)






			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				Optional[Any]:

				"""simple docstring"""

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

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

						@jax.jit
						def model_jitted(a							:       Optional[int]					,					**a							:       str		):
							return model(pixel_values=a					,					**a		)

						with self.subTest("JIT Enabled"		):
							SCREAMING_SNAKE_CASE      :					str    =				model_jitted(**a		).to_tuple()

						with self.subTest("JIT Disabled"		):
							with jax.disable_jit():
								SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				model_jitted(**a		).to_tuple()

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

def        lowerCamelCase__       (    ):
	SCREAMING_SNAKE_CASE      :					Optional[int]    =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
	return image






@require_flax
class _UpperCamelCase							(							unittest.TestCase      ):
			'''simple docstring'''







			@cached_property
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				Dict:

				"""simple docstring"""

				return AutoImageProcessor.from_pretrained("facebook/regnet-y-040"		) if is_vision_available() else None






			@slow
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Any    =				FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040"		)

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.default_image_processor
				SCREAMING_SNAKE_CASE      :					Any    =				prepare_img()
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				image_processor(images=a					,					return_tensors="np"		)

				SCREAMING_SNAKE_CASE      :					int    =				model(**a		)

				# verify the logits
				SCREAMING_SNAKE_CASE      :					str    =				(1, 1000)
				self.assertEqual(outputs.logits.shape					,					a		)

				SCREAMING_SNAKE_CASE      :					Any    =				jnp.array([-0.4180, -1.5051, -3.4836]		)

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





import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class        lowerCamelCase_							(      unittest.TestCase					):


 '''simple docstring'''







 def       lowerCAmelCase_  (							self  :		Any						):
       SCREAMING_SNAKE_CASE_							=			0



 def       lowerCAmelCase_  (							self  :		int						):
       SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32'						)
       self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		str						):
       # Ensure we can load the image processor from the feature extractor config
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Union[str, Any]						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			CLIPConfig()

             # Create a dummy config file with image_proceesor_type
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             # remove image_processor_type to make sure config.json alone is enough to load image processor locally
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						).to_dict()

             config_dict.pop('image_processor_type'						)
             SCREAMING_SNAKE_CASE_							=			CLIPImageProcessor(**_lowerCAmelCase						)

             # save in new folder
             model_config.save_pretrained(_lowerCAmelCase						)
             config.save_pretrained(_lowerCAmelCase						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)

             # make sure private variable is not incorrectly saved
             SCREAMING_SNAKE_CASE_							=			json.loads(config.to_json_string()						)
             self.assertTrue('_processor_class' not in dict_as_saved						)

       self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		str						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		List[Any]						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				'clip-base is not a local folder and is not a valid model identifier'						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('clip-base'						)



 def       lowerCAmelCase_  (							self  :		List[Any]						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase				,				revision='aaaaaa'						)



 def       lowerCAmelCase_  (							self  :		str						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'				,				):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model'						)



 def       lowerCAmelCase_  (							self  :		Tuple						):
       # If remote code is not set, we will time out when asking whether to load the model.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor'						)
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
           'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)

       # Test image processor can be reloaded.
       with tempfile.TemporaryDirectory() as tmp_dir:
             image_processor.save_pretrained(_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase				,				trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(reloaded_image_processor.__class__.__name__				,				'NewImageProcessor'						)



 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       try:
             AutoConfig.register('custom'				,				_lowerCAmelCase						)
             AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(_lowerCAmelCase						):
                   AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)

             with tempfile.TemporaryDirectory() as tmpdirname:
                   SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
                   SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
                   json.dump(
                       {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
                   json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

                   SCREAMING_SNAKE_CASE_							=			CustomImageProcessor.from_pretrained(_lowerCAmelCase						)

             # Now that the config is registered, it can be used as any other config with the auto-API
             with tempfile.TemporaryDirectory() as tmp_dir:
                   image_processor.save_pretrained(_lowerCAmelCase						)
                   SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
                   self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)

       finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                   del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]




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





       class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


        '''simple docstring'''







        lowercase_				    =    True

       try:
             AutoConfig.register('custom'				,				_lowerCAmelCase						)
             AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)
             # If remote code is not set, the default is to use local
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor'						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(image_processor.is_local						)

             # If remote code is disabled, we load the local one.
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(image_processor.is_local						)

             # If remote is enabled, we load from the Hub
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(not hasattr(_lowerCAmelCase				,				'is_local'						)						)

       finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                   del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]