

"""simple docstring"""


import copy
import os
from typing import Union

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


__A						       =      logging.get_logger(__name__)

__A						       =      {
    "google/pix2struct-textcaps-base": (
        "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"
    ),
}





class    snake_case     (    __snake_case  ):
				SCREAMING_SNAKE_CASE_       :				Tuple       				=  """pix2struct_text_model"""
				SCREAMING_SNAKE_CASE_       :				Tuple       				=  ["""past_key_values"""]
				SCREAMING_SNAKE_CASE_       :				str       				=  {
				    """hidden_size""": """hidden_size""",
				    """num_attention_heads""": """num_heads""",
				    """num_hidden_layers""": """num_layers""",
				}

				def __init__(     self							:    Union[str, Any]					,  UpperCamelCase__							:    Dict=5_0_2_4_4					,  UpperCamelCase__							:    Union[str, Any]=7_6_8					,  UpperCamelCase__							:    str=6_4					,  UpperCamelCase__							:    Tuple=2_0_4_8					,  UpperCamelCase__							:    Dict=1_2					,  UpperCamelCase__							:    Dict=1_2					,  UpperCamelCase__							:    Optional[Any]=3_2					,  UpperCamelCase__							:    Union[str, Any]=1_2_8					,  UpperCamelCase__							:    int=0.1					,  UpperCamelCase__							:    int=1e-6					,  UpperCamelCase__							:    int=1.0					,  UpperCamelCase__							:    int="gelu_new"					,  UpperCamelCase__							:    Tuple=0					,  UpperCamelCase__							:    Tuple=False					,  UpperCamelCase__							:    List[Any]=0					,  UpperCamelCase__							:    Union[str, Any]=1					,  UpperCamelCase__							:    Any=False					,  UpperCamelCase__							:    Dict=True					,  **UpperCamelCase__							:    List[str]					,  )->       Any:



						'''simple docstring'''


						__lowerCAmelCase:	Dict   				=      vocab_size
						__lowerCAmelCase:	int   				=      hidden_size
						__lowerCAmelCase:	Dict   				=      d_kv
						__lowerCAmelCase:	Union[str, Any]   				=      d_ff
						__lowerCAmelCase:	List[str]   				=      num_layers
						__lowerCAmelCase:	Union[str, Any]   				=      num_heads
						__lowerCAmelCase:	Tuple   				=      relative_attention_num_buckets
						__lowerCAmelCase:	Optional[Any]   				=      relative_attention_max_distance
						__lowerCAmelCase:	Dict   				=      dropout_rate
						__lowerCAmelCase:	Dict   				=      layer_norm_epsilon
						__lowerCAmelCase:	int   				=      initializer_factor
						__lowerCAmelCase:	str   				=      use_cache

						__lowerCAmelCase:	Optional[Any]   				=      eos_token_id
						__lowerCAmelCase:	Optional[Any]   				=      decoder_start_token_id

						# for backwards compatibility
						__lowerCAmelCase:	str   				=      dense_act_fn

						super().__init__(
						    pad_token_id=UpperCamelCase__					,  eos_token_id=UpperCamelCase__					,  decoder_start_token_id=UpperCamelCase__					,  tie_word_embeddings=UpperCamelCase__					,  is_decoder=UpperCamelCase__					,  **UpperCamelCase__					,  )




				@classmethod
				def 							lowercase_					(     cls							:    Any					,  UpperCamelCase__							:    Union[str, os.PathLike]					,  **UpperCamelCase__							:    str)->       "PretrainedConfig":



						'''simple docstring'''


						cls._set_token_in_kwargs(UpperCamelCase__)

						__lowerCAmelCase				,			__lowerCAmelCase:	List[str]   				=      cls.get_config_dict(UpperCamelCase__					,  **UpperCamelCase__)

						# get the text config dict if we are loading from Pix2StructConfig
						if config_dict.get("model_type") == "pix2struct":
								__lowerCAmelCase:	Optional[int]   				=      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(UpperCamelCase__					,  **UpperCamelCase__)





class    snake_case     (    __snake_case  ):
				SCREAMING_SNAKE_CASE_       :				int       				=  """pix2struct_vision_model"""

				def __init__(     self							:    int					,  UpperCamelCase__							:    int=7_6_8					,  UpperCamelCase__							:    str=7_6_8					,  UpperCamelCase__							:    Optional[Any]=2_0_4_8					,  UpperCamelCase__							:    List[str]=6_4					,  UpperCamelCase__							:    Any=1_2					,  UpperCamelCase__							:    Tuple=1_2					,  UpperCamelCase__							:    Optional[int]="gelu_new"					,  UpperCamelCase__							:    str=1e-6					,  UpperCamelCase__							:    List[str]=0.0					,  UpperCamelCase__							:    List[str]=0.0					,  UpperCamelCase__							:    Tuple=1e-10					,  UpperCamelCase__							:    str=1.0					,  UpperCamelCase__							:    Optional[int]=4_0_9_6					,  UpperCamelCase__							:    Dict=3_2					,  UpperCamelCase__							:    Tuple=1_2_8					,  **UpperCamelCase__							:    str					,  )->       List[str]:



						'''simple docstring'''


						super().__init__(**UpperCamelCase__)

						__lowerCAmelCase:	Union[str, Any]   				=      hidden_size
						__lowerCAmelCase:	List[Any]   				=      patch_embed_hidden_size
						__lowerCAmelCase:	List[str]   				=      d_ff
						__lowerCAmelCase:	int   				=      dropout_rate
						__lowerCAmelCase:	Tuple   				=      num_hidden_layers
						__lowerCAmelCase:	List[Any]   				=      num_attention_heads
						__lowerCAmelCase:	List[str]   				=      initializer_range
						__lowerCAmelCase:	List[str]   				=      initializer_factor
						__lowerCAmelCase:	Union[str, Any]   				=      attention_dropout
						__lowerCAmelCase:	Union[str, Any]   				=      layer_norm_eps
						__lowerCAmelCase:	Dict   				=      dense_act_fn
						__lowerCAmelCase:	Dict   				=      seq_len
						__lowerCAmelCase:	List[str]   				=      relative_attention_num_buckets
						__lowerCAmelCase:	Union[str, Any]   				=      relative_attention_max_distance
						__lowerCAmelCase:	List[Any]   				=      d_kv




				@classmethod
				def 							lowercase_					(     cls							:    List[Any]					,  UpperCamelCase__							:    Union[str, os.PathLike]					,  **UpperCamelCase__							:    Union[str, Any])->       "PretrainedConfig":



						'''simple docstring'''


						cls._set_token_in_kwargs(UpperCamelCase__)

						__lowerCAmelCase				,			__lowerCAmelCase:	Optional[int]   				=      cls.get_config_dict(UpperCamelCase__					,  **UpperCamelCase__)

						# get the vision config dict if we are loading from Pix2StructConfig
						if config_dict.get("model_type") == "pix2struct":
								__lowerCAmelCase:	str   				=      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(UpperCamelCase__					,  **UpperCamelCase__)





class    snake_case     (    __snake_case  ):
				SCREAMING_SNAKE_CASE_       :				Any       				=  """pix2struct"""
				SCREAMING_SNAKE_CASE_       :				Optional[Any]       				=  True

				def __init__(     self							:    Any					,  UpperCamelCase__							:    Tuple=None					,  UpperCamelCase__							:    Any=None					,  UpperCamelCase__							:    int=1.0					,  UpperCamelCase__							:    Tuple=0.02					,  UpperCamelCase__							:    List[Any]=False					,  UpperCamelCase__							:    int=False					,  UpperCamelCase__							:    Any=True					,  **UpperCamelCase__							:    int					,  )->       Dict:



						'''simple docstring'''


						super().__init__(tie_word_embeddings=UpperCamelCase__					,  is_encoder_decoder=UpperCamelCase__					,  **UpperCamelCase__)

						if text_config is None:
								__lowerCAmelCase:	Any   				=      {}
								logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values.")

						if vision_config is None:
								__lowerCAmelCase:	Dict   				=      {}
								logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values.")

						__lowerCAmelCase:	Tuple   				=      PixaStructTextConfig(**UpperCamelCase__)
						__lowerCAmelCase:	Dict   				=      PixaStructVisionConfig(**UpperCamelCase__)

						__lowerCAmelCase:	str   				=      self.text_config.decoder_start_token_id
						__lowerCAmelCase:	Dict   				=      self.text_config.pad_token_id
						__lowerCAmelCase:	Optional[Any]   				=      self.text_config.eos_token_id

						__lowerCAmelCase:	Optional[Any]   				=      initializer_factor
						__lowerCAmelCase:	Dict   				=      initializer_range

						__lowerCAmelCase:	List[str]   				=      self.initializer_range
						__lowerCAmelCase:	Dict   				=      self.initializer_range

						__lowerCAmelCase:	Tuple   				=      is_vqa

				@classmethod
				def 							lowercase_					(     cls							:    Union[str, Any]					,  UpperCamelCase__							:    PixaStructTextConfig					,  UpperCamelCase__							:    PixaStructVisionConfig					,  **UpperCamelCase__							:    Union[str, Any])->       Optional[int]:



						'''simple docstring'''


						return cls(text_config=text_config.to_dict()					,  vision_config=vision_config.to_dict()					,  **UpperCamelCase__)




				def 							lowercase_					(     self							:    Optional[int])->       int:



						'''simple docstring'''


						__lowerCAmelCase:	Any   				=      copy.deepcopy(self.__dict__)
						__lowerCAmelCase:	str   				=      self.text_config.to_dict()
						__lowerCAmelCase:	Optional[int]   				=      self.vision_config.to_dict()
						__lowerCAmelCase:	Tuple   				=      self.__class__.model_type
						return output





"""simple docstring"""


import comet  # From: unbabel-comet
import torch

import datasets


__A						       =      datasets.logging.get_logger(__name__)

__A						       =      "\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel's Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = \"{COMET}: A Neural Framework for {MT} Evaluation\",\n   author = \"Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon\",\n   booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\",\n   month = nov,\n   year = \"2020\",\n   address = \"Online\",\n   publisher = \"Association for Computational Linguistics\",\n   url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\",\n   pages = \"2685--2702\",\n}\n"

__A						       =      "\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n"

__A						       =      "\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric('comet')\n    >>> # comet_metric = load_metric('comet', 'wmt20-comet-da')  # you can also choose which model to use\n    >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"]\n    >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"]\n    >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results[\"scores\"]])\n    [0.19, 0.92]\n"





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

				def 							lowercase_					(     self							:    List[Any])->       Dict:



						'''simple docstring'''


						return datasets.MetricInfo(
						    description=_DESCRIPTION					,  citation=_CITATION					,  homepage="https://unbabel.github.io/COMET/html/index.html"					,  inputs_description=_KWARGS_DESCRIPTION					,  features=datasets.Features(
						        {
						            "sources": datasets.Value("string"					,  id="sequence"),
						            "predictions": datasets.Value("string"					,  id="sequence"),
						            "references": datasets.Value("string"					,  id="sequence"),
						        })					,  codebase_urls=["https://github.com/Unbabel/COMET"]					,  reference_urls=[
						        "https://github.com/Unbabel/COMET",
						        "https://www.aclweb.org/anthology/2020.emnlp-main.213/",
						        "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6",
						    ]					,  )

				def 							lowercase_					(     self							:    Tuple					,  UpperCamelCase__							:    Any)->       Dict:



						'''simple docstring'''


						if self.config_name == "default":
								__lowerCAmelCase:	Union[str, Any]   				=      comet.load_from_checkpoint(comet.download_model("wmt20-comet-da"))
						else:
								__lowerCAmelCase:	Tuple   				=      comet.load_from_checkpoint(comet.download_model(self.config_name))




				def 							lowercase_					(     self							:    Optional[int]					,  UpperCamelCase__							:    Optional[Any]					,  UpperCamelCase__							:    Optional[Any]					,  UpperCamelCase__							:    int					,  UpperCamelCase__							:    Optional[int]=None					,  UpperCamelCase__							:    List[str]=False)->       str:



						'''simple docstring'''


						if gpus is None:
								__lowerCAmelCase:	Union[str, Any]   				=      1 if torch.cuda.is_available() else 0
						__lowerCAmelCase:	Dict   				=      {"src": sources, "mt": predictions, "ref": references}
						__lowerCAmelCase:	Union[str, Any]   				=      [dict(zip(UpperCamelCase__					,  UpperCamelCase__)) for t in zip(*data.values())]
						__lowerCAmelCase				,			__lowerCAmelCase:	str   				=      self.scorer.predict(UpperCamelCase__					,  gpus=UpperCamelCase__					,  progress_bar=UpperCamelCase__)
						return {"mean_score": mean_score, "scores": scores}


