'''simple docstring'''
from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
      import timm


if is_torch_available():
      from torch import Tensor







class lowerCamelCase							(	lowerCamelCase     ,		lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	'''pixel_values'''
  lowerCAmelCase__										=	False
  lowerCAmelCase__										=	TimmBackboneConfig






  def __init__(      self			:       Optional[Any]  ,							UpperCAmelCase__			:       Dict  ,							**UpperCAmelCase__			:       Any  )				->List[Any]:
        requires_backends(self  ,							'''timm'''  )
        super().__init__(UpperCAmelCase__  )
        UpperCAmelCase_            =  config

        if config.backbone is None:
              raise ValueError('''backbone is not set in the config. Please set it to a timm model name.'''  )

        if config.backbone not in timm.list_models():
              raise ValueError(f"""backbone {config.backbone} is not supported by timm."""  )

        if hasattr(UpperCAmelCase__  ,							'''out_features'''  ) and config.out_features is not None:
              raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''  )

        UpperCAmelCase_            =  getattr(UpperCAmelCase__  ,							'''use_pretrained_backbone'''  ,							UpperCAmelCase__  )
        if pretrained is None:
              raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.'''  )

        # We just take the final layer by default. This matches the default for the transformers models.
        UpperCAmelCase_            =  config.out_indices if getattr(UpperCAmelCase__  ,							'''out_indices'''  ,							UpperCAmelCase__  ) is not None else (-1,)

        UpperCAmelCase_            =  timm.create_model(
            config.backbone  ,							pretrained=UpperCAmelCase__  ,							features_only=config.features_only  ,							in_chans=config.num_channels  ,							out_indices=UpperCAmelCase__  ,							**UpperCAmelCase__  ,							)
        # These are used to control the output of the model when called. If output_hidden_states is True, then
        # return_layers is modified to include all layers.
        UpperCAmelCase_            =  self._backbone.return_layers
        UpperCAmelCase_            =  {layer['''module''']: str(UpperCAmelCase__  ) for i, layer in enumerate(self._backbone.feature_info.info  )}
        super()._init_backbone(UpperCAmelCase__  )






  @classmethod
  def  lowerCAmelCase__ (      cls			:       List[str]  ,							UpperCAmelCase__			:       Optional[int]  ,							*UpperCAmelCase__			:       Union[str, Any]  ,							**UpperCAmelCase__			:       List[Any]  )				->Union[str, Any]:
        requires_backends(cls  ,							['''vision''', '''timm''']  )
        from ...models.timm_backbone import TimmBackboneConfig

        UpperCAmelCase_            =  kwargs.pop('''config'''  ,							TimmBackboneConfig()  )

        UpperCAmelCase_            =  kwargs.pop('''use_timm_backbone'''  ,							UpperCAmelCase__  )
        if not use_timm:
              raise ValueError('''use_timm_backbone must be True for timm backbones'''  )

        UpperCAmelCase_            =  kwargs.pop('''num_channels'''  ,							config.num_channels  )
        UpperCAmelCase_            =  kwargs.pop('''features_only'''  ,							config.features_only  )
        UpperCAmelCase_            =  kwargs.pop('''use_pretrained_backbone'''  ,							config.use_pretrained_backbone  )
        UpperCAmelCase_            =  kwargs.pop('''out_indices'''  ,							config.out_indices  )
        UpperCAmelCase_            =  TimmBackboneConfig(
            backbone=UpperCAmelCase__  ,							num_channels=UpperCAmelCase__  ,							features_only=UpperCAmelCase__  ,							use_pretrained_backbone=UpperCAmelCase__  ,							out_indices=UpperCAmelCase__  ,							)
        return super()._from_config(UpperCAmelCase__  ,							**UpperCAmelCase__  )






  def  lowerCAmelCase__ (      self			:       str  ,							UpperCAmelCase__			:       int  )				->List[str]:
        pass






  def  lowerCAmelCase__ (      self			:       List[Any]  ,							UpperCAmelCase__			:       str  ,							UpperCAmelCase__			:       int=None  ,							UpperCAmelCase__			:       Union[str, Any]=None  ,							UpperCAmelCase__			:       Any=None  ,							**UpperCAmelCase__			:       List[str]  )				->Union[BackboneOutput, Tuple[Tensor, ...]]:
        UpperCAmelCase_            =  return_dict if return_dict is not None else self.config.use_return_dict
        UpperCAmelCase_            =  (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        UpperCAmelCase_            =  output_attentions if output_attentions is not None else self.config.output_attentions

        if output_attentions:
              raise ValueError('''Cannot output attentions for timm backbones at the moment'''  )

        if output_hidden_states:
              # We modify the return layers to include all the stages of the backbone
              UpperCAmelCase_            =  self._all_layers
              UpperCAmelCase_            =  self._backbone(UpperCAmelCase__  ,							**UpperCAmelCase__  )
              UpperCAmelCase_            =  self._return_layers
              UpperCAmelCase_            =  tuple(hidden_states[i] for i in self.out_indices  )
        else:
              UpperCAmelCase_            =  self._backbone(UpperCAmelCase__  ,							**UpperCAmelCase__  )
              UpperCAmelCase_            =  None

        UpperCAmelCase_            =  tuple(UpperCAmelCase__  )
        UpperCAmelCase_            =  tuple(UpperCAmelCase__  ) if hidden_states is not None else None

        if not return_dict:
              UpperCAmelCase_            =  (feature_maps,)
              if output_hidden_states:
                    UpperCAmelCase_            =  output + (hidden_states,)
              return output

        return BackboneOutput(feature_maps=UpperCAmelCase__  ,							hidden_states=UpperCAmelCase__  ,							attentions=UpperCAmelCase__  )






'''simple docstring'''
import comet  # From: unbabel-comet
import torch

import datasets


lowercase__  :      str        =					datasets.logging.get_logger(__name__)

lowercase__  :      Dict        =					"\\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"

lowercase__  :      str        =					"\\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"

lowercase__  :      str        =					"\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 lowerCamelCase							(	datasets.Metric					):




  '''simple docstring'''



  def  lowerCAmelCase__ (      self			:       List[Any]  )				->Any:
        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  lowerCAmelCase__ (      self			:       int  ,							UpperCAmelCase__			:       Union[str, Any]  )				->Any:
        if self.config_name == "default":
              UpperCAmelCase_            =  comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''  )  )
        else:
              UpperCAmelCase_            =  comet.load_from_checkpoint(comet.download_model(self.config_name  )  )






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





