'''simple docstring'''







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCamelCase_      	=	logging.get_logger(__name__)


if is_vision_available():
		import PIL




class _SCREAMING_SNAKE_CASE(							_SCREAMING_SNAKE_CASE					):
						A_			:							Optional[int]     		= ['pixel_values']




						def __init__(    self :       int							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Dict[str, int] = None							,							UpperCamelCase_ :       PILImageResampling = PILImageResampling.BICUBIC							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Dict[str, int] = None							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Union[int, float] = 1 / 2_55							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = None							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = None							,							UpperCamelCase_ :       bool = True							,							**UpperCamelCase_ :       Any							,							)     ->				None:
													super().__init__(**UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :Any						    = size if size is not None else {'shortest_edge': 2_24}
													SCREAMING_SNAKE_CASE__     :Tuple						    = get_size_dict(UpperCamelCase_							,							default_to_square=UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :str						    = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
													SCREAMING_SNAKE_CASE__     :int						    = get_size_dict(UpperCamelCase_							,							default_to_square=UpperCamelCase_							,							param_name='crop_size'      )

													SCREAMING_SNAKE_CASE__     :Tuple						    = do_resize
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = size
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = resample
													SCREAMING_SNAKE_CASE__     :str						    = do_center_crop
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = crop_size
													SCREAMING_SNAKE_CASE__     :int						    = do_rescale
													SCREAMING_SNAKE_CASE__     :str						    = rescale_factor
													SCREAMING_SNAKE_CASE__     :List[Any]						    = do_normalize
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = image_std if image_std is not None else OPENAI_CLIP_STD
													SCREAMING_SNAKE_CASE__     :Tuple						    = do_convert_rgb




						def      __lowerCamelCase       (    self :       List[str]							,							UpperCamelCase_ :       np.ndarray							,							UpperCamelCase_ :       Dict[str, int]							,							UpperCamelCase_ :       PILImageResampling = PILImageResampling.BICUBIC							,							UpperCamelCase_ :       Optional[Union[str, ChannelDimension]] = None							,							**UpperCamelCase_ :       Tuple							,							)     ->				np.ndarray:
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = get_size_dict(UpperCamelCase_							,							default_to_square=UpperCamelCase_      )
													if "shortest_edge" not in size:
																				raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''      )
													SCREAMING_SNAKE_CASE__     :int						    = get_resize_output_image_size(UpperCamelCase_							,							size=size['shortest_edge']							,							default_to_square=UpperCamelCase_      )
													return resize(UpperCamelCase_							,							size=UpperCamelCase_							,							resample=UpperCamelCase_							,							data_format=UpperCamelCase_							,							**UpperCamelCase_      )




						def      __lowerCamelCase       (    self :       Union[str, Any]							,							UpperCamelCase_ :       np.ndarray							,							UpperCamelCase_ :       Dict[str, int]							,							UpperCamelCase_ :       Optional[Union[str, ChannelDimension]] = None							,							**UpperCamelCase_ :       List[str]							,							)     ->				np.ndarray:
													SCREAMING_SNAKE_CASE__     :List[str]						    = get_size_dict(UpperCamelCase_      )
													if "height" not in size or "width" not in size:
																				raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''      )
													return center_crop(UpperCamelCase_							,							size=(size['height'], size['width'])							,							data_format=UpperCamelCase_							,							**UpperCamelCase_      )




						def      __lowerCamelCase       (    self :       int							,							UpperCamelCase_ :       np.ndarray							,							UpperCamelCase_ :       Union[int, float]							,							UpperCamelCase_ :       Optional[Union[str, ChannelDimension]] = None							,							**UpperCamelCase_ :       Optional[int]							,							)     ->				Union[str, Any]:
													return rescale(UpperCamelCase_							,							scale=UpperCamelCase_							,							data_format=UpperCamelCase_							,							**UpperCamelCase_      )




						def      __lowerCamelCase       (    self :       Optional[int]							,							UpperCamelCase_ :       np.ndarray							,							UpperCamelCase_ :       Union[float, List[float]]							,							UpperCamelCase_ :       Union[float, List[float]]							,							UpperCamelCase_ :       Optional[Union[str, ChannelDimension]] = None							,							**UpperCamelCase_ :       Optional[int]							,							)     ->				np.ndarray:
													return normalize(UpperCamelCase_							,							mean=UpperCamelCase_							,							std=UpperCamelCase_							,							data_format=UpperCamelCase_							,							**UpperCamelCase_      )




						def      __lowerCamelCase       (    self :       List[Any]							,							UpperCamelCase_ :       ImageInput							,							UpperCamelCase_ :       bool = None							,							UpperCamelCase_ :       Dict[str, int] = None							,							UpperCamelCase_ :       PILImageResampling = None							,							UpperCamelCase_ :       bool = None							,							UpperCamelCase_ :       int = None							,							UpperCamelCase_ :       bool = None							,							UpperCamelCase_ :       float = None							,							UpperCamelCase_ :       bool = None							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = None							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = None							,							UpperCamelCase_ :       bool = None							,							UpperCamelCase_ :       Optional[Union[str, TensorType]] = None							,							UpperCamelCase_ :       Optional[ChannelDimension] = ChannelDimension.FIRST							,							**UpperCamelCase_ :       Tuple							,							)     ->				PIL.Image.Image:
													SCREAMING_SNAKE_CASE__     :str						    = do_resize if do_resize is not None else self.do_resize
													SCREAMING_SNAKE_CASE__     :List[str]						    = size if size is not None else self.size
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = get_size_dict(UpperCamelCase_							,							param_name='size'							,							default_to_square=UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = resample if resample is not None else self.resample
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = do_center_crop if do_center_crop is not None else self.do_center_crop
													SCREAMING_SNAKE_CASE__     :Dict						    = crop_size if crop_size is not None else self.crop_size
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = get_size_dict(UpperCamelCase_							,							param_name='crop_size'							,							default_to_square=UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :List[Any]						    = do_rescale if do_rescale is not None else self.do_rescale
													SCREAMING_SNAKE_CASE__     :List[Any]						    = rescale_factor if rescale_factor is not None else self.rescale_factor
													SCREAMING_SNAKE_CASE__     :int						    = do_normalize if do_normalize is not None else self.do_normalize
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = image_mean if image_mean is not None else self.image_mean
													SCREAMING_SNAKE_CASE__     :Tuple						    = image_std if image_std is not None else self.image_std
													SCREAMING_SNAKE_CASE__     :List[Any]						    = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

													SCREAMING_SNAKE_CASE__     :str						    = make_list_of_images(UpperCamelCase_      )

													if not valid_images(UpperCamelCase_      ):
																				raise ValueError(
																				    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
																				    'torch.Tensor, tf.Tensor or jax.ndarray.'      )

													if do_resize and size is None:
																				raise ValueError('Size must be specified if do_resize is True.'      )

													if do_center_crop and crop_size is None:
																				raise ValueError('Crop size must be specified if do_center_crop is True.'      )

													if do_rescale and rescale_factor is None:
																				raise ValueError('Rescale factor must be specified if do_rescale is True.'      )

													if do_normalize and (image_mean is None or image_std is None):
																				raise ValueError('Image mean and std must be specified if do_normalize is True.'      )

													# PIL RGBA images are converted to RGB
													if do_convert_rgb:
																				SCREAMING_SNAKE_CASE__     :Tuple						    = [convert_to_rgb(UpperCamelCase_      ) for image in images]

													# All transformations expect numpy arrays.
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = [to_numpy_array(UpperCamelCase_      ) for image in images]

													if do_resize:
																				SCREAMING_SNAKE_CASE__     :Dict						    = [self.resize(image=UpperCamelCase_							,							size=UpperCamelCase_							,							resample=UpperCamelCase_      ) for image in images]

													if do_center_crop:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = [self.center_crop(image=UpperCamelCase_							,							size=UpperCamelCase_      ) for image in images]

													if do_rescale:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = [self.rescale(image=UpperCamelCase_							,							scale=UpperCamelCase_      ) for image in images]

													if do_normalize:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = [self.normalize(image=UpperCamelCase_							,							mean=UpperCamelCase_							,							std=UpperCamelCase_      ) for image in images]

													SCREAMING_SNAKE_CASE__     :Dict						    = [to_channel_dimension_format(UpperCamelCase_							,							UpperCamelCase_      ) for image in images]

													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = {'pixel_values': images}
													return BatchFeature(data=UpperCamelCase_							,							tensor_type=UpperCamelCase_      )







'''simple docstring'''







import comet  # From: unbabel-comet
import torch

import datasets


UpperCamelCase_      	=	datasets.logging.get_logger(__name__)

UpperCamelCase_      	=	'''\
@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",
}
'''

UpperCamelCase_      	=	'''\
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.
'''

UpperCamelCase_      	=	'''
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 _SCREAMING_SNAKE_CASE(							datasets.Metric					):




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




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






