





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


_SCREAMING_SNAKE_CASE					=    logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE					=    {
    '''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 							__lowercase       (      lowerCAmelCase__						):







	'''simple docstring'''

	a    :				List[str]											=       "owlvit_text_model"


	def __init__(self     ,_lowerCamelCase=49408     ,_lowerCamelCase=512     ,_lowerCamelCase=2048     ,_lowerCamelCase=12     ,_lowerCamelCase=8     ,_lowerCamelCase=16     ,_lowerCamelCase="quick_gelu"     ,_lowerCamelCase=1E-5     ,_lowerCamelCase=0.0     ,_lowerCamelCase=0.0_2     ,_lowerCamelCase=1.0     ,_lowerCamelCase=0     ,_lowerCamelCase=49406     ,_lowerCamelCase=49407     ,**_lowerCamelCase     ,)							->							Optional[Any]:







				'''simple docstring'''





				super().__init__(pad_token_id=_lowerCamelCase     ,bos_token_id=_lowerCamelCase     ,eos_token_id=_lowerCamelCase     ,**_lowerCamelCase )

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


	@classmethod
	def 						_UpperCAmelCase     (cls     ,_lowerCamelCase     ,**_lowerCamelCase )							->							"PretrainedConfig":







				'''simple docstring'''





				cls._set_token_in_kwargs(_lowerCamelCase )

				__lowercase						,		__lowercase										=							cls.get_config_dict(_lowerCamelCase     ,**_lowerCamelCase )

				# get the text config dict if we are loading from OwlViTConfig
				if config_dict.get('''model_type''' ) == "owlvit":
							__lowercase										=							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(_lowerCamelCase     ,**_lowerCamelCase )






class 							__lowercase       (      lowerCAmelCase__						):







	'''simple docstring'''

	a    :				Tuple											=       "owlvit_vision_model"


	def __init__(self     ,_lowerCamelCase=768     ,_lowerCamelCase=3072     ,_lowerCamelCase=12     ,_lowerCamelCase=12     ,_lowerCamelCase=3     ,_lowerCamelCase=768     ,_lowerCamelCase=32     ,_lowerCamelCase="quick_gelu"     ,_lowerCamelCase=1E-5     ,_lowerCamelCase=0.0     ,_lowerCamelCase=0.0_2     ,_lowerCamelCase=1.0     ,**_lowerCamelCase     ,)							->							Union[str, Any]:







				'''simple docstring'''





				super().__init__(**_lowerCamelCase )

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


	@classmethod
	def 						_UpperCAmelCase     (cls     ,_lowerCamelCase     ,**_lowerCamelCase )							->							"PretrainedConfig":







				'''simple docstring'''





				cls._set_token_in_kwargs(_lowerCamelCase )

				__lowercase						,		__lowercase										=							cls.get_config_dict(_lowerCamelCase     ,**_lowerCamelCase )

				# get the vision config dict if we are loading from OwlViTConfig
				if config_dict.get('''model_type''' ) == "owlvit":
							__lowercase										=							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(_lowerCamelCase     ,**_lowerCamelCase )






class 							__lowercase       (      lowerCAmelCase__						):







	'''simple docstring'''

	a    :				List[Any]											=       "owlvit"
	a    :				str											=       True


	def __init__(self     ,_lowerCamelCase=None     ,_lowerCamelCase=None     ,_lowerCamelCase=512     ,_lowerCamelCase=2.6_5_9_2     ,_lowerCamelCase=True     ,**_lowerCamelCase     ,)							->							List[Any]:







				'''simple docstring'''





				super().__init__(**_lowerCamelCase )

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

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

				__lowercase										=							OwlViTTextConfig(**_lowerCamelCase )
				__lowercase										=							OwlViTVisionConfig(**_lowerCamelCase )

				__lowercase										=							projection_dim
				__lowercase										=							logit_scale_init_value
				__lowercase										=							return_dict
				__lowercase										=							1.0


	@classmethod
	def 						_UpperCAmelCase     (cls     ,_lowerCamelCase     ,**_lowerCamelCase )							->							"PretrainedConfig":







				'''simple docstring'''





				cls._set_token_in_kwargs(_lowerCamelCase )

				__lowercase						,		__lowercase										=							cls.get_config_dict(_lowerCamelCase     ,**_lowerCamelCase )

				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(_lowerCamelCase     ,**_lowerCamelCase )


	@classmethod
	def 						_UpperCAmelCase     (cls     ,_lowerCamelCase     ,_lowerCamelCase     ,**_lowerCamelCase )							->							List[Any]:







				'''simple docstring'''





				__lowercase										=							{}
				__lowercase										=							text_config
				__lowercase										=							vision_config

				return cls.from_dict(_lowerCamelCase     ,**_lowerCamelCase )


	def 						_UpperCAmelCase     (self )							->							Dict:







				'''simple docstring'''





				__lowercase										=							copy.deepcopy(self.__dict__ )
				__lowercase										=							self.text_config.to_dict()
				__lowercase										=							self.vision_config.to_dict()
				__lowercase										=							self.__class__.model_type
				return output






class 							__lowercase       (      lowerCAmelCase__						):







	'''simple docstring'''

	@property
	def 						_UpperCAmelCase     (self )							->							Mapping[str, Mapping[int, str]]:







				'''simple docstring'''





				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 )							->							Mapping[str, Mapping[int, str]]:







				'''simple docstring'''





				return OrderedDict(
				    [
				        ('''logits_per_image''', {0: '''batch'''}),
				        ('''logits_per_text''', {0: '''batch'''}),
				        ('''text_embeds''', {0: '''batch'''}),
				        ('''image_embeds''', {0: '''batch'''}),
				    ] )


	@property
	def 						_UpperCAmelCase     (self )							->							float:







				'''simple docstring'''





				return 1E-4


	def 						_UpperCAmelCase     (self     ,_lowerCamelCase     ,_lowerCamelCase = -1     ,_lowerCamelCase = -1     ,_lowerCamelCase = None     ,)							->							Mapping[str, Any]:







				'''simple docstring'''





				__lowercase										=							super().generate_dummy_inputs(
				    processor.tokenizer     ,batch_size=_lowerCamelCase     ,seq_length=_lowerCamelCase     ,framework=_lowerCamelCase )
				__lowercase										=							super().generate_dummy_inputs(
				    processor.image_processor     ,batch_size=_lowerCamelCase     ,framework=_lowerCamelCase )
				return {**text_input_dict, **image_input_dict}


	@property
	def 						_UpperCAmelCase     (self )							->							int:







				'''simple docstring'''





				return 14












'''simple docstring'''



from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


_SCREAMING_SNAKE_CASE					=    '''\
@inproceedings{wang2019glue,
  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},
  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},
  note={In the Proceedings of ICLR.},
  year={2019}
}
'''

_SCREAMING_SNAKE_CASE					=    '''\
GLUE, the General Language Understanding Evaluation benchmark
(https://gluebenchmark.com/) is a collection of resources for training,
evaluating, and analyzing natural language understanding systems.
'''

_SCREAMING_SNAKE_CASE					=    '''
Compute GLUE evaluation metric associated to each GLUE dataset.
Args:
    predictions: list of predictions to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
Returns: depending on the GLUE subset, one or several of:
    "accuracy": Accuracy
    "f1": F1 score
    "pearson": Pearson Correlation
    "spearmanr": Spearman Correlation
    "matthews_correlation": Matthew Correlation
Examples:

    >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\')  # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0}

    >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\')  # \'mrpc\' or \'qqp\'
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'accuracy\': 1.0, \'f1\': 1.0}

    >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')
    >>> references = [0., 1., 2., 3., 4., 5.]
    >>> predictions = [0., 1., 2., 3., 4., 5.]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)})
    {\'pearson\': 1.0, \'spearmanr\': 1.0}

    >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'matthews_correlation\': 1.0}
'''




def    _lowerCAmelCase						(				lowerCamelCase_			:  Any		,       lowerCamelCase_			:  int				):
			return float((preds == labels).mean()				)




def    _lowerCAmelCase						(				lowerCamelCase_			:  List[str]		,       lowerCamelCase_			:  str				):
			__lowercase										=							simple_accuracy(lowerCamelCase_		,       lowerCamelCase_				)
			__lowercase										=							float(fa_score(y_true=lowerCamelCase_		,       y_pred=lowerCamelCase_				)				)
			return {
			    "accuracy": acc,
			    "f1": fa,
			}




def    _lowerCAmelCase						(				lowerCamelCase_			:  List[Any]		,       lowerCamelCase_			:  Any				):
			__lowercase										=							float(pearsonr(lowerCamelCase_		,       lowerCamelCase_				)[0]				)
			__lowercase										=							float(spearmanr(lowerCamelCase_		,       lowerCamelCase_				)[0]				)
			return {
			    "pearson": pearson_corr,
			    "spearmanr": spearman_corr,
			}






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,      _KWARGS_DESCRIPTION						)
class 							__lowercase       (      datasets.Metric						):







	'''simple docstring'''

	def 						_UpperCAmelCase     (self )							->							str:







				'''simple docstring'''





				if self.config_name not in [
				    "sst2",
				    "mnli",
				    "mnli_mismatched",
				    "mnli_matched",
				    "cola",
				    "stsb",
				    "mrpc",
				    "qqp",
				    "qnli",
				    "rte",
				    "wnli",
				    "hans",
				]:
							raise KeyError(
							    '''You should supply a configuration name selected in '''
							    '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", '''
							    '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
				return datasets.MetricInfo(
				    description=_DESCRIPTION     ,citation=_CITATION     ,inputs_description=_KWARGS_DESCRIPTION     ,features=datasets.Features(
				        {
				            '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ),
				            '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ),
				        } )     ,codebase_urls=[]     ,reference_urls=[]     ,format='''numpy'''     ,)


	def 						_UpperCAmelCase     (self     ,_lowerCamelCase     ,_lowerCamelCase )							->							Dict:







				'''simple docstring'''





				if self.config_name == "cola":
							return {"matthews_correlation": matthews_corrcoef(_lowerCamelCase     ,_lowerCamelCase )}
				elif self.config_name == "stsb":
							return pearson_and_spearman(_lowerCamelCase     ,_lowerCamelCase )
				elif self.config_name in ["mrpc", "qqp"]:
							return acc_and_fa(_lowerCamelCase     ,_lowerCamelCase )
				elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
							return {"accuracy": simple_accuracy(_lowerCamelCase     ,_lowerCamelCase )}
				else:
							raise KeyError(
							    '''You should supply a configuration name selected in '''
							    '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", '''
							    '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )





