



"""simple docstring"""


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


__A :				Tuple					    = logging.get_logger(__name__)

__A :				Optional[int]					    = {
    "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       _a			(       __lowercase):
			"""simple docstring"""
			UpperCamelCase__         =						"owlvit_text_model"



			def __init__(		self  :     Union[str, Any]					, __UpperCamelCase  :     Union[str, Any]=4_9_4_0_8					, __UpperCamelCase  :     List[str]=5_1_2					, __UpperCamelCase  :     Dict=2_0_4_8					, __UpperCamelCase  :     Any=1_2					, __UpperCamelCase  :     Optional[Any]=8					, __UpperCamelCase  :     Optional[Any]=1_6					, __UpperCamelCase  :     Optional[Any]="quick_gelu"					, __UpperCamelCase  :     str=1e-5					, __UpperCamelCase  :     List[Any]=0.0					, __UpperCamelCase  :     Union[str, Any]=0.0_2					, __UpperCamelCase  :     Union[str, Any]=1.0					, __UpperCamelCase  :     Any=0					, __UpperCamelCase  :     int=4_9_4_0_6					, __UpperCamelCase  :     Any=4_9_4_0_7					, **__UpperCamelCase  :     Optional[Any]					, )->int:
							super().__init__(pad_token_id=_a					, bos_token_id=_a					, eos_token_id=_a					, **_a )

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



			@classmethod
			def 			lowercase__    (		cls  :     Union[str, Any]					, __UpperCamelCase  :     Union[str, Any]					, **__UpperCamelCase  :     Optional[int] )->"PretrainedConfig":
							cls._set_token_in_kwargs(_a )

							_UpperCAmelCase      		=     cls.get_config_dict(_a					, **_a )

							# get the text config dict if we are loading from OwlViTConfig
							if config_dict.get('''model_type''' ) == "owlvit":
											_UpperCAmelCase      		=     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       _a			(       __lowercase):
			"""simple docstring"""
			UpperCamelCase__         =						"owlvit_vision_model"



			def __init__(		self  :     Optional[Any]					, __UpperCamelCase  :     List[str]=7_6_8					, __UpperCamelCase  :     str=3_0_7_2					, __UpperCamelCase  :     Dict=1_2					, __UpperCamelCase  :     Optional[int]=1_2					, __UpperCamelCase  :     List[str]=3					, __UpperCamelCase  :     Union[str, Any]=7_6_8					, __UpperCamelCase  :     Any=3_2					, __UpperCamelCase  :     Union[str, Any]="quick_gelu"					, __UpperCamelCase  :     Optional[Any]=1e-5					, __UpperCamelCase  :     List[str]=0.0					, __UpperCamelCase  :     Any=0.0_2					, __UpperCamelCase  :     Any=1.0					, **__UpperCamelCase  :     Dict					, )->Dict:
							super().__init__(**_a )

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



			@classmethod
			def 			lowercase__    (		cls  :     Optional[int]					, __UpperCamelCase  :     Dict					, **__UpperCamelCase  :     List[Any] )->"PretrainedConfig":
							cls._set_token_in_kwargs(_a )

							_UpperCAmelCase      		=     cls.get_config_dict(_a					, **_a )

							# get the vision config dict if we are loading from OwlViTConfig
							if config_dict.get('''model_type''' ) == "owlvit":
											_UpperCAmelCase      		=     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       _a			(       __lowercase):
			"""simple docstring"""
			UpperCamelCase__         =						"owlvit"
			UpperCamelCase__         =						True



			def __init__(		self  :     Optional[Any]					, __UpperCamelCase  :     Tuple=None					, __UpperCamelCase  :     List[str]=None					, __UpperCamelCase  :     Optional[int]=5_1_2					, __UpperCamelCase  :     Union[str, Any]=2.6_5_9_2					, __UpperCamelCase  :     str=True					, **__UpperCamelCase  :     Dict					, )->Any:
							super().__init__(**_a )

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

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

							_UpperCAmelCase      		=     OwlViTTextConfig(**_a )
							_UpperCAmelCase      		=     OwlViTVisionConfig(**_a )

							_UpperCAmelCase      		=     projection_dim
							_UpperCAmelCase      		=     logit_scale_init_value
							_UpperCAmelCase      		=     return_dict
							_UpperCAmelCase      		=     1.0



			@classmethod
			def 			lowercase__    (		cls  :     Any					, __UpperCamelCase  :     List[str]					, **__UpperCamelCase  :     Optional[int] )->"PretrainedConfig":
							cls._set_token_in_kwargs(_a )

							_UpperCAmelCase      		=     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 			lowercase__    (		cls  :     Any					, __UpperCamelCase  :     Union[str, Any]					, __UpperCamelCase  :     Dict					, **__UpperCamelCase  :     Union[str, Any] )->Dict:
							_UpperCAmelCase      		=     {}
							_UpperCAmelCase      		=     text_config
							_UpperCAmelCase      		=     vision_config

							return cls.from_dict(_a					, **_a )



			def 			lowercase__    (		self  :     Optional[int] )->Union[str, Any]:
							_UpperCAmelCase      		=     copy.deepcopy(self.__dict__ )
							_UpperCAmelCase      		=     self.text_config.to_dict()
							_UpperCAmelCase      		=     self.vision_config.to_dict()
							_UpperCAmelCase      		=     self.__class__.model_type
							return output



class       _a			(       __lowercase):
			"""simple docstring"""



			@property
			def 			lowercase__    (		self  :     List[Any] )->Mapping[str, Mapping[int, str]]:
							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 			lowercase__    (		self  :     int )->Mapping[str, Mapping[int, str]]:
							return OrderedDict(
							    [
							        ('''logits_per_image''', {0: '''batch'''}),
							        ('''logits_per_text''', {0: '''batch'''}),
							        ('''text_embeds''', {0: '''batch'''}),
							        ('''image_embeds''', {0: '''batch'''}),
							    ] )



			@property
			def 			lowercase__    (		self  :     str )->float:
							return 1e-4



			def 			lowercase__    (		self  :     str					, __UpperCamelCase  :     int					, __UpperCamelCase  :     List[Any] = -1					, __UpperCamelCase  :     List[Any] = -1					, __UpperCamelCase  :     int = None					, )->Mapping[str, Any]:
							_UpperCAmelCase      		=     super().generate_dummy_inputs(
							    processor.tokenizer					, batch_size=_a					, seq_length=_a					, framework=_a )
							_UpperCAmelCase      		=     super().generate_dummy_inputs(
							    processor.image_processor					, batch_size=_a					, framework=_a )
							return {**text_input_dict, **image_input_dict}



			@property
			def 			lowercase__    (		self  :     Dict )->int:
							return 1_4






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 							__lowercase							(     self			)       ->       List[Any]:
												_a      :       int   =						0


							def 							__lowercase							(     self			)       ->       List[str]:
												_a      :       Dict   =						AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''			)
												self.assertIsInstance(_a			,				_a			)


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

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


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

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


							def 							__lowercase							(     self			)       ->       Optional[Any]:
												with tempfile.TemporaryDirectory() as tmpdirname:
																	_a      :       Dict   =						CLIPConfig()

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

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

																	config_dict.pop('''image_processor_type'''			)
																	_a      :       Tuple   =						CLIPImageProcessor(**_a			)

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

																	_a      :       List[str]   =						AutoImageProcessor.from_pretrained(_a			)

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

												self.assertIsInstance(_a			,				_a			)


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

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


							def 							__lowercase							(     self			)       ->       Any:
												with self.assertRaisesRegex(
												    _a			,				'''clip-base is not a local folder and is not a valid model identifier'''			):
																	_a      :       Dict   =						AutoImageProcessor.from_pretrained('''clip-base'''			)


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


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


							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												# If remote code is not set, we will time out when asking whether to load the model.
												with self.assertRaises(_a			):
																	_a      :       str   =						AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''			)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(_a			):
																	_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_image_processor'''			,				trust_remote_code=_a			)

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

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


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

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

																						_a      :       int   =						CustomImageProcessor.from_pretrained(_a			)

																	# 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(_a			)
																						_a      :       Optional[Any]   =						AutoImageProcessor.from_pretrained(_a			)
																						self.assertIsInstance(_a			,				_a			)

												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 							__lowercase							(     self			)       ->       Union[str, Any]:

												class 							UpperCAmelCase_						(     __lowercase  ):
																			"""simple docstring"""







																			UpperCAmelCase__			:		Tuple             =       True

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

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



