






import math

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin
class UpperCAmelCase_					(    __A				,       __A				):




      """simple docstring"""




      @register_to_config
      def __init__( self			:		str     ,      UpperCAmelCase			:		int = 128     ,      UpperCAmelCase			:		int = 256     ,      UpperCAmelCase			:		float = 2000.0     ,      UpperCAmelCase			:		int = 768     ,      UpperCAmelCase			:		int = 12     ,      UpperCAmelCase			:		int = 12     ,      UpperCAmelCase			:		int = 64     ,      UpperCAmelCase			:		int = 2048     ,      UpperCAmelCase			:		float = 0.1     ,      )  ->  int:


       '''simple docstring'''

       super().__init__()

       lowercase					:   Optional[int]				  =nn.Sequential(
           nn.Linear(UpperCAmelCase     ,      d_model * 4     ,      bias=UpperCAmelCase		)     ,      nn.SiLU()     ,      nn.Linear(d_model * 4     ,      d_model * 4     ,      bias=UpperCAmelCase		)     ,      nn.SiLU()     ,      )

       lowercase					:   Any				  =nn.Embedding(UpperCAmelCase     ,      UpperCAmelCase		)
       lowercase					:   Optional[Any]				  =False

       lowercase					:   Optional[int]				  =nn.Linear(UpperCAmelCase     ,      UpperCAmelCase     ,      bias=UpperCAmelCase		)

       lowercase					:   Optional[int]				  =nn.Dropout(p=UpperCAmelCase		)

       lowercase					:   Tuple				  =nn.ModuleList()
       for lyr_num in range(UpperCAmelCase		):
        # FiLM conditional T5 decoder
        lowercase					:   Dict				  =DecoderLayer(d_model=UpperCAmelCase     ,      d_kv=UpperCAmelCase     ,      num_heads=UpperCAmelCase     ,      d_ff=UpperCAmelCase     ,      dropout_rate=UpperCAmelCase		)
        self.decoders.append(UpperCAmelCase		)

       lowercase					:   Optional[int]				  =TaLayerNorm(UpperCAmelCase		)

       lowercase					:   str				  =nn.Dropout(p=UpperCAmelCase		)
       lowercase					:   Dict				  =nn.Linear(UpperCAmelCase     ,      UpperCAmelCase     ,      bias=UpperCAmelCase		)






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		int		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   List[str]				  =torch.mul(query_input.unsqueeze(-1		)     ,      key_input.unsqueeze(-2		)		)
       return mask.unsqueeze(-3		)






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


       '''simple docstring'''

       lowercase					:   int				  =decoder_input_tokens.shape
       assert decoder_noise_time.shape == (batch,)

       # decoder_noise_time is in [0, 1), so rescale to expected timing range.
       lowercase					:   int				  =get_timestep_embedding(
           decoder_noise_time * self.config.max_decoder_noise_time     ,      embedding_dim=self.config.d_model     ,      max_period=self.config.max_decoder_noise_time     ,      ).to(dtype=self.dtype		)

       lowercase					:   int				  =self.conditioning_emb(UpperCAmelCase		).unsqueeze(1		)

       assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)

       lowercase					:   int				  =decoder_input_tokens.shape[1]

       # If we want to use relative positions for audio context, we can just offset
       # this sequence by the length of encodings_and_masks.
       lowercase					:   str				  =torch.broadcast_to(
           torch.arange(UpperCAmelCase     ,      device=decoder_input_tokens.device		)     ,      (batch, seq_length)     ,      )

       lowercase					:   Tuple				  =self.position_encoding(UpperCAmelCase		)

       lowercase					:   Any				  =self.continuous_inputs_projection(UpperCAmelCase		)
       inputs += position_encodings
       lowercase					:   Optional[int]				  =self.dropout(UpperCAmelCase		)

       # decoder: No padding present.
       lowercase					:   List[Any]				  =torch.ones(
           decoder_input_tokens.shape[:2]     ,      device=decoder_input_tokens.device     ,      dtype=inputs.dtype		)

       # Translate encoding masks to encoder-decoder masks.
       lowercase					:   Any				  =[(x, self.encoder_decoder_mask(UpperCAmelCase     ,      UpperCAmelCase		)) for x, y in encodings_and_masks]

       # cross attend style: concat encodings
       lowercase					:   Optional[Any]				  =torch.cat([x[0] for x in encodings_and_encdec_masks]     ,      dim=1		)
       lowercase					:   str				  =torch.cat([x[1] for x in encodings_and_encdec_masks]     ,      dim=-1		)

       for lyr in self.decoders:
        lowercase					:   List[str]				  =lyr(
            UpperCAmelCase     ,      conditioning_emb=UpperCAmelCase     ,      encoder_hidden_states=UpperCAmelCase     ,      encoder_attention_mask=UpperCAmelCase     ,      )[0]

       lowercase					:   Any				  =self.decoder_norm(UpperCAmelCase		)
       lowercase					:   List[Any]				  =self.post_dropout(UpperCAmelCase		)

       lowercase					:   Any				  =self.spec_out(UpperCAmelCase		)
       return spec_out





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Tuple     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		int=1e-6		)  ->  Any:


       '''simple docstring'''

       super().__init__()
       lowercase					:   str				  =nn.ModuleList()

       # cond self attention: layer 0
       self.layer.append(
           TaLayerSelfAttentionCond(d_model=UpperCAmelCase     ,      d_kv=UpperCAmelCase     ,      num_heads=UpperCAmelCase     ,      dropout_rate=UpperCAmelCase		)		)

       # cross attention: layer 1
       self.layer.append(
           TaLayerCrossAttention(
               d_model=UpperCAmelCase     ,      d_kv=UpperCAmelCase     ,      num_heads=UpperCAmelCase     ,      dropout_rate=UpperCAmelCase     ,      layer_norm_epsilon=UpperCAmelCase     ,      )		)

       # Film Cond MLP + dropout: last layer
       self.layer.append(
           TaLayerFFCond(d_model=UpperCAmelCase     ,      d_ff=UpperCAmelCase     ,      dropout_rate=UpperCAmelCase     ,      layer_norm_epsilon=UpperCAmelCase		)		)






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		int=None     ,      UpperCAmelCase			:		Optional[Any]=None     ,      UpperCAmelCase			:		Optional[Any]=None     ,      UpperCAmelCase			:		List[str]=None     ,      UpperCAmelCase			:		int=None     ,      )  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =self.layer[0](
           UpperCAmelCase     ,      conditioning_emb=UpperCAmelCase     ,      attention_mask=UpperCAmelCase     ,      )

       if encoder_hidden_states is not None:
        lowercase					:   Union[str, Any]				  =torch.where(encoder_attention_mask > 0     ,      0     ,      -1e10		).to(
            encoder_hidden_states.dtype		)

        lowercase					:   List[str]				  =self.layer[1](
            UpperCAmelCase     ,      key_value_states=UpperCAmelCase     ,      attention_mask=UpperCAmelCase     ,      )

       # Apply Film Conditional Feed Forward layer
       lowercase					:   List[str]				  =self.layer[-1](UpperCAmelCase     ,      UpperCAmelCase		)

       return (hidden_states,)





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Optional[Any]     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		List[str]		)  ->  Union[str, Any]:


       '''simple docstring'''

       super().__init__()
       lowercase					:   Optional[int]				  =TaLayerNorm(UpperCAmelCase		)
       lowercase					:   List[str]				  =TaFiLMLayer(in_features=d_model * 4     ,      out_features=UpperCAmelCase		)
       lowercase					:   Optional[Any]				  =Attention(query_dim=UpperCAmelCase     ,      heads=UpperCAmelCase     ,      dim_head=UpperCAmelCase     ,      out_bias=UpperCAmelCase     ,      scale_qk=UpperCAmelCase		)
       lowercase					:   Any				  =nn.Dropout(UpperCAmelCase		)






      def 				A__      ( self			:		List[str]     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		Optional[int]=None     ,      UpperCAmelCase			:		Optional[int]=None     ,      )  ->  Optional[Any]:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =self.layer_norm(UpperCAmelCase		)

       if conditioning_emb is not None:
        lowercase					:   Tuple				  =self.FiLMLayer(UpperCAmelCase     ,      UpperCAmelCase		)

       # Self-attention block
       lowercase					:   Tuple				  =self.attention(UpperCAmelCase		)

       lowercase					:   Dict				  =hidden_states + self.dropout(UpperCAmelCase		)

       return hidden_states





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		int     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		List[str]		)  ->  Tuple:


       '''simple docstring'''

       super().__init__()
       lowercase					:   str				  =Attention(query_dim=UpperCAmelCase     ,      heads=UpperCAmelCase     ,      dim_head=UpperCAmelCase     ,      out_bias=UpperCAmelCase     ,      scale_qk=UpperCAmelCase		)
       lowercase					:   Any				  =TaLayerNorm(UpperCAmelCase     ,      eps=UpperCAmelCase		)
       lowercase					:   Any				  =nn.Dropout(UpperCAmelCase		)






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		List[str]=None     ,      UpperCAmelCase			:		Any=None     ,      )  ->  int:


       '''simple docstring'''

       lowercase					:   List[str]				  =self.layer_norm(UpperCAmelCase		)
       lowercase					:   List[Any]				  =self.attention(
           UpperCAmelCase     ,      encoder_hidden_states=UpperCAmelCase     ,      attention_mask=attention_mask.squeeze(1		)     ,      )
       lowercase					:   Tuple				  =hidden_states + self.dropout(UpperCAmelCase		)
       return layer_output





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Dict     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		Tuple		)  ->  List[Any]:


       '''simple docstring'''

       super().__init__()
       lowercase					:   List[str]				  =TaDenseGatedActDense(d_model=UpperCAmelCase     ,      d_ff=UpperCAmelCase     ,      dropout_rate=UpperCAmelCase		)
       lowercase					:   str				  =TaFiLMLayer(in_features=d_model * 4     ,      out_features=UpperCAmelCase		)
       lowercase					:   Optional[Any]				  =TaLayerNorm(UpperCAmelCase     ,      eps=UpperCAmelCase		)
       lowercase					:   Any				  =nn.Dropout(UpperCAmelCase		)






      def 				A__      ( self			:		int     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		List[str]=None		)  ->  int:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.layer_norm(UpperCAmelCase		)
       if conditioning_emb is not None:
        lowercase					:   Tuple				  =self.film(UpperCAmelCase     ,      UpperCAmelCase		)

       lowercase					:   List[Any]				  =self.DenseReluDense(UpperCAmelCase		)
       lowercase					:   List[str]				  =hidden_states + self.dropout(UpperCAmelCase		)
       return hidden_states





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		int     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Optional[Any]		)  ->  Dict:


       '''simple docstring'''

       super().__init__()
       lowercase					:   List[str]				  =nn.Linear(UpperCAmelCase     ,      UpperCAmelCase     ,      bias=UpperCAmelCase		)
       lowercase					:   Dict				  =nn.Linear(UpperCAmelCase     ,      UpperCAmelCase     ,      bias=UpperCAmelCase		)
       lowercase					:   Optional[Any]				  =nn.Linear(UpperCAmelCase     ,      UpperCAmelCase     ,      bias=UpperCAmelCase		)
       lowercase					:   Optional[int]				  =nn.Dropout(UpperCAmelCase		)
       lowercase					:   Union[str, Any]				  =NewGELUActivation()






      def 				A__      ( self			:		List[str]     ,      UpperCAmelCase			:		Optional[Any]		)  ->  str:


       '''simple docstring'''

       lowercase					:   int				  =self.act(self.wi_a(UpperCAmelCase		)		)
       lowercase					:   Optional[Any]				  =self.wi_a(UpperCAmelCase		)
       lowercase					:   Dict				  =hidden_gelu * hidden_linear
       lowercase					:   Optional[int]				  =self.dropout(UpperCAmelCase		)

       lowercase					:   Union[str, Any]				  =self.wo(UpperCAmelCase		)
       return hidden_states





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		str     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		Tuple=1e-6		)  ->  Optional[int]:


       '''simple docstring'''

       super().__init__()
       lowercase					:   str				  =nn.Parameter(torch.ones(UpperCAmelCase		)		)
       lowercase					:   Union[str, Any]				  =eps






      def 				A__      ( self			:		List[Any]     ,      UpperCAmelCase			:		Any		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =hidden_states.to(torch.floataa		).pow(2		).mean(-1     ,      keepdim=UpperCAmelCase		)
       lowercase					:   Dict				  =hidden_states * torch.rsqrt(variance + self.variance_epsilon		)

       # convert into half-precision if necessary
       if self.weight.dtype in [torch.floataa, torch.bfloataa]:
        lowercase					:   Union[str, Any]				  =hidden_states.to(self.weight.dtype		)

       return self.weight * hidden_states





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		torch.Tensor		)  ->  torch.Tensor:


       '''simple docstring'''

       return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi		) * (input + 0.0_4_4_7_1_5 * torch.pow(UpperCAmelCase     ,      3.0		))		))





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Tuple     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		Tuple		)  ->  Any:


       '''simple docstring'''

       super().__init__()
       lowercase					:   Any				  =nn.Linear(UpperCAmelCase     ,      out_features * 2     ,      bias=UpperCAmelCase		)






      def 				A__      ( self			:		Optional[Any]     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		Optional[Any]		)  ->  str:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =self.scale_bias(UpperCAmelCase		)
       lowercase					:   Dict				  =torch.chunk(UpperCAmelCase     ,      2     ,      -1		)
       lowercase					:   Optional[int]				  =x * (1 + scale) + shift
       return x











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




      """simple docstring"""




      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =0






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


       '''simple docstring'''

       lowercase					:   Tuple				  =AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''		)
       self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)






      def 				A__      ( self			:		Any		)  ->  int:


       '''simple docstring'''

       with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase					:   int				  =Path(UpperCAmelCase		) / '''preprocessor_config.json'''
        lowercase					:   str				  =Path(UpperCAmelCase		) / '''config.json'''
        json.dump(
            {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,      open(UpperCAmelCase     ,      '''w'''		)     ,      )
        json.dump({'''model_type''': '''clip'''}     ,      open(UpperCAmelCase     ,      '''w'''		)		)

        lowercase					:   str				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		)
        self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)






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


       '''simple docstring'''

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

        lowercase					:   Optional[Any]				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		)
        self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)






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


       '''simple docstring'''

       with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase					:   str				  =CLIPConfig()

        # Create a dummy config file with image_proceesor_type
        lowercase					:   Optional[int]				  =Path(UpperCAmelCase		) / '''preprocessor_config.json'''
        lowercase					:   Optional[Any]				  =Path(UpperCAmelCase		) / '''config.json'''
        json.dump(
            {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,      open(UpperCAmelCase     ,      '''w'''		)     ,      )
        json.dump({'''model_type''': '''clip'''}     ,      open(UpperCAmelCase     ,      '''w'''		)		)

        # remove image_processor_type to make sure config.json alone is enough to load image processor locally
        lowercase					:   Dict				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		).to_dict()

        config_dict.pop('''image_processor_type'''		)
        lowercase					:   str				  =CLIPImageProcessor(**UpperCAmelCase		)

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

        lowercase					:   Optional[int]				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		)

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

       self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)






      def 				A__      ( self			:		str		)  ->  List[str]:


       '''simple docstring'''

       with tempfile.TemporaryDirectory() as tmpdirname:
        lowercase					:   Dict				  =Path(UpperCAmelCase		) / '''preprocessor_config.json'''
        json.dump(
            {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}     ,      open(UpperCAmelCase     ,      '''w'''		)     ,      )

        lowercase					:   Optional[Any]				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		)
        self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)






      def 				A__      ( self			:		int		)  ->  List[str]:


       '''simple docstring'''

       with self.assertRaisesRegex(
           UpperCAmelCase     ,      '''clip-base is not a local folder and is not a valid model identifier'''		):
        lowercase					:   Union[str, Any]				  =AutoImageProcessor.from_pretrained('''clip-base'''		)






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


       '''simple docstring'''

       with self.assertRaisesRegex(
           UpperCAmelCase     ,      R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''		):
        lowercase					:   Any				  =AutoImageProcessor.from_pretrained(UpperCAmelCase     ,      revision='''aaaaaa'''		)






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


       '''simple docstring'''

       with self.assertRaisesRegex(
           UpperCAmelCase     ,      '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''     ,      ):
        lowercase					:   Optional[int]				  =AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''		)






      def 				A__      ( self			:		List[str]		)  ->  str:


       '''simple docstring'''

       with self.assertRaises(UpperCAmelCase		):
        lowercase					:   Dict				  =AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''		)
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(UpperCAmelCase		):
        lowercase					:   List[str]				  =AutoImageProcessor.from_pretrained(
            '''hf-internal-testing/test_dynamic_image_processor'''     ,      trust_remote_code=UpperCAmelCase		)

       lowercase					:   Union[str, Any]				  =AutoImageProcessor.from_pretrained(
           '''hf-internal-testing/test_dynamic_image_processor'''     ,      trust_remote_code=UpperCAmelCase		)
       self.assertEqual(image_processor.__class__.__name__     ,      '''NewImageProcessor'''		)

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






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


       '''simple docstring'''

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

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

         lowercase					:   Optional[int]				  =CustomImageProcessor.from_pretrained(UpperCAmelCase		)

        # 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(UpperCAmelCase		)
         lowercase					:   Dict				  =AutoImageProcessor.from_pretrained(UpperCAmelCase		)
         self.assertIsInstance(UpperCAmelCase     ,      UpperCAmelCase		)

       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			:		Any		)  ->  Any:


       '''simple docstring'''

       class UpperCAmelCase_					(    __A				):




             """simple docstring"""




             UpperCamelCase_								=			True

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

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



