






'''simple docstring'''

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

  def 						A__		(   self   )						->   Optional[int]:



        """simple docstring"""






        UpperCamelCase       						=      0

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



        """simple docstring"""






        UpperCamelCase       						=      AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32"""   )
        self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   str:



        """simple docstring"""






        with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCamelCase       						=      Path(_SCREAMING_SNAKE_CASE   ) / """preprocessor_config.json"""
              UpperCamelCase       						=      Path(_SCREAMING_SNAKE_CASE   ) / """config.json"""
              json.dump(
                  {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}    ,	open(_SCREAMING_SNAKE_CASE    ,	"""w"""   )    ,	)
              json.dump({"""model_type""": """clip"""}    ,	open(_SCREAMING_SNAKE_CASE    ,	"""w"""   )   )

              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Tuple:



        """simple docstring"""






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

              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Any:



        """simple docstring"""






        with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCamelCase       						=      CLIPConfig()

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

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

              config_dict.pop("""image_processor_type"""   )
              UpperCamelCase       						=      CLIPImageProcessor(**_SCREAMING_SNAKE_CASE   )

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

              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )

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

        self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   str:



        """simple docstring"""






        with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCamelCase       						=      Path(_SCREAMING_SNAKE_CASE   ) / """preprocessor_config.json"""
              json.dump(
                  {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}    ,	open(_SCREAMING_SNAKE_CASE    ,	"""w"""   )    ,	)

              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






        with self.assertRaisesRegex(
            _SCREAMING_SNAKE_CASE    ,	"""clip-base is not a local folder and is not a valid model identifier"""   ):
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained("""clip-base"""   )

  def 						A__		(   self   )						->   Dict:



        """simple docstring"""






        with self.assertRaisesRegex(
            _SCREAMING_SNAKE_CASE    ,	R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""   ):
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE    ,	revision="""aaaaaa"""   )

  def 						A__		(   self   )						->   int:



        """simple docstring"""






        with self.assertRaisesRegex(
            _SCREAMING_SNAKE_CASE    ,	"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""    ,	):
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model"""   )

  def 						A__		(   self   )						->   str:



        """simple docstring"""






        with self.assertRaises(_SCREAMING_SNAKE_CASE   ):
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor"""   )
        # If remote code is disabled, we can't load this config.
        with self.assertRaises(_SCREAMING_SNAKE_CASE   ):
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(
                  """hf-internal-testing/test_dynamic_image_processor"""    ,	trust_remote_code=_SCREAMING_SNAKE_CASE   )

        UpperCamelCase       						=      AutoImageProcessor.from_pretrained(
            """hf-internal-testing/test_dynamic_image_processor"""    ,	trust_remote_code=_SCREAMING_SNAKE_CASE   )
        self.assertEqual(image_processor.__class__.__name__    ,	"""NewImageProcessor"""   )

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

  def 						A__		(   self   )						->   Tuple:



        """simple docstring"""






        try:
              AutoConfig.register("""custom"""    ,	_SCREAMING_SNAKE_CASE   )
              AutoImageProcessor.register(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )
              # Trying to register something existing in the Transformers library will raise an error
              with self.assertRaises(_SCREAMING_SNAKE_CASE   ):
                    AutoImageProcessor.register(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

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

                    UpperCamelCase       						=      CustomImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )

              # 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(_SCREAMING_SNAKE_CASE   )
                    UpperCamelCase       						=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE   )
                    self.assertIsInstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )

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



        """simple docstring"""






        class        a_		(    lowerCamelCase       ):
          lowercase  	=   True

        try:
              AutoConfig.register("""custom"""    ,	_SCREAMING_SNAKE_CASE   )
              AutoImageProcessor.register(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   )
              # If remote code is not set, the default is to use local
              UpperCamelCase       						=      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.
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(
                  """hf-internal-testing/test_dynamic_image_processor"""    ,	trust_remote_code=_SCREAMING_SNAKE_CASE   )
              self.assertEqual(image_processor.__class__.__name__    ,	"""NewImageProcessor"""   )
              self.assertTrue(image_processor.is_local   )

              # If remote is enabled, we load from the Hub
              UpperCamelCase       						=      AutoImageProcessor.from_pretrained(
                  """hf-internal-testing/test_dynamic_image_processor"""    ,	trust_remote_code=_SCREAMING_SNAKE_CASE   )
              self.assertEqual(image_processor.__class__.__name__    ,	"""NewImageProcessor"""   )
              self.assertTrue(not hasattr(_SCREAMING_SNAKE_CASE    ,	"""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]








'''simple docstring'''

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


SCREAMING_SNAKE_CASE__											=     logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__											=     {
    'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}






class        a_		(    lowerCamelCase       ):
  lowercase  	=   """deformable_detr"""
  lowercase  	=   {
      """hidden_size""": """d_model""",
      """num_attention_heads""": """encoder_attention_heads""",
  }

  def __init__(   self    ,	_SCREAMING_SNAKE_CASE=True    ,	_SCREAMING_SNAKE_CASE=None    ,	_SCREAMING_SNAKE_CASE=3    ,	_SCREAMING_SNAKE_CASE=300    ,	_SCREAMING_SNAKE_CASE=1024    ,	_SCREAMING_SNAKE_CASE=6    ,	_SCREAMING_SNAKE_CASE=1024    ,	_SCREAMING_SNAKE_CASE=8    ,	_SCREAMING_SNAKE_CASE=6    ,	_SCREAMING_SNAKE_CASE=1024    ,	_SCREAMING_SNAKE_CASE=8    ,	_SCREAMING_SNAKE_CASE=0.0    ,	_SCREAMING_SNAKE_CASE=True    ,	_SCREAMING_SNAKE_CASE="relu"    ,	_SCREAMING_SNAKE_CASE=256    ,	_SCREAMING_SNAKE_CASE=0.1    ,	_SCREAMING_SNAKE_CASE=0.0    ,	_SCREAMING_SNAKE_CASE=0.0    ,	_SCREAMING_SNAKE_CASE=0.0_2    ,	_SCREAMING_SNAKE_CASE=1.0    ,	_SCREAMING_SNAKE_CASE=True    ,	_SCREAMING_SNAKE_CASE=False    ,	_SCREAMING_SNAKE_CASE="sine"    ,	_SCREAMING_SNAKE_CASE="resnet50"    ,	_SCREAMING_SNAKE_CASE=True    ,	_SCREAMING_SNAKE_CASE=False    ,	_SCREAMING_SNAKE_CASE=4    ,	_SCREAMING_SNAKE_CASE=4    ,	_SCREAMING_SNAKE_CASE=4    ,	_SCREAMING_SNAKE_CASE=False    ,	_SCREAMING_SNAKE_CASE=300    ,	_SCREAMING_SNAKE_CASE=False    ,	_SCREAMING_SNAKE_CASE=1    ,	_SCREAMING_SNAKE_CASE=5    ,	_SCREAMING_SNAKE_CASE=2    ,	_SCREAMING_SNAKE_CASE=1    ,	_SCREAMING_SNAKE_CASE=1    ,	_SCREAMING_SNAKE_CASE=5    ,	_SCREAMING_SNAKE_CASE=2    ,	_SCREAMING_SNAKE_CASE=0.1    ,	_SCREAMING_SNAKE_CASE=0.2_5    ,	_SCREAMING_SNAKE_CASE=False    ,	**_SCREAMING_SNAKE_CASE    ,	)						->   List[str]:



        """simple docstring"""






        if backbone_config is not None and use_timm_backbone:
              raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`."""   )

        if not use_timm_backbone:
              if backbone_config is None:
                    logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""   )
                    UpperCamelCase       						=      CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""]   )
              elif isinstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE   ):
                    UpperCamelCase       						=      backbone_config.get("""model_type"""   )
                    UpperCamelCase       						=      CONFIG_MAPPING[backbone_model_type]
                    UpperCamelCase       						=      config_class.from_dict(_SCREAMING_SNAKE_CASE   )
        UpperCamelCase       						=      use_timm_backbone
        UpperCamelCase       						=      backbone_config
        UpperCamelCase       						=      num_channels
        UpperCamelCase       						=      num_queries
        UpperCamelCase       						=      max_position_embeddings
        UpperCamelCase       						=      d_model
        UpperCamelCase       						=      encoder_ffn_dim
        UpperCamelCase       						=      encoder_layers
        UpperCamelCase       						=      encoder_attention_heads
        UpperCamelCase       						=      decoder_ffn_dim
        UpperCamelCase       						=      decoder_layers
        UpperCamelCase       						=      decoder_attention_heads
        UpperCamelCase       						=      dropout
        UpperCamelCase       						=      attention_dropout
        UpperCamelCase       						=      activation_dropout
        UpperCamelCase       						=      activation_function
        UpperCamelCase       						=      init_std
        UpperCamelCase       						=      init_xavier_std
        UpperCamelCase       						=      encoder_layerdrop
        UpperCamelCase       						=      auxiliary_loss
        UpperCamelCase       						=      position_embedding_type
        UpperCamelCase       						=      backbone
        UpperCamelCase       						=      use_pretrained_backbone
        UpperCamelCase       						=      dilation
        # deformable attributes
        UpperCamelCase       						=      num_feature_levels
        UpperCamelCase       						=      encoder_n_points
        UpperCamelCase       						=      decoder_n_points
        UpperCamelCase       						=      two_stage
        UpperCamelCase       						=      two_stage_num_proposals
        UpperCamelCase       						=      with_box_refine
        if two_stage is True and with_box_refine is False:
              raise ValueError("""If two_stage is True, with_box_refine must be True."""   )
        # Hungarian matcher
        UpperCamelCase       						=      class_cost
        UpperCamelCase       						=      bbox_cost
        UpperCamelCase       						=      giou_cost
        # Loss coefficients
        UpperCamelCase       						=      mask_loss_coefficient
        UpperCamelCase       						=      dice_loss_coefficient
        UpperCamelCase       						=      bbox_loss_coefficient
        UpperCamelCase       						=      giou_loss_coefficient
        UpperCamelCase       						=      eos_coefficient
        UpperCamelCase       						=      focal_alpha
        UpperCamelCase       						=      disable_custom_kernels
        super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE    ,	**_SCREAMING_SNAKE_CASE   )

  @property
  def 						A__		(   self   )						->   int:



        """simple docstring"""






        return self.encoder_attention_heads

  @property
  def 						A__		(   self   )						->   int:



        """simple docstring"""






        return self.d_model


  def 						A__		(   self   )						->   Tuple:



        """simple docstring"""






        UpperCamelCase       						=      copy.deepcopy(self.__dict__   )
        if self.backbone_config is not None:
              UpperCamelCase       						=      self.backbone_config.to_dict()
        UpperCamelCase       						=      self.__class__.model_type
        return output
