
import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
					from ...processing_utils import ProcessorMixin
					from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE							:Dict							 =				logging.get_logger(__name__)

SCREAMING_SNAKE_CASE							:Optional[Any]							 =				{
    'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json',
    'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json',
    'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json',
}





class 							UpperCAmelCase      (  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_					    =     "owlvit_text_model"






	def __init__(       self					: Dict							,A					: Any=4_94_08							,A					: Optional[Any]=5_12							,A					: Optional[Any]=20_48							,A					: int=12							,A					: List[Any]=8							,A					: str=16							,A					: Dict="quick_gelu"							,A					: str=1E-5							,A					: Dict=0.0							,A					: str=0.02							,A					: List[Any]=1.0							,A					: List[Any]=0							,A					: int=4_94_06							,A					: List[Any]=4_94_07							,**A					: List[str]							,):
					super().__init__(pad_token_id=A							,bos_token_id=A							,eos_token_id=A							,**A )

					__A   			= vocab_size
					__A   			= hidden_size
					__A   			= intermediate_size
					__A   			= num_hidden_layers
					__A   			= num_attention_heads
					__A   			= max_position_embeddings
					__A   			= hidden_act
					__A   			= layer_norm_eps
					__A   			= attention_dropout
					__A   			= initializer_range
					__A   			= initializer_factor







	@classmethod
	def 				UpperCamelCase_  (       cls					: List[str]							,A					: Union[str, os.PathLike]							,**A					: Optional[Any] ):
					cls._set_token_in_kwargs(A )

					__A			,							__A   			= cls.get_config_dict(A							,**A )

					# get the text config dict if we are loading from OwlViTConfig
					if config_dict.get("model_type" ) == "owlvit":
									__A   			= config_dict["text_config"]

					if "model_type" in config_dict and hasattr(cls							,"model_type" ) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
									    f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )

					return cls.from_dict(A							,**A )





class 							UpperCAmelCase      (  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_					    =     "owlvit_vision_model"






	def __init__(       self					: List[Any]							,A					: str=7_68							,A					: Tuple=30_72							,A					: List[str]=12							,A					: str=12							,A					: List[str]=3							,A					: List[str]=7_68							,A					: Optional[Any]=32							,A					: Optional[int]="quick_gelu"							,A					: List[str]=1E-5							,A					: Optional[int]=0.0							,A					: Union[str, Any]=0.02							,A					: Optional[Any]=1.0							,**A					: Union[str, Any]							,):
					super().__init__(**A )

					__A   			= hidden_size
					__A   			= intermediate_size
					__A   			= num_hidden_layers
					__A   			= num_attention_heads
					__A   			= num_channels
					__A   			= image_size
					__A   			= patch_size
					__A   			= hidden_act
					__A   			= layer_norm_eps
					__A   			= attention_dropout
					__A   			= initializer_range
					__A   			= initializer_factor







	@classmethod
	def 				UpperCamelCase_  (       cls					: Union[str, Any]							,A					: Union[str, os.PathLike]							,**A					: List[Any] ):
					cls._set_token_in_kwargs(A )

					__A			,							__A   			= cls.get_config_dict(A							,**A )

					# get the vision config dict if we are loading from OwlViTConfig
					if config_dict.get("model_type" ) == "owlvit":
									__A   			= config_dict["vision_config"]

					if "model_type" in config_dict and hasattr(cls							,"model_type" ) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
									    f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )

					return cls.from_dict(A							,**A )





class 							UpperCAmelCase      (  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_					    =     "owlvit"
	snake_case_					    =     True






	def __init__(       self					: Any							,A					: List[Any]=None							,A					: Tuple=None							,A					: Optional[Any]=5_12							,A					: Tuple=2.65_92							,A					: Dict=True							,**A					: Optional[Any]							,):
					super().__init__(**A )

					if text_config is None:
									__A   			= {}
									logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." )

					if vision_config is None:
									__A   			= {}
									logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." )

					__A   			= OwlViTTextConfig(**A )
					__A   			= OwlViTVisionConfig(**A )

					__A   			= projection_dim
					__A   			= logit_scale_init_value
					__A   			= return_dict
					__A   			= 1.0






	@classmethod
	def 				UpperCamelCase_  (       cls					: List[Any]							,A					: Union[str, os.PathLike]							,**A					: List[Any] ):
					cls._set_token_in_kwargs(A )

					__A			,							__A   			= cls.get_config_dict(A							,**A )

					if "model_type" in config_dict and hasattr(cls							,"model_type" ) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
									    f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )

					return cls.from_dict(A							,**A )






	@classmethod
	def 				UpperCamelCase_  (       cls					: Dict							,A					: Dict							,A					: Dict							,**A					: Any ):
					__A   			= {}
					__A   			= text_config
					__A   			= vision_config

					return cls.from_dict(A							,**A )







	def 				UpperCamelCase_  (       self					: Any ):
					__A   			= copy.deepcopy(self.__dict__ )
					__A   			= self.text_config.to_dict()
					__A   			= self.vision_config.to_dict()
					__A   			= self.__class__.model_type
					return output





class 							UpperCAmelCase      (  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	@property
	def 				UpperCamelCase_  (       self					: Dict ):
					return OrderedDict(
					    [
					        ("input_ids", {0: "batch", 1: "sequence"}),
					        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
					        ("attention_mask", {0: "batch", 1: "sequence"}),
					    ] )






	@property
	def 				UpperCamelCase_  (       self					: List[str] ):
					return OrderedDict(
					    [
					        ("logits_per_image", {0: "batch"}),
					        ("logits_per_text", {0: "batch"}),
					        ("text_embeds", {0: "batch"}),
					        ("image_embeds", {0: "batch"}),
					    ] )






	@property
	def 				UpperCamelCase_  (       self					: Dict ):
					return 1E-4






	def 				UpperCamelCase_  (       self					: Union[str, Any]							,A					: "ProcessorMixin"							,A					: int = -1							,A					: int = -1							,A					: Optional["TensorType"] = None							,):
					__A   			= super().generate_dummy_inputs(
					    processor.tokenizer							,batch_size=A							,seq_length=A							,framework=A )
					__A   			= super().generate_dummy_inputs(
					    processor.image_processor							,batch_size=A							,framework=A )
					return {**text_input_dict, **image_input_dict}







	@property
	def 				UpperCamelCase_  (       self					: Any ):
					return 14






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

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
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
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCAmelCase_									=	get_tests_dir('fixtures')
UpperCAmelCase_									=	get_tests_dir('fixtures/dummy_feature_extractor_config.json')
UpperCAmelCase_									=	get_tests_dir('fixtures/dummy-config.json')





class     lowerCamelCase__(					unittest.TestCase):
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						0
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int   ):
             with tempfile.TemporaryDirectory() as tmpdirname:
                    __lowerCamelCase   =						WavaVecaConfig()

                    # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   ).to_dict()

                    config_dict.pop("""feature_extractor_type"""   )
                    __lowerCamelCase   =						WavaVecaFeatureExtractor(**UpperCamelCase_   )

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

                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )

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

             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       """bert-base is not a local folder and is not a valid model identifier"""   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""bert-base"""   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_    ,       revision="""aaaaaa"""   )
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""    ,       ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             # If remote code is not set, we will time out when asking whether to load the model.
             with self.assertRaises(UpperCamelCase_   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""   )
             # If remote code is disabled, we can't load this config.
             with self.assertRaises(UpperCamelCase_   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )

             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                 """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
             self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )

             # Test feature extractor can be reloaded.
             with tempfile.TemporaryDirectory() as tmp_dir:
                    feature_extractor.save_pretrained(UpperCamelCase_   )
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_    ,       trust_remote_code=UpperCamelCase_   )
             self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
      def 			lowerCAmelCase__						(				self: Any   ):
             try:
                    AutoConfig.register("""custom"""    ,       UpperCamelCase_   )
                    AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )
                    # Trying to register something existing in the Transformers library will raise an error
                    with self.assertRaises(UpperCamelCase_   ):
                           AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )

                    # Now that the config is registered, it can be used as any other config with the auto-API
                    __lowerCamelCase   =						CustomFeatureExtractor.from_pretrained(UpperCamelCase_   )
                    with tempfile.TemporaryDirectory() as tmp_dir:
                           feature_extractor.save_pretrained(UpperCamelCase_   )
                           __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
                           self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )

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




      def 			lowerCAmelCase__						(				self: Dict   ):





             class     lowerCamelCase__(					__lowerCamelCase):
                   UpperCAmelCase__      :	str    		=   True

             try:
                    AutoConfig.register("""custom"""    ,       UpperCamelCase_   )
                    AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )
                    # If remote code is not set, the default is to use local
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(feature_extractor.is_local   )

                    # If remote code is disabled, we load the local one.
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(feature_extractor.is_local   )

                    # If remote is enabled, we load from the Hub
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(not hasattr(UpperCamelCase_    ,       """is_local"""   )   )

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

