'''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}







'''simple docstring'''







import unittest
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import BridgeTowerImageProcessor




class _SCREAMING_SNAKE_CASE(							unittest.TestCase					):




						def __init__(    self :       Any							,							UpperCamelCase_ :       List[Any]							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Dict[str, int] = None							,							UpperCamelCase_ :       int = 32							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Union[int, float] = 1 / 2_55							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = [0.4814_5466, 0.457_8275, 0.4082_1073]							,							UpperCamelCase_ :       Optional[Union[float, List[float]]] = [0.2686_2954, 0.2613_0258, 0.2757_7711]							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       int=7							,							UpperCamelCase_ :       Dict=30							,							UpperCamelCase_ :       Tuple=4_00							,							UpperCamelCase_ :       List[Any]=3							,							)     ->				List[Any]:
													SCREAMING_SNAKE_CASE__     :List[str]						    = parent
													SCREAMING_SNAKE_CASE__     :Tuple						    = do_resize
													SCREAMING_SNAKE_CASE__     :List[Any]						    = size if size is not None else {'shortest_edge': 2_88}
													SCREAMING_SNAKE_CASE__     :str						    = size_divisor
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = do_rescale
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = rescale_factor
													SCREAMING_SNAKE_CASE__     :str						    = do_normalize
													SCREAMING_SNAKE_CASE__     :int						    = do_center_crop
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = image_mean
													SCREAMING_SNAKE_CASE__     :str						    = image_std
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = do_pad
													SCREAMING_SNAKE_CASE__     :Tuple						    = batch_size
													SCREAMING_SNAKE_CASE__     :List[str]						    = num_channels
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = min_resolution
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = max_resolution




						def      __lowerCamelCase       (    self :       Tuple      )     ->				Optional[int]:
													return {
													    "image_mean": self.image_mean,
													    "image_std": self.image_std,
													    "do_normalize": self.do_normalize,
													    "do_resize": self.do_resize,
													    "size": self.size,
													    "size_divisor": self.size_divisor,
													}




						def      __lowerCamelCase       (    self :       int							,							UpperCamelCase_ :       str							,							UpperCamelCase_ :       str=False      )     ->				Optional[int]:
													if not batched:
																				SCREAMING_SNAKE_CASE__     :Dict						    = self.size['shortest_edge']
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = image_inputs[0]
																				if isinstance(UpperCamelCase_							,							Image.Image      ):
																											SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Optional[int]						    = image.size
																				else:
																											SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :str						    = image.shape[1], image.shape[2]
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = size / min(UpperCamelCase_							,							UpperCamelCase_      )
																				if h < w:
																											SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :List[Any]						    = size, scale * w
																				else:
																											SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :str						    = scale * h, size

																				SCREAMING_SNAKE_CASE__     :Any						    = int((13_33 / 8_00) * size      )
																				if max(UpperCamelCase_							,							UpperCamelCase_      ) > max_size:
																											SCREAMING_SNAKE_CASE__     :Tuple						    = max_size / max(UpperCamelCase_							,							UpperCamelCase_      )
																											SCREAMING_SNAKE_CASE__     :str						    = newh * scale
																											SCREAMING_SNAKE_CASE__     :Any						    = neww * scale

																				SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :int						    = int(newh + 0.5      ), int(neww + 0.5      )
																				SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Optional[Any]						    = (
																				    newh // self.size_divisor * self.size_divisor,
																				    neww // self.size_divisor * self.size_divisor,
																				)

													else:
																				SCREAMING_SNAKE_CASE__     :Any						    = []
																				for image in image_inputs:
																											SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :str						    = self.get_expected_values([image]      )
																											expected_values.append((expected_height, expected_width)      )
																				SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = max(UpperCamelCase_							,							key=lambda UpperCamelCase_      : item[0]      )[0]
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = max(UpperCamelCase_							,							key=lambda UpperCamelCase_      : item[1]      )[1]

													return expected_height, expected_width




@require_torch
@require_vision
class _SCREAMING_SNAKE_CASE(							_SCREAMING_SNAKE_CASE						,						unittest.TestCase					):
						A_			:							List[Any]     		= BridgeTowerImageProcessor if is_vision_available() else None




						def      __lowerCamelCase       (    self :       Optional[Any]      )     ->				str:
													SCREAMING_SNAKE_CASE__     :List[str]						    = BridgeTowerImageProcessingTester(self      )




						@property
						def      __lowerCamelCase       (    self :       int      )     ->				Any:
													return self.image_processor_tester.prepare_image_processor_dict()




						def      __lowerCamelCase       (    self :       int      )     ->				Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.image_processing_class(**self.image_processor_dict      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'image_mean'      )      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'image_std'      )      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'do_normalize'      )      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'do_resize'      )      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'size'      )      )
													self.assertTrue(hasattr(UpperCamelCase_							,							'size_divisor'      )      )




						def      __lowerCamelCase       (    self :       Union[str, Any]      )     ->				List[str]:
													pass




						def      __lowerCamelCase       (    self :       int      )     ->				Dict:
													# Initialize image processor
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.image_processing_class(**self.image_processor_dict      )
													# create random PIL images
													SCREAMING_SNAKE_CASE__     :Any						    = prepare_image_inputs(self.image_processor_tester							,							equal_resolution=UpperCamelCase_      )
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase_							,							Image.Image      )

													# Test not batched input
													SCREAMING_SNAKE_CASE__     :str						    = image_processing(image_inputs[0]							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Dict						    = self.image_processor_tester.get_expected_values(UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,							)

													# Test batched
													SCREAMING_SNAKE_CASE__     :Any						    = image_processing(UpperCamelCase_							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :int						    = self.image_processor_tester.get_expected_values(UpperCamelCase_							,							batched=UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )							,							)




						def      __lowerCamelCase       (    self :       List[Any]      )     ->				Tuple:
													# Initialize image processor
													SCREAMING_SNAKE_CASE__     :Dict						    = self.image_processing_class(**self.image_processor_dict      )
													# create random numpy tensors
													SCREAMING_SNAKE_CASE__     :Tuple						    = prepare_image_inputs(self.image_processor_tester							,							equal_resolution=UpperCamelCase_							,							numpify=UpperCamelCase_      )
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase_							,							np.ndarray      )

													# Test not batched input
													SCREAMING_SNAKE_CASE__     :List[str]						    = image_processing(image_inputs[0]							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :int						    = self.image_processor_tester.get_expected_values(UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,							)

													# Test batched
													SCREAMING_SNAKE_CASE__     :str						    = image_processing(UpperCamelCase_							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Any						    = self.image_processor_tester.get_expected_values(UpperCamelCase_							,							batched=UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )							,							)




						def      __lowerCamelCase       (    self :       List[str]      )     ->				List[Any]:
													# Initialize image processor
													SCREAMING_SNAKE_CASE__     :List[str]						    = self.image_processing_class(**self.image_processor_dict      )
													# create random PyTorch tensors
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = prepare_image_inputs(self.image_processor_tester							,							equal_resolution=UpperCamelCase_							,							torchify=UpperCamelCase_      )
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase_							,							torch.Tensor      )

													# Test not batched input
													SCREAMING_SNAKE_CASE__     :List[str]						    = image_processing(image_inputs[0]							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.image_processor_tester.get_expected_values(UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,							)

													# Test batched
													SCREAMING_SNAKE_CASE__     :List[Any]						    = image_processing(UpperCamelCase_							,							return_tensors='pt'      ).pixel_values

													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :List[Any]						    = self.image_processor_tester.get_expected_values(UpperCamelCase_							,							batched=UpperCamelCase_      )
													self.assertEqual(
													    encoded_images.shape							,							(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )							,							)






