


from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


SCREAMING_SNAKE_CASE							    =							logging.get_logger(__name__)




def  a   (lowerCAmelCase__   ):
   if isinstance(lowerCAmelCase__		,				np.ndarray   ):
      return list(tensor.shape   )

   __a					=  tf.shape(lowerCAmelCase__   )

   if tensor.shape == tf.TensorShape(lowerCAmelCase__   ):
      return dynamic

   __a					=  tensor.shape.as_list()

   return [dynamic[i] if s is None else s for i, s in enumerate(lowerCAmelCase__   )]




def  a   (lowerCAmelCase__		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None   ):
   return tf.nn.softmax(logits=logits + 1E-9		,				axis=lowerCAmelCase__		,				name=lowerCAmelCase__   )




def  a   (lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__=1E-5		,				lowerCAmelCase__=-1   ):
   # This is a very simplified functional layernorm, designed to duplicate
   # the functionality of PyTorch nn.functional.layer_norm when this is needed to port
   # models in Transformers.

   if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCAmelCase__		,				lowerCAmelCase__   ):
      raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis."""   )

   # Get mean and variance on the axis to be normalized
   __a	,    __a					=  tf.nn.moments(lowerCAmelCase__		,				axes=[axis]		,				keepdims=lowerCAmelCase__   )

   if axis != -1:
      # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
      # on every dimension except axis
      __a					=  [1] * inputs.shape.rank
      __a					=  shape_list(lowerCAmelCase__   )[axis]
      __a					=  tf.reshape(lowerCAmelCase__		,				lowerCAmelCase__   )
      __a					=  tf.reshape(lowerCAmelCase__		,				lowerCAmelCase__   )

   # Compute layer normalization using the batch_normalization
   # function.
   __a					=  tf.nn.batch_normalization(
       lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				offset=lowerCAmelCase__		,				scale=lowerCAmelCase__		,				variance_epsilon=lowerCAmelCase__		,				)
   return outputs




def  a   (lowerCAmelCase__		,				lowerCAmelCase__=0		,				lowerCAmelCase__=-1   ):
   # Replicates the behavior of torch.flatten in TF

   # If end_dim or start_dim is negative, count them from the end
   if end_dim < 0:
      end_dim += input.shape.rank
   if start_dim < 0:
      start_dim += input.shape.rank

   if start_dim == end_dim:
      return input

   __a					=  tf.shape(lowerCAmelCase__   )
   __a					=  tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]   )
   __a					=  tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]		,				axis=0   )
   return tf.reshape(lowerCAmelCase__		,				lowerCAmelCase__   )




def  a   (lowerCAmelCase__   ):
   if not isinstance(lowerCAmelCase__		,				tf.Tensor   ):
      __a					=  tf.convert_to_tensor(lowerCAmelCase__   )  # Catches stray NumPy inputs
   if encoder_attention_mask.shape.rank == 3:
      __a					=  encoder_attention_mask[:, None, :, :]
   if encoder_attention_mask.shape.rank == 2:
      __a					=  encoder_attention_mask[:, None, None, :]
   # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
   # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
   # /transformer/transformer_layers.py#L270
   # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
   # encoder_extended_attention_mask.transpose(-1, -2))
   __a					=  (
       tf.cast(1		,				encoder_attention_mask.dtype   ) - encoder_extended_attention_mask
   ) * encoder_extended_attention_mask.dtype.min

   return encoder_extended_attention_mask




def  a   (lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = "input_ids"   ):
   tf.debugging.assert_less(
       lowerCAmelCase__		,				tf.cast(lowerCAmelCase__		,				dtype=tensor.dtype   )		,				message=(
           f'''The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCAmelCase__   )}) must be smaller than the embedding '''
           f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
       )		,				)




def  a   (lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__   ):
   __a					=  64_512
   # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
   # because in that case even chunking the array would not make the saving
   # possible.
   __a					=  [x for x in data if len(lowerCAmelCase__   ) > HDF5_OBJECT_HEADER_LIMIT]

   # Expecting this to never be true.
   if bad_attributes:
      raise RuntimeError(
          """The following attributes cannot be saved to HDF5 file because """
          f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
          f'''bytes: {bad_attributes}'''   )

   __a					=  np.asarray(lowerCAmelCase__   )

   __a					=  1
   __a					=  np.array_split(lowerCAmelCase__		,				lowerCAmelCase__   )

   # This will never loop forever thanks to the test above.
   while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data   ):
      num_chunks += 1
      __a					=  np.array_split(lowerCAmelCase__		,				lowerCAmelCase__   )

   if num_chunks > 1:
      for chunk_id, chunk_data in enumerate(lowerCAmelCase__   ):
         __a					=  chunk_data
   else:
      __a					=  data




def  a   (lowerCAmelCase__		,				lowerCAmelCase__   ):
   if name in group.attrs:
      __a					=  [n.decode("""utf8"""   ) if hasattr(lowerCAmelCase__		,				"""decode"""   ) else n for n in group.attrs[name]]
   else:
      __a					=  []
      __a					=  0
      while "%s%d" % (name, chunk_id) in group.attrs:
         data.extend(
             [n.decode("""utf8"""   ) if hasattr(lowerCAmelCase__		,				"""decode"""   ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]]   )
         chunk_id += 1
   return data




def  a   (lowerCAmelCase__   ):

   def _expand_single_ad_tensor(lowerCAmelCase__   ):
      if isinstance(lowerCAmelCase__		,				tf.Tensor   ) and t.shape.rank == 1:
         return tf.expand_dims(lowerCAmelCase__		,				axis=-1   )
      return t

   return tf.nest.map_structure(_expand_single_ad_tensor		,				lowerCAmelCase__   )







import comet  # From: unbabel-comet
import torch

import datasets


SCREAMING_SNAKE_CASE							    =							datasets.logging.get_logger(__name__)

SCREAMING_SNAKE_CASE							    =							'\\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'

SCREAMING_SNAKE_CASE							    =							'\\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'

SCREAMING_SNAKE_CASE							    =							'\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     __UpperCAmelCase							(       datasets.Metric							):


     """simple docstring"""


     def 	snake_case_  (	self    ):
        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 	snake_case_  (	self  ,       __A    ):
        if self.config_name == "default":
           __a					=  comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""    )    )
        else:
           __a					=  comet.load_from_checkpoint(comet.download_model(self.config_name    )    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A  ,       __A=None  ,       __A=False    ):
        if gpus is None:
           __a					=  1 if torch.cuda.is_available() else 0
        __a					=  {"""src""": sources, """mt""": predictions, """ref""": references}
        __a					=  [dict(zip(__A  ,       __A    )    ) for t in zip(*data.values()    )]
        __a	,    __a					=  self.scorer.predict(__A  ,       gpus=__A  ,       progress_bar=__A    )
        return {"mean_score": mean_score, "scores": scores}



