






"""simple docstring"""







import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCAmelCase_	:    Optional[int]            =      get_tests_dir('''fixtures/dummy-config.json''')





class   UpperCamelCase_ (       unittest.TestCase  ):



  def 		UpperCamelCase_				(      self				)			->			List[Any]:



         """simple docstring"""





         UpperCAmelCase	    =			0



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



         """simple docstring"""





         self.assertIsNotNone(transformers.models.auto.__spec__				)
         self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""				)				)



  def 		UpperCamelCase_				(      self				)			->			Any:



         """simple docstring"""





         UpperCAmelCase	    =			AutoConfig.from_pretrained("""bert-base-uncased"""				)
         self.assertIsInstance(snake_case__ ,		snake_case__				)



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



         """simple docstring"""





         UpperCAmelCase	    =			AutoConfig.from_pretrained(snake_case__				)
         self.assertIsInstance(snake_case__ ,		snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         UpperCAmelCase	    =			AutoConfig.from_pretrained(snake_case__				)
         self.assertIsInstance(snake_case__ ,		snake_case__				)



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



         """simple docstring"""





         UpperCAmelCase	    =			AutoConfig.for_model("""roberta"""				)
         self.assertIsInstance(snake_case__ ,		snake_case__				)



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



         """simple docstring"""





         with tempfile.TemporaryDirectory() as tmp_dir:
                # This model name contains bert and roberta, but roberta ends up being picked.
                UpperCAmelCase	    =			os.path.join(snake_case__ ,		"""fake-roberta"""				)
                os.makedirs(snake_case__ ,		exist_ok=snake_case__				)
                with open(os.path.join(snake_case__ ,		"""config.json"""				) ,		"""w"""				) as f:
                       f.write(json.dumps({}				)				)
                UpperCAmelCase	    =			AutoConfig.from_pretrained(snake_case__				)
                self.assertEqual(type(snake_case__				) ,		snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			str:



         """simple docstring"""





         try:
                AutoConfig.register("""custom""" ,		snake_case__				)
                # Wrong model type will raise an error
                with self.assertRaises(snake_case__				):
                       AutoConfig.register("""model""" ,		snake_case__				)
                # Trying to register something existing in the Transformers library will raise an error
                with self.assertRaises(snake_case__				):
                       AutoConfig.register("""bert""" ,		snake_case__				)

                # Now that the config is registered, it can be used as any other config with the auto-API
                UpperCAmelCase	    =			CustomConfig()
                with tempfile.TemporaryDirectory() as tmp_dir:
                       config.save_pretrained(snake_case__				)
                       UpperCAmelCase	    =			AutoConfig.from_pretrained(snake_case__				)
                       self.assertIsInstance(snake_case__ ,		snake_case__				)

         finally:
                if "custom" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["custom"]



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



         """simple docstring"""





         with self.assertRaisesRegex(
             snake_case__ ,		"""bert-base is not a local folder and is not a valid model identifier"""				):
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""bert-base"""				)



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



         """simple docstring"""





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



  def 		UpperCamelCase_				(      self				)			->			List[Any]:



         """simple docstring"""





         with self.assertRaisesRegex(
             snake_case__ ,		"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.""" ,		):
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""				)



  def 		UpperCamelCase_				(      self				)			->			Any:



         """simple docstring"""





         with self.assertRaises(snake_case__				):
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""				)
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(snake_case__				):
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,		trust_remote_code=snake_case__				)

         UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,		trust_remote_code=snake_case__				)
         self.assertEqual(config.__class__.__name__ ,		"""NewModelConfig"""				)

         # Test config can be reloaded.
         with tempfile.TemporaryDirectory() as tmp_dir:
                config.save_pretrained(snake_case__				)
                UpperCAmelCase	    =			AutoConfig.from_pretrained(snake_case__ ,		trust_remote_code=snake_case__				)
         self.assertEqual(reloaded_config.__class__.__name__ ,		"""NewModelConfig"""				)



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         class   UpperCamelCase_ (       a_  ):
           _A       :					Tuple				=	'new-model'

         try:
                AutoConfig.register("""new-model""" ,		snake_case__				)
                # If remote code is not set, the default is to use local
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""				)
                self.assertEqual(config.__class__.__name__ ,		"""NewModelConfigLocal"""				)

                # If remote code is disabled, we load the local one.
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,		trust_remote_code=snake_case__				)
                self.assertEqual(config.__class__.__name__ ,		"""NewModelConfigLocal"""				)

                # If remote is enabled, we load from the Hub
                UpperCAmelCase	    =			AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model""" ,		trust_remote_code=snake_case__				)
                self.assertEqual(config.__class__.__name__ ,		"""NewModelConfig"""				)

         finally:
                if "new-model" in CONFIG_MAPPING._extra_content:
                       del CONFIG_MAPPING._extra_content["new-model"]








"""simple docstring"""







import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding





class   UpperCamelCase_ (       a_  ):
  _A       :					Optional[int]				=	['image_processor', 'tokenizer']
  _A       :					Optional[Any]				=	'ViTImageProcessor'
  _A       :					Tuple				=	('CLIPTokenizer', 'CLIPTokenizerFast')



  def __init__(      self ,		snake_case__=None ,		snake_case__=None ,		**snake_case__				)			->			Union[str, Any]:



         """simple docstring"""





         UpperCAmelCase	    =			None
         if "feature_extractor" in kwargs:
                warnings.warn(
                    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                    """ instead.""" ,		snake_case__ ,		)
                UpperCAmelCase	    =			kwargs.pop("""feature_extractor"""				)

         UpperCAmelCase	    =			image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
                raise ValueError("""You need to specify an `image_processor`."""				)
         if tokenizer is None:
                raise ValueError("""You need to specify a `tokenizer`."""				)

         super().__init__(snake_case__ ,		snake_case__				)



  def __call__(      self ,		snake_case__=None ,		snake_case__=None ,		snake_case__=None ,		snake_case__=None ,		**snake_case__				)			->			List[str]:



         """simple docstring"""





         if text is None and visual_prompt is None and images is None:
                raise ValueError("""You have to specify either text, visual prompt or images."""				)

         if text is not None and visual_prompt is not None:
                raise ValueError("""You have to specify exactly one type of prompt. Either text or visual prompt."""				)

         if text is not None:
                UpperCAmelCase	    =			self.tokenizer(snake_case__ ,		return_tensors=snake_case__ ,		**snake_case__				)

         if visual_prompt is not None:
                UpperCAmelCase	    =			self.image_processor(snake_case__ ,		return_tensors=snake_case__ ,		**snake_case__				)

         if images is not None:
                UpperCAmelCase	    =			self.image_processor(snake_case__ ,		return_tensors=snake_case__ ,		**snake_case__				)

         if visual_prompt is not None and images is not None:
                UpperCAmelCase	    =			{
                    """pixel_values""": image_features.pixel_values,
                    """conditional_pixel_values""": prompt_features.pixel_values,
                }
                return encoding
         elif text is not None and images is not None:
                UpperCAmelCase	    =			image_features.pixel_values
                return encoding
         elif text is not None:
                return encoding
         elif visual_prompt is not None:
                UpperCAmelCase	    =			{
                    """conditional_pixel_values""": prompt_features.pixel_values,
                }
                return encoding
         else:
                return BatchEncoding(data=dict(**snake_case__				) ,		tensor_type=snake_case__				)



  def 		UpperCamelCase_				(      self ,		*snake_case__ ,		**snake_case__				)			->			Tuple:



         """simple docstring"""





         return self.tokenizer.batch_decode(*snake_case__ ,		**snake_case__				)



  def 		UpperCamelCase_				(      self ,		*snake_case__ ,		**snake_case__				)			->			Optional[int]:



         """simple docstring"""





         return self.tokenizer.decode(*snake_case__ ,		**snake_case__				)



  @property
  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         warnings.warn(
             """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" ,		snake_case__ ,		)
         return self.image_processor_class



  @property
  def 		UpperCamelCase_				(      self				)			->			Any:



         """simple docstring"""





         warnings.warn(
             """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" ,		snake_case__ ,		)
         return self.image_processor
