




from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowerCamelCase__ :   Tuple					=							logging.get_logger(__name__)

lowerCamelCase__ :   List[Any]					=							{
    'shi-labs/dinat-mini-in1k-224': 'https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json',
    # See all Dinat models at https://huggingface.co/models?filter=dinat
}





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE       ,   _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    "dinat"

 lowercase_				    =    {
     "num_attention_heads": "num_heads",
     "num_hidden_layers": "num_layers",
 }



 def __init__(							self  :		Any				,				_lowerCAmelCase  :		int=4				,				_lowerCAmelCase  :		Optional[Any]=3				,				_lowerCAmelCase  :		List[Any]=64				,				_lowerCAmelCase  :		Optional[int]=[3, 4, 6, 5]				,				_lowerCAmelCase  :		Optional[Any]=[2, 4, 8, 16]				,				_lowerCAmelCase  :		List[str]=7				,				_lowerCAmelCase  :		Optional[int]=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]]				,				_lowerCAmelCase  :		Tuple=3.0				,				_lowerCAmelCase  :		Tuple=True				,				_lowerCAmelCase  :		int=0.0				,				_lowerCAmelCase  :		Union[str, Any]=0.0				,				_lowerCAmelCase  :		List[Any]=0.1				,				_lowerCAmelCase  :		int="gelu"				,				_lowerCAmelCase  :		Union[str, Any]=0.02				,				_lowerCAmelCase  :		Any=1E-5				,				_lowerCAmelCase  :		Dict=0.0				,				_lowerCAmelCase  :		List[str]=None				,				_lowerCAmelCase  :		int=None				,				**_lowerCAmelCase  :		Optional[int]				,				):
       super().__init__(**_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			patch_size
       SCREAMING_SNAKE_CASE_							=			num_channels
       SCREAMING_SNAKE_CASE_							=			embed_dim
       SCREAMING_SNAKE_CASE_							=			depths
       SCREAMING_SNAKE_CASE_							=			len(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			num_heads
       SCREAMING_SNAKE_CASE_							=			kernel_size
       SCREAMING_SNAKE_CASE_							=			dilations
       SCREAMING_SNAKE_CASE_							=			mlp_ratio
       SCREAMING_SNAKE_CASE_							=			qkv_bias
       SCREAMING_SNAKE_CASE_							=			hidden_dropout_prob
       SCREAMING_SNAKE_CASE_							=			attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE_							=			drop_path_rate
       SCREAMING_SNAKE_CASE_							=			hidden_act
       SCREAMING_SNAKE_CASE_							=			layer_norm_eps
       SCREAMING_SNAKE_CASE_							=			initializer_range
       # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel
       # this indicates the channel dimension after the last stage of the model
       SCREAMING_SNAKE_CASE_							=			int(embed_dim * 2 ** (len(_lowerCAmelCase						) - 1)						)
       SCREAMING_SNAKE_CASE_							=			layer_scale_init_value
       SCREAMING_SNAKE_CASE_							=			['stem'] + [F"stage{idx}" for idx in range(1				,				len(_lowerCAmelCase						) + 1						)]
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			get_aligned_output_features_output_indices(
           out_features=_lowerCAmelCase				,				out_indices=_lowerCAmelCase				,				stage_names=self.stage_names						)





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]