


"""simple docstring"""






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase     =  logging.get_logger(__name__)

_lowerCamelCase     =  {
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}


class 			lowerCamelCase_		(			_lowercase   ):





				"""simple docstring"""







				_lowerCAmelCase      :      Dict      							=					'''altclip_text_model'''



				def __init__(						self       ,		UpperCAmelCase__=25_0002       ,		UpperCAmelCase__=1024       ,		UpperCAmelCase__=24       ,		UpperCAmelCase__=16       ,		UpperCAmelCase__=4096       ,		UpperCAmelCase__="gelu"       ,		UpperCAmelCase__=0.1       ,		UpperCAmelCase__=0.1       ,		UpperCAmelCase__=514       ,		UpperCAmelCase__=1       ,		UpperCAmelCase__=0.02       ,		UpperCAmelCase__=0.02       ,		UpperCAmelCase__=1e-05       ,		UpperCAmelCase__=1       ,		UpperCAmelCase__=0       ,		UpperCAmelCase__=2       ,		UpperCAmelCase__="absolute"       ,		UpperCAmelCase__=True       ,		UpperCAmelCase__=768       ,		**UpperCAmelCase__       ,		):
								super().__init__(pad_token_id=A_       ,		bos_token_id=A_       ,		eos_token_id=A_       ,		**A_     )

								SCREAMING_SNAKE_CASE__     							=				vocab_size
								SCREAMING_SNAKE_CASE__     							=				hidden_size
								SCREAMING_SNAKE_CASE__     							=				num_hidden_layers
								SCREAMING_SNAKE_CASE__     							=				num_attention_heads
								SCREAMING_SNAKE_CASE__     							=				hidden_act
								SCREAMING_SNAKE_CASE__     							=				intermediate_size
								SCREAMING_SNAKE_CASE__     							=				hidden_dropout_prob
								SCREAMING_SNAKE_CASE__     							=				attention_probs_dropout_prob
								SCREAMING_SNAKE_CASE__     							=				max_position_embeddings
								SCREAMING_SNAKE_CASE__     							=				type_vocab_size
								SCREAMING_SNAKE_CASE__     							=				initializer_range
								SCREAMING_SNAKE_CASE__     							=				initializer_factor
								SCREAMING_SNAKE_CASE__     							=				layer_norm_eps
								SCREAMING_SNAKE_CASE__     							=				position_embedding_type
								SCREAMING_SNAKE_CASE__     							=				use_cache
								SCREAMING_SNAKE_CASE__     							=				project_dim


class 			lowerCamelCase_		(			_lowercase   ):





				"""simple docstring"""







				_lowerCAmelCase      :      Optional[int]      							=					'''altclip_vision_model'''



				def __init__(						self       ,		UpperCAmelCase__=768       ,		UpperCAmelCase__=3072       ,		UpperCAmelCase__=512       ,		UpperCAmelCase__=12       ,		UpperCAmelCase__=12       ,		UpperCAmelCase__=3       ,		UpperCAmelCase__=224       ,		UpperCAmelCase__=32       ,		UpperCAmelCase__="quick_gelu"       ,		UpperCAmelCase__=1e-5       ,		UpperCAmelCase__=0.0       ,		UpperCAmelCase__=0.02       ,		UpperCAmelCase__=1.0       ,		**UpperCAmelCase__       ,		):
								super().__init__(**A_     )

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






				@classmethod
				def   lowerCAmelCase__		(						cls       ,		UpperCAmelCase__       ,		**UpperCAmelCase__     ):
								cls._set_token_in_kwargs(A_     )

								SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     							=				cls.get_config_dict(A_       ,		**A_     )

								# get the vision config dict if we are loading from AltCLIPConfig
								if config_dict.get("model_type"     ) == "altclip":
												SCREAMING_SNAKE_CASE__     							=				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 			lowerCamelCase_		(			_lowercase   ):





				"""simple docstring"""







				_lowerCAmelCase      :      int      							=					'''altclip'''
				_lowerCAmelCase      :      Union[str, Any]      							=					True



				def __init__(						self       ,		UpperCAmelCase__=None       ,		UpperCAmelCase__=None       ,		UpperCAmelCase__=768       ,		UpperCAmelCase__=2.6_592       ,		**UpperCAmelCase__     ):
								# If `_config_dict` exist, we use them for the backward compatibility.
								# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
								# of confusion!).
								SCREAMING_SNAKE_CASE__     							=				kwargs.pop("text_config_dict"       ,		A_     )
								SCREAMING_SNAKE_CASE__     							=				kwargs.pop("vision_config_dict"       ,		A_     )

								super().__init__(**A_     )

								# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
								# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
								# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
								if text_config_dict is not None:
												if text_config is None:
																SCREAMING_SNAKE_CASE__     							=				{}

												# This is the complete result when using `text_config_dict`.
												SCREAMING_SNAKE_CASE__     							=				AltCLIPTextConfig(**A_     ).to_dict()

												# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
												for key, value in _text_config_dict.items():
																if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
																				# If specified in `text_config_dict`
																				if key in text_config_dict:
																								SCREAMING_SNAKE_CASE__     							=				(
																								    f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
																								    f'''The value `text_config_dict["{key}"]` will be used instead.'''
																								)
																				# If inferred from default argument values (just to be super careful)
																				else:
																								SCREAMING_SNAKE_CASE__     							=				(
																								    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																								    f'''value `text_config["{key}"]` will be overriden.'''
																								)
																				logger.warning(A_     )

            # Update all values in `text_config` with the ones in `_text_config_dict`.
												text_config.update(_text_config_dict     )

								if vision_config_dict is not None:
												if vision_config is None:
																SCREAMING_SNAKE_CASE__     							=				{}

												# This is the complete result when using `vision_config_dict`.
												SCREAMING_SNAKE_CASE__     							=				AltCLIPVisionConfig(**A_     ).to_dict()
												# convert keys to string instead of integer
												if "id2label" in _vision_config_dict:
																SCREAMING_SNAKE_CASE__     							=				{
																    str(A_     ): value for key, value in _vision_config_dict["id2label"].items()
																}

												# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
												for key, value in _vision_config_dict.items():
																if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
																				# If specified in `vision_config_dict`
																				if key in vision_config_dict:
																								SCREAMING_SNAKE_CASE__     							=				(
																								    f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
																								    f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
																								)
																				# If inferred from default argument values (just to be super careful)
																				else:
																								SCREAMING_SNAKE_CASE__     							=				(
																								    f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
																								    f'''The value `vision_config["{key}"]` will be overriden.'''
																								)
																				logger.warning(A_     )

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
												vision_config.update(_vision_config_dict     )

								if text_config is None:
												SCREAMING_SNAKE_CASE__     							=				{}
												logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."     )

								if vision_config is None:
												SCREAMING_SNAKE_CASE__     							=				{}
												logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."     )

								SCREAMING_SNAKE_CASE__     							=				AltCLIPTextConfig(**A_     )
								SCREAMING_SNAKE_CASE__     							=				AltCLIPVisionConfig(**A_     )

								SCREAMING_SNAKE_CASE__     							=				projection_dim
								SCREAMING_SNAKE_CASE__     							=				logit_scale_init_value
								SCREAMING_SNAKE_CASE__     							=				1.0



				@classmethod
				def   lowerCAmelCase__		(						cls       ,		UpperCAmelCase__       ,		UpperCAmelCase__       ,		**UpperCAmelCase__     ):
								return cls(text_config=text_config.to_dict()       ,		vision_config=vision_config.to_dict()       ,		**A_     )






				def   lowerCAmelCase__		(						self     ):
								SCREAMING_SNAKE_CASE__     							=				copy.deepcopy(self.__dict__     )
								SCREAMING_SNAKE_CASE__     							=				self.text_config.to_dict()
								SCREAMING_SNAKE_CASE__     							=				self.vision_config.to_dict()
								SCREAMING_SNAKE_CASE__     							=				self.__class__.model_type
								return output




"""simple docstring"""






import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


_lowerCamelCase     =  datasets.logging.get_logger(__name__)


_lowerCamelCase     =  '\\n@inproceedings{bleurt,\n  title={BLEURT: Learning Robust Metrics for Text Generation},\n  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n  booktitle={ACL},\n  year={2020},\n  url={https://arxiv.org/abs/2004.04696}\n}\n'

_lowerCamelCase     =  '\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n'

_lowerCamelCase     =  '\nBLEURT score.\n\nArgs:\n    `predictions` (list of str): prediction/candidate sentences\n    `references` (list of str): reference sentences\n    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n    \'scores\': List of scores.\nExamples:\n\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> bleurt = datasets.load_metric("bleurt")\n    >>> results = bleurt.compute(predictions=predictions, references=references)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [1.03, 1.04]\n'

_lowerCamelCase     =  {
    'bleurt-tiny-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip',
    'bleurt-tiny-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip',
    'bleurt-base-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip',
    'bleurt-base-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip',
    'bleurt-large-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip',
    'bleurt-large-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip',
    'BLEURT-20-D3': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip',
    'BLEURT-20-D6': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip',
    'BLEURT-20-D12': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip',
    'BLEURT-20': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip',
}


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





				"""simple docstring"""







				def   lowerCAmelCase__		(						self     ):
								return datasets.MetricInfo(
								    description=_DESCRIPTION       ,		citation=_CITATION       ,		homepage="https://github.com/google-research/bleurt"       ,		inputs_description=_KWARGS_DESCRIPTION       ,		features=datasets.Features(
								        {
								            "predictions": datasets.Value("string"       ,		id="sequence"     ),
								            "references": datasets.Value("string"       ,		id="sequence"     ),
								        }     )       ,		codebase_urls=["https://github.com/google-research/bleurt"]       ,		reference_urls=["https://github.com/google-research/bleurt", "https://arxiv.org/abs/2004.04696"]       ,		)



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								# check that config name specifies a valid BLEURT model
								if self.config_name == "default":
												logger.warning(
												    "Using default BLEURT-Base checkpoint for sequence maximum length 128. "
												    "You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512')."     )
												SCREAMING_SNAKE_CASE__     							=				"bleurt-base-128"

								if self.config_name.lower() in CHECKPOINT_URLS:
												SCREAMING_SNAKE_CASE__     							=				self.config_name.lower()

								elif self.config_name.upper() in CHECKPOINT_URLS:
												SCREAMING_SNAKE_CASE__     							=				self.config_name.upper()

								else:
												raise KeyError(
												    f'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}'''     )

								# download the model checkpoint specified by self.config_name and set up the scorer
								SCREAMING_SNAKE_CASE__     							=				dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name]     )
								SCREAMING_SNAKE_CASE__     							=				score.BleurtScorer(os.path.join(UpperCAmelCase__       ,		UpperCAmelCase__     )     )






				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__     ):
								SCREAMING_SNAKE_CASE__     							=				self.scorer.score(references=UpperCAmelCase__       ,		candidates=UpperCAmelCase__     )
								return {"scores": scores}
