from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


__lowercase										= logging.get_logger(__name__)

# General docstring
__lowercase										= '''RegNetConfig'''

# Base docstring
__lowercase										= '''facebook/regnet-y-040'''
__lowercase										= [1, 1088, 7, 7]

# Image classification docstring
__lowercase										= '''facebook/regnet-y-040'''
__lowercase										= '''tabby, tabby cat'''

__lowercase										= [
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase			,			__lowercase = 3			,			__lowercase = 1			,			__lowercase = 1			,			__lowercase = "relu"			,			)	->     Dict:
        super().__init__()
        __UpperCamelCase					:Optional[int]        =		nn.Convad(
            __lowercase			,			__lowercase			,			kernel_size=__lowercase			,			stride=__lowercase			,			padding=kernel_size // 2			,			groups=__lowercase			,			bias=__lowercase			,			)
        __UpperCamelCase					:Tuple        =		nn.BatchNormad(__lowercase)
        __UpperCamelCase					:Any        =		ACTaFN[activation] if activation is not None else nn.Identity()







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Optional[Any]:
        __UpperCamelCase					:str        =		self.convolution(__lowercase)
        __UpperCamelCase					:Optional[Any]        =		self.normalization(__lowercase)
        __UpperCamelCase					:List[str]        =		self.activation(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase)	->     Any:
        super().__init__()
        __UpperCamelCase					:Any        =		RegNetConvLayer(
            config.num_channels			,			config.embedding_size			,			kernel_size=3			,			stride=2			,			activation=config.hidden_act)
        __UpperCamelCase					:Optional[int]        =		config.num_channels







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Union[str, Any]:
        __UpperCamelCase					:str        =		pixel_values.shape[1]
        if num_channels != self.num_channels:
            raise ValueError(
                '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''')
        __UpperCamelCase					:Any        =		self.embedder(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase			,			__lowercase = 2)	->     Optional[Any]:
        super().__init__()
        __UpperCamelCase					:Dict        =		nn.Convad(__lowercase			,			__lowercase			,			kernel_size=1			,			stride=__lowercase			,			bias=__lowercase)
        __UpperCamelCase					:str        =		nn.BatchNormad(__lowercase)







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Tensor:
        __UpperCamelCase					:Any        =		self.convolution(__lowercase)
        __UpperCamelCase					:Optional[Any]        =		self.normalization(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase)	->     int:
        super().__init__()

        __UpperCamelCase					:List[str]        =		nn.AdaptiveAvgPoolad((1, 1))
        __UpperCamelCase					:Union[str, Any]        =		nn.Sequential(
            nn.Convad(__lowercase			,			__lowercase			,			kernel_size=1)			,			nn.ReLU()			,			nn.Convad(__lowercase			,			__lowercase			,			kernel_size=1)			,			nn.Sigmoid()			,			)







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Any:
        # b c h w -> b c 1 1
        __UpperCamelCase					:str        =		self.pooler(__lowercase)
        __UpperCamelCase					:List[Any]        =		self.attention(__lowercase)
        __UpperCamelCase					:Union[str, Any]        =		hidden_state * attention
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase = 1)	->     List[str]:
        super().__init__()
        __UpperCamelCase					:Tuple        =		in_channels != out_channels or stride != 1
        __UpperCamelCase					:Optional[int]        =		max(1			,			out_channels // config.groups_width)
        __UpperCamelCase					:Optional[int]        =		(
            RegNetShortCut(__lowercase			,			__lowercase			,			stride=__lowercase) if should_apply_shortcut else nn.Identity()
        )
        __UpperCamelCase					:Optional[int]        =		nn.Sequential(
            RegNetConvLayer(__lowercase			,			__lowercase			,			kernel_size=1			,			activation=config.hidden_act)			,			RegNetConvLayer(__lowercase			,			__lowercase			,			stride=__lowercase			,			groups=__lowercase			,			activation=config.hidden_act)			,			RegNetConvLayer(__lowercase			,			__lowercase			,			kernel_size=1			,			activation=__lowercase)			,			)
        __UpperCamelCase					:Dict        =		ACTaFN[config.hidden_act]







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Union[str, Any]:
        __UpperCamelCase					:Dict        =		hidden_state
        __UpperCamelCase					:int        =		self.layer(__lowercase)
        __UpperCamelCase					:List[str]        =		self.shortcut(__lowercase)
        hidden_state += residual
        __UpperCamelCase					:Any        =		self.activation(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase = 1)	->     Tuple:
        super().__init__()
        __UpperCamelCase					:List[Any]        =		in_channels != out_channels or stride != 1
        __UpperCamelCase					:Optional[Any]        =		max(1			,			out_channels // config.groups_width)
        __UpperCamelCase					:List[Any]        =		(
            RegNetShortCut(__lowercase			,			__lowercase			,			stride=__lowercase) if should_apply_shortcut else nn.Identity()
        )
        __UpperCamelCase					:List[str]        =		nn.Sequential(
            RegNetConvLayer(__lowercase			,			__lowercase			,			kernel_size=1			,			activation=config.hidden_act)			,			RegNetConvLayer(__lowercase			,			__lowercase			,			stride=__lowercase			,			groups=__lowercase			,			activation=config.hidden_act)			,			RegNetSELayer(__lowercase			,			reduced_channels=int(round(in_channels / 4)))			,			RegNetConvLayer(__lowercase			,			__lowercase			,			kernel_size=1			,			activation=__lowercase)			,			)
        __UpperCamelCase					:List[str]        =		ACTaFN[config.hidden_act]







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Any:
        __UpperCamelCase					:List[str]        =		hidden_state
        __UpperCamelCase					:str        =		self.layer(__lowercase)
        __UpperCamelCase					:Optional[int]        =		self.shortcut(__lowercase)
        hidden_state += residual
        __UpperCamelCase					:Optional[int]        =		self.activation(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase = 2			,			__lowercase = 2			,			)	->     str:
        super().__init__()

        __UpperCamelCase					:Tuple        =		RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

        __UpperCamelCase					:Any        =		nn.Sequential(
            # downsampling is done in the first layer with stride of 2
            layer(
                __lowercase			,			__lowercase			,			__lowercase			,			stride=__lowercase			,			)			,			*[layer(__lowercase			,			__lowercase			,			__lowercase) for _ in range(depth - 1)]			,			)







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Dict:
        __UpperCamelCase					:str        =		self.layers(__lowercase)
        return hidden_state


class      lowerCamelCase_					(       nn.Module			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase)	->     Tuple:
        super().__init__()
        __UpperCamelCase					:int        =		nn.ModuleList([])
        # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
        self.stages.append(
            RegNetStage(
                __lowercase			,			config.embedding_size			,			config.hidden_sizes[0]			,			stride=2 if config.downsample_in_first_stage else 1			,			depth=config.depths[0]			,			))
        __UpperCamelCase					:List[str]        =		zip(config.hidden_sizes			,			config.hidden_sizes[1:])
        for (in_channels, out_channels), depth in zip(__lowercase			,			config.depths[1:]):
            self.stages.append(RegNetStage(__lowercase			,			__lowercase			,			__lowercase			,			depth=__lowercase))







    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase = False			,			__lowercase = True)	->     BaseModelOutputWithNoAttention:
        __UpperCamelCase					:Tuple        =		() if output_hidden_states else None

        for stage_module in self.stages:
            if output_hidden_states:
                __UpperCamelCase					:List[str]        =		hidden_states + (hidden_state,)

            __UpperCamelCase					:Optional[Any]        =		stage_module(__lowercase)

        if output_hidden_states:
            __UpperCamelCase					:List[Any]        =		hidden_states + (hidden_state,)

        if not return_dict:
            return tuple(v for v in [hidden_state, hidden_states] if v is not None)

        return BaseModelOutputWithNoAttention(last_hidden_state=__lowercase			,			hidden_states=__lowercase)


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    a__     :						Optional[int]      =				RegNetConfig
    a__     :						Dict      =				"""regnet"""
    a__     :						Any      =				"""pixel_values"""
    a__     :						Optional[Any]      =				True







    def       UpperCamelCase__       (     self			,			__lowercase)	->     List[str]:
        if isinstance(__lowercase			,			nn.Convad):
            nn.init.kaiming_normal_(module.weight			,			mode='''fan_out'''			,			nonlinearity='''relu''')
        elif isinstance(__lowercase			,			(nn.BatchNormad, nn.GroupNorm)):
            nn.init.constant_(module.weight			,			1)
            nn.init.constant_(module.bias			,			0)







    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase=False)	->     int:
        if isinstance(__lowercase			,			__lowercase):
            __UpperCamelCase					:Any        =		value
__lowercase										= r'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

__lowercase										= r'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
'''


@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top."""						,     UpperCAmelCase_						,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase)	->     Optional[int]:
        super().__init__(__lowercase)
        __UpperCamelCase					:str        =		config
        __UpperCamelCase					:str        =		RegNetEmbeddings(__lowercase)
        __UpperCamelCase					:Optional[Any]        =		RegNetEncoder(__lowercase)
        __UpperCamelCase					:Tuple        =		nn.AdaptiveAvgPoolad((1, 1))
        # Initialize weights and apply final processing
        self.post_init()







    @add_start_docstrings_to_model_forward(__lowercase)
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC			,			output_type=__lowercase			,			config_class=_CONFIG_FOR_DOC			,			modality='''vision'''			,			expected_output=_EXPECTED_OUTPUT_SHAPE			,			)
    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase = None			,			__lowercase = None)	->     BaseModelOutputWithPoolingAndNoAttention:
        __UpperCamelCase					:int        =		(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        __UpperCamelCase					:Tuple        =		return_dict if return_dict is not None else self.config.use_return_dict

        __UpperCamelCase					:str        =		self.embedder(__lowercase)

        __UpperCamelCase					:List[str]        =		self.encoder(
            __lowercase			,			output_hidden_states=__lowercase			,			return_dict=__lowercase)

        __UpperCamelCase					:Union[str, Any]        =		encoder_outputs[0]

        __UpperCamelCase					:str        =		self.pooler(__lowercase)

        if not return_dict:
            return (last_hidden_state, pooled_output) + encoder_outputs[1:]

        return BaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=__lowercase			,			pooler_output=__lowercase			,			hidden_states=encoder_outputs.hidden_states			,			)


@add_start_docstrings(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """						,     UpperCAmelCase_						,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase)	->     Union[str, Any]:
        super().__init__(__lowercase)
        __UpperCamelCase					:int        =		config.num_labels
        __UpperCamelCase					:str        =		RegNetModel(__lowercase)
        # classification head
        __UpperCamelCase					:Any        =		nn.Sequential(
            nn.Flatten()			,			nn.Linear(config.hidden_sizes[-1]			,			config.num_labels) if config.num_labels > 0 else nn.Identity()			,			)
        # initialize weights and apply final processing
        self.post_init()







    @add_start_docstrings_to_model_forward(__lowercase)
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT			,			output_type=__lowercase			,			config_class=_CONFIG_FOR_DOC			,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,			)
    def       UpperCamelCase__       (     self			,			__lowercase = None			,			__lowercase = None			,			__lowercase = None			,			__lowercase = None			,			)	->     ImageClassifierOutputWithNoAttention:
        __UpperCamelCase					:Tuple        =		return_dict if return_dict is not None else self.config.use_return_dict

        __UpperCamelCase					:Any        =		self.regnet(__lowercase			,			output_hidden_states=__lowercase			,			return_dict=__lowercase)

        __UpperCamelCase					:Union[str, Any]        =		outputs.pooler_output if return_dict else outputs[1]

        __UpperCamelCase					:List[Any]        =		self.classifier(__lowercase)

        __UpperCamelCase					:str        =		None

        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    __UpperCamelCase					:Dict        =		'''regression'''
                elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                    __UpperCamelCase					:Union[str, Any]        =		'''single_label_classification'''
                else:
                    __UpperCamelCase					:Any        =		'''multi_label_classification'''
            if self.config.problem_type == "regression":
                __UpperCamelCase					:List[str]        =		MSELoss()
                if self.num_labels == 1:
                    __UpperCamelCase					:Any        =		loss_fct(logits.squeeze()			,			labels.squeeze())
                else:
                    __UpperCamelCase					:str        =		loss_fct(__lowercase			,			__lowercase)
            elif self.config.problem_type == "single_label_classification":
                __UpperCamelCase					:List[str]        =		CrossEntropyLoss()
                __UpperCamelCase					:Optional[Any]        =		loss_fct(logits.view(-1			,			self.num_labels)			,			labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                __UpperCamelCase					:Optional[int]        =		BCEWithLogitsLoss()
                __UpperCamelCase					:List[str]        =		loss_fct(__lowercase			,			__lowercase)

        if not return_dict:
            __UpperCamelCase					:List[str]        =		(logits,) + outputs[2:]
            return (loss,) + output if loss is not None else output

        return ImageClassifierOutputWithNoAttention(loss=__lowercase			,			logits=__lowercase			,			hidden_states=outputs.hidden_states)






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       UpperCamelCase__       (     self)	->     int:
        __UpperCamelCase					:str        =		0







    def       UpperCamelCase__       (     self)	->     Optional[Any]:
        __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''')
        self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:int        =		Path(__lowercase) / '''preprocessor_config.json'''
            __UpperCamelCase					:Dict        =		Path(__lowercase) / '''config.json'''
            json.dump(
                {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
            json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

            __UpperCamelCase					:Union[str, Any]        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Union[str, Any]:
        # Ensure we can load the image processor from the feature extractor config
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:str        =		Path(__lowercase) / '''preprocessor_config.json'''
            __UpperCamelCase					:Union[str, Any]        =		Path(__lowercase) / '''config.json'''
            json.dump(
                {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
            json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

            __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:int        =		CLIPConfig()

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

            # remove image_processor_type to make sure config.json alone is enough to load image processor locally
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained(__lowercase).to_dict()

            config_dict.pop('''image_processor_type''')
            __UpperCamelCase					:List[str]        =		CLIPImageProcessor(**__lowercase)

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

            __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained(__lowercase)

            # make sure private variable is not incorrectly saved
            __UpperCamelCase					:Union[str, Any]        =		json.loads(config.to_json_string())
            self.assertTrue('''_processor_class''' not in dict_as_saved)

        self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     List[str]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:Tuple        =		Path(__lowercase) / '''preprocessor_config.json'''
            json.dump(
                {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)

            __UpperCamelCase					:List[str]        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with self.assertRaisesRegex(
            __lowercase			,			'''clip-base is not a local folder and is not a valid model identifier'''):
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained('''clip-base''')







    def       UpperCamelCase__       (     self)	->     List[Any]:
        with self.assertRaisesRegex(
            __lowercase			,			r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
            __UpperCamelCase					:str        =		AutoImageProcessor.from_pretrained(__lowercase			,			revision='''aaaaaa''')







    def       UpperCamelCase__       (     self)	->     List[str]:
        with self.assertRaisesRegex(
            __lowercase			,			'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''			,			):
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''')







    def       UpperCamelCase__       (     self)	->     str:
        # If remote code is not set, we will time out when asking whether to load the model.
        with self.assertRaises(__lowercase):
            __UpperCamelCase					: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(__lowercase):
            __UpperCamelCase					:List[Any]        =		AutoImageProcessor.from_pretrained(
                '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)

        __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained(
            '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)
        self.assertEqual(image_processor.__class__.__name__			,			'''NewImageProcessor''')

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







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

            with tempfile.TemporaryDirectory() as tmpdirname:
                __UpperCamelCase					:int        =		Path(__lowercase) / '''preprocessor_config.json'''
                __UpperCamelCase					:List[str]        =		Path(__lowercase) / '''config.json'''
                json.dump(
                    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
                json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

                __UpperCamelCase					:int        =		CustomImageProcessor.from_pretrained(__lowercase)

            # 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(__lowercase)
                __UpperCamelCase					:int        =		AutoImageProcessor.from_pretrained(__lowercase)
                self.assertIsInstance(__lowercase			,			__lowercase)

        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       UpperCamelCase__       (     self)	->     List[Any]:


        class      lowerCamelCase_					(       UpperCAmelCase_			):






            '''simple docstring'''






            a__     :						List[str]      =				True

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

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





