






import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
      from transformers.models.mobilevitva.modeling_mobilevitva import (
          MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
          make_divisible,
      )


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor
class UpperCAmelCase_					(    SCREAMING_SNAKE_CASE_				):




      """simple docstring"""




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


       '''simple docstring'''

       lowercase					:   List[str]				  =self.config_class(**self.inputs_dict		)
       self.parent.assertTrue(hasattr(UpperCamelCase__     ,      '''width_multiplier'''		)		)





class UpperCAmelCase_					:




      """simple docstring"""




      def __init__( self			:		List[Any]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Tuple=13     ,      UpperCAmelCase			:		Dict=64     ,      UpperCAmelCase			:		List[str]=2     ,      UpperCAmelCase			:		Tuple=3     ,      UpperCAmelCase			:		Dict="swish"     ,      UpperCAmelCase			:		str=3     ,      UpperCAmelCase			:		int=32     ,      UpperCAmelCase			:		Any=0.1     ,      UpperCAmelCase			:		Dict=0.0_2     ,      UpperCAmelCase			:		Optional[Any]=True     ,      UpperCAmelCase			:		List[Any]=True     ,      UpperCAmelCase			:		Dict=10     ,      UpperCAmelCase			:		Union[str, Any]=None     ,      UpperCAmelCase			:		Optional[int]=0.2_5     ,      UpperCAmelCase			:		Optional[Any]=0.0     ,      UpperCAmelCase			:		Tuple=0.0     ,      )  ->  Dict:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =parent
       lowercase					:   List[str]				  =batch_size
       lowercase					:   str				  =image_size
       lowercase					:   Dict				  =patch_size
       lowercase					:   Optional[int]				  =num_channels
       lowercase					:   List[Any]				  =make_divisible(512 * width_multiplier     ,      divisor=8		)
       lowercase					:   Optional[Any]				  =hidden_act
       lowercase					:   Any				  =conv_kernel_size
       lowercase					:   str				  =output_stride
       lowercase					:   Any				  =classifier_dropout_prob
       lowercase					:   Union[str, Any]				  =use_labels
       lowercase					:   str				  =is_training
       lowercase					:   Tuple				  =num_labels
       lowercase					:   str				  =initializer_range
       lowercase					:   List[Any]				  =scope
       lowercase					:   List[str]				  =width_multiplier
       lowercase					:   int				  =ffn_dropout
       lowercase					:   Union[str, Any]				  =attn_dropout






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


       '''simple docstring'''

       lowercase					:   Dict				  =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       lowercase					:   Union[str, Any]				  =None
       lowercase					:   Optional[Any]				  =None
       if self.use_labels:
        lowercase					:   str				  =ids_tensor([self.batch_size]     ,      self.num_labels		)
        lowercase					:   Optional[Any]				  =ids_tensor([self.batch_size, self.image_size, self.image_size]     ,      self.num_labels		)

       lowercase					:   Any				  =self.get_config()

       return config, pixel_values, labels, pixel_labels






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


       '''simple docstring'''

       return MobileViTVaConfig(
           image_size=self.image_size     ,      patch_size=self.patch_size     ,      num_channels=self.num_channels     ,      hidden_act=self.hidden_act     ,      conv_kernel_size=self.conv_kernel_size     ,      output_stride=self.output_stride     ,      classifier_dropout_prob=self.classifier_dropout_prob     ,      initializer_range=self.initializer_range     ,      width_multiplier=self.width_multiplier     ,      ffn_dropout=self.ffn_dropout_prob     ,      attn_dropout=self.attn_dropout_prob     ,      )






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


       '''simple docstring'''

       lowercase					:   str				  =MobileViTVaModel(config=UpperCamelCase__		)
       model.to(UpperCamelCase__		)
       model.eval()
       lowercase					:   Dict				  =model(UpperCamelCase__		)
       self.parent.assertEqual(
           result.last_hidden_state.shape     ,      (
               self.batch_size,
               self.last_hidden_size,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )     ,      )






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


       '''simple docstring'''

       lowercase					:   Dict				  =self.num_labels
       lowercase					:   List[Any]				  =MobileViTVaForImageClassification(UpperCamelCase__		)
       model.to(UpperCamelCase__		)
       model.eval()
       lowercase					:   Union[str, Any]				  =model(UpperCamelCase__     ,      labels=UpperCamelCase__		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_labels)		)






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


       '''simple docstring'''

       lowercase					:   Any				  =self.num_labels
       lowercase					:   Optional[Any]				  =MobileViTVaForSemanticSegmentation(UpperCamelCase__		)
       model.to(UpperCamelCase__		)
       model.eval()
       lowercase					:   Union[str, Any]				  =model(UpperCamelCase__		)
       self.parent.assertEqual(
           result.logits.shape     ,      (
               self.batch_size,
               self.num_labels,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )     ,      )
       lowercase					:   Union[str, Any]				  =model(UpperCamelCase__     ,      labels=UpperCamelCase__		)
       self.parent.assertEqual(
           result.logits.shape     ,      (
               self.batch_size,
               self.num_labels,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )     ,      )






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


       '''simple docstring'''

       lowercase					:   List[str]				  =self.prepare_config_and_inputs()
       lowercase					:   Dict				  =config_and_inputs
       lowercase					:   Tuple				  ={'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_torch
class UpperCAmelCase_					(    SCREAMING_SNAKE_CASE_				,       SCREAMING_SNAKE_CASE_				,       unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			(
          (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
          if is_torch_available()
          else ()
      )

      UpperCamelCase_								=			(
          {
              '''feature-extraction''': MobileViTVaModel,
              '''image-classification''': MobileViTVaForImageClassification,
              '''image-segmentation''': MobileViTVaForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False






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


       '''simple docstring'''

       lowercase					:   List[str]				  =MobileViTVaModelTester(self		)
       lowercase					:   int				  =MobileViTVaConfigTester(self     ,      config_class=UpperCamelCase__     ,      has_text_modality=UpperCamelCase__		)






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


       '''simple docstring'''

       self.config_tester.run_common_tests()






      @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds'''		)
      def 				A__      ( self			:		Optional[Any]		)  ->  Union[str, Any]:


       '''simple docstring'''

       pass






      @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''		)
      def 				A__      ( self			:		Tuple		)  ->  List[str]:


       '''simple docstring'''

       pass






      @unittest.skip(reason='''MobileViTV2 does not output attentions'''		)
      def 				A__      ( self			:		Optional[int]		)  ->  Tuple:


       '''simple docstring'''

       pass






      @require_torch_multi_gpu
      @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.'''		)
      def 				A__      ( self			:		Dict		)  ->  Any:


       '''simple docstring'''

       pass






      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''		)
      def 				A__      ( self			:		List[Any]		)  ->  List[str]:


       '''simple docstring'''

       pass






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


       '''simple docstring'''

       lowercase					:   str				  =self.model_tester.prepare_config_and_inputs_for_common()

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

        lowercase					:   List[Any]				  =['''pixel_values''']
        self.assertListEqual(arg_names[:1]     ,      UpperCamelCase__		)






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


       '''simple docstring'''

       lowercase					:   List[str]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__		)






      def 				A__      ( self			:		int		)  ->  str:


       '''simple docstring'''

       def check_hidden_states_output(UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		Union[str, Any]		):
        lowercase					:   Optional[Any]				  =model_class(UpperCamelCase__		)
        model.to(UpperCamelCase__		)
        model.eval()

        with torch.no_grad():
         lowercase					:   Tuple				  =model(**self._prepare_for_class(UpperCamelCase__     ,      UpperCamelCase__		)		)

        lowercase					:   Union[str, Any]				  =outputs.hidden_states

        lowercase					:   Any				  =5
        self.assertEqual(len(UpperCamelCase__		)     ,      UpperCamelCase__		)

        # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        lowercase					:   str				  =2
        for i in range(len(UpperCamelCase__		)		):
         self.assertListEqual(
             list(hidden_states[i].shape[-2:]		)     ,      [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]     ,      )
         divisor *= 2

        self.assertEqual(self.model_tester.output_stride     ,      divisor // 2		)

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

       for model_class in self.all_model_classes:
        lowercase					:   Optional[Any]				  =True
        check_hidden_states_output(UpperCamelCase__     ,      UpperCamelCase__     ,      UpperCamelCase__		)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowercase					:   List[Any]				  =True

        check_hidden_states_output(UpperCamelCase__     ,      UpperCamelCase__     ,      UpperCamelCase__		)






      def 				A__      ( self			:		Tuple		)  ->  int:


       '''simple docstring'''

       lowercase					:   int				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__		)






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


       '''simple docstring'''

       lowercase					:   int				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__		)






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


       '''simple docstring'''

       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase					:   Optional[int]				  =MobileViTVaModel.from_pretrained(UpperCamelCase__		)
        self.assertIsNotNone(UpperCamelCase__		)





def 							lowercase_				(    )       ->      Dict:



 """simple docstring"""




 lowercase					:   str				  =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
 return image





@require_torch
@require_vision
class UpperCAmelCase_					(    unittest.TestCase				):




      """simple docstring"""




      @cached_property
      def 				A__      ( self			:		Any		)  ->  Tuple:


       '''simple docstring'''

       return (
           MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''		)
           if is_vision_available()
           else None
       )






      @slow
      def 				A__      ( self			:		Any		)  ->  int:


       '''simple docstring'''

       lowercase					:   int				  =MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''		).to(
           UpperCamelCase__		)

       lowercase					:   Dict				  =self.default_image_processor
       lowercase					:   List[Any]				  =prepare_img()
       lowercase					:   List[str]				  =image_processor(images=UpperCamelCase__     ,      return_tensors='''pt'''		).to(UpperCamelCase__		)

       # forward pass
       with torch.no_grad():
        lowercase					:   List[Any]				  =model(**UpperCamelCase__		)

       # verify the logits
       lowercase					:   int				  =torch.Size((1, 1000)		)
       self.assertEqual(outputs.logits.shape     ,      UpperCamelCase__		)

       lowercase					:   List[Any]				  =torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01]		).to(UpperCamelCase__		)

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






      @slow
      def 				A__      ( self			:		Any		)  ->  str:


       '''simple docstring'''

       lowercase					:   int				  =MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)
       lowercase					:   int				  =model.to(UpperCamelCase__		)

       lowercase					:   str				  =MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)

       lowercase					:   List[str]				  =prepare_img()
       lowercase					:   int				  =image_processor(images=UpperCamelCase__     ,      return_tensors='''pt'''		).to(UpperCamelCase__		)

       # forward pass
       with torch.no_grad():
        lowercase					:   Dict				  =model(**UpperCamelCase__		)
       lowercase					:   Any				  =outputs.logits

       # verify the logits
       lowercase					:   Any				  =torch.Size((1, 21, 32, 32)		)
       self.assertEqual(logits.shape     ,      UpperCamelCase__		)

       lowercase					:   Optional[int]				  =torch.tensor(
           [
               [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
               [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
               [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
           ]     ,      device=UpperCamelCase__     ,      )

       self.assertTrue(torch.allclose(logits[0, :3, :3, :3]     ,      UpperCamelCase__     ,      atol=1e-4		)		)






      @slow
      def 				A__      ( self			:		Any		)  ->  Any:


       '''simple docstring'''

       lowercase					:   str				  =MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)
       lowercase					:   Tuple				  =model.to(UpperCamelCase__		)

       lowercase					:   int				  =MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''		)

       lowercase					:   Tuple				  =prepare_img()
       lowercase					:   Optional[Any]				  =image_processor(images=UpperCamelCase__     ,      return_tensors='''pt'''		).to(UpperCamelCase__		)

       # forward pass
       with torch.no_grad():
        lowercase					:   Union[str, Any]				  =model(**UpperCamelCase__		)

       lowercase					:   Optional[int]				  =outputs.logits.detach().cpu()

       lowercase					:   List[str]				  =image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__     ,      target_sizes=[(50, 60)]		)
       lowercase					:   Union[str, Any]				  =torch.Size((50, 60)		)
       self.assertEqual(segmentation[0].shape     ,      UpperCamelCase__		)

       lowercase					:   List[str]				  =image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__		)
       lowercase					:   str				  =torch.Size((32, 32)		)
       self.assertEqual(segmentation[0].shape     ,      UpperCamelCase__		)











'''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]



