

import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


_SCREAMING_SNAKE_CASE					:  List[str]             =      logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE					:  Optional[Any]             =      {
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "blip_2_vision_model"






  def __init__(							self						:		List[str]     ,       __lowerCamelCase						:		Tuple=1408     ,       __lowerCamelCase						:		Union[str, Any]=6144     ,       __lowerCamelCase						:		Union[str, Any]=39     ,       __lowerCamelCase						:		Any=16     ,       __lowerCamelCase						:		List[Any]=224     ,       __lowerCamelCase						:		str=14     ,       __lowerCamelCase						:		str="gelu"     ,       __lowerCamelCase						:		Dict=0.00001     ,       __lowerCamelCase						:		List[str]=0.0     ,       __lowerCamelCase						:		Tuple=1e-10     ,       __lowerCamelCase						:		str=True     ,       **__lowerCamelCase						:		Dict     ,       )		->							List[str]:
       super().__init__(**__lowerCamelCase )

       SCREAMING_SNAKE_CASE__   =   hidden_size
       SCREAMING_SNAKE_CASE__   =   intermediate_size
       SCREAMING_SNAKE_CASE__   =   num_hidden_layers
       SCREAMING_SNAKE_CASE__   =   num_attention_heads
       SCREAMING_SNAKE_CASE__   =   patch_size
       SCREAMING_SNAKE_CASE__   =   image_size
       SCREAMING_SNAKE_CASE__   =   initializer_range
       SCREAMING_SNAKE_CASE__   =   attention_dropout
       SCREAMING_SNAKE_CASE__   =   layer_norm_eps
       SCREAMING_SNAKE_CASE__   =   hidden_act
       SCREAMING_SNAKE_CASE__   =   qkv_bias







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

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

       # get the vision config dict if we are loading from Blip2Config
       if config_dict.get('''model_type''' ) == "blip-2":
            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(__lowerCamelCase     ,       **__lowerCamelCase )






class 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "blip_2_qformer"






  def __init__(							self						:		List[Any]     ,       __lowerCamelCase						:		List[str]=3_0522     ,       __lowerCamelCase						:		List[str]=768     ,       __lowerCamelCase						:		Any=12     ,       __lowerCamelCase						:		Tuple=12     ,       __lowerCamelCase						:		Dict=3072     ,       __lowerCamelCase						:		Optional[Any]="gelu"     ,       __lowerCamelCase						:		List[Any]=0.1     ,       __lowerCamelCase						:		List[str]=0.1     ,       __lowerCamelCase						:		Any=512     ,       __lowerCamelCase						:		int=0.02     ,       __lowerCamelCase						:		int=1e-12     ,       __lowerCamelCase						:		Dict=0     ,       __lowerCamelCase						:		Optional[int]="absolute"     ,       __lowerCamelCase						:		List[Any]=2     ,       __lowerCamelCase						:		int=1408     ,       **__lowerCamelCase						:		Dict     ,       )		->							Any:
       super().__init__(pad_token_id=__lowerCamelCase     ,       **__lowerCamelCase )

       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__   =   initializer_range
       SCREAMING_SNAKE_CASE__   =   layer_norm_eps
       SCREAMING_SNAKE_CASE__   =   position_embedding_type
       SCREAMING_SNAKE_CASE__   =   cross_attention_frequency
       SCREAMING_SNAKE_CASE__   =   encoder_hidden_size







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

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

       # get the qformer config dict if we are loading from Blip2Config
       if config_dict.get('''model_type''' ) == "blip-2":
            SCREAMING_SNAKE_CASE__   =   config_dict['''qformer_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 	UpperCAmelCase__		(	A__	):






  """simple docstring"""


  a									= "blip-2"
  a									= True






  def __init__(							self						:		List[Any]     ,       __lowerCamelCase						:		Dict=None     ,       __lowerCamelCase						:		Tuple=None     ,       __lowerCamelCase						:		Any=None     ,       __lowerCamelCase						:		Optional[int]=32     ,       **__lowerCamelCase						:		Union[str, Any] )		->							Tuple:
       super().__init__(**__lowerCamelCase )

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

       if qformer_config is None:
            SCREAMING_SNAKE_CASE__   =   {}
            logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' )

       if text_config is None:
            SCREAMING_SNAKE_CASE__   =   {}
            logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' )

       SCREAMING_SNAKE_CASE__   =   BlipaVisionConfig(**__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   BlipaQFormerConfig(**__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
       SCREAMING_SNAKE_CASE__   =   CONFIG_MAPPING[text_model_type](**__lowerCamelCase )

       SCREAMING_SNAKE_CASE__   =   self.text_config.tie_word_embeddings
       SCREAMING_SNAKE_CASE__   =   self.text_config.is_encoder_decoder

       SCREAMING_SNAKE_CASE__   =   num_query_tokens
       SCREAMING_SNAKE_CASE__   =   self.vision_config.hidden_size
       SCREAMING_SNAKE_CASE__   =   self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
       SCREAMING_SNAKE_CASE__   =   1.0
       SCREAMING_SNAKE_CASE__   =   0.02






  @classmethod
  def 				lowercase_		(							cls						:		Tuple     ,       __lowerCamelCase						:		BlipaVisionConfig     ,       __lowerCamelCase						:		BlipaQFormerConfig     ,       __lowerCamelCase						:		PretrainedConfig     ,       **__lowerCamelCase						:		int     ,       )		->							List[str]:
       return cls(
           vision_config=vision_config.to_dict()     ,       qformer_config=qformer_config.to_dict()     ,       text_config=text_config.to_dict()     ,       **__lowerCamelCase     ,       )







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





import comet  # From: unbabel-comet
import torch

import datasets


_SCREAMING_SNAKE_CASE					:  List[str]             =      datasets.logging.get_logger(__name__)

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

_SCREAMING_SNAKE_CASE					:  Optional[Any]             =      '''\
Crosslingual 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).
With 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.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
'''

_SCREAMING_SNAKE_CASE					:  str             =      '''
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric(\'comet\')
    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use
    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]
    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]
    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results["scores"]])
    [0.19, 0.92]
'''






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






  """simple docstring"""


  def 				lowercase_		(							self						:		List[Any] )		->							List[str]:
       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						:		List[Any]     ,       __lowerCamelCase						:		Dict )		->							Tuple:
       if self.config_name == "default":
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) )
       else:
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model(self.config_name ) )







  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		List[str]     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Dict=None     ,       __lowerCamelCase						:		Optional[int]=False )		->							str:
       if gpus is None:
            SCREAMING_SNAKE_CASE__   =   1 if torch.cuda.is_available() else 0
       SCREAMING_SNAKE_CASE__   =   {'''src''': sources, '''mt''': predictions, '''ref''': references}
       SCREAMING_SNAKE_CASE__   =   [dict(zip(__lowerCamelCase     ,       __lowerCamelCase ) ) for t in zip(*data.values() )]
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   self.scorer.predict(__lowerCamelCase     ,       gpus=__lowerCamelCase     ,       progress_bar=__lowerCamelCase )
       return {"mean_score": mean_score, "scores": scores}


