

"""simple docstring"""




import comet  # From: unbabel-comet
import torch

import datasets


A_				:      Dict           =			datasets.logging.get_logger(__name__)

A_				:      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"

A_				:      int           =			"\\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"

A_				:      int           =			"\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      ):

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[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        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]     ,					__UpperCAmelCase					:    Optional[Any]							) ->     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        SCREAMING_SNAKE_CASE					(       self					:    List[Any]     ,					__UpperCAmelCase					:    Optional[int]     ,					__UpperCAmelCase					:    Tuple     ,					__UpperCAmelCase					:    List[str]     ,					__UpperCAmelCase					:    int=None     ,					__UpperCAmelCase					:    Optional[int]=False							) ->     Union[str, Any]:
						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(__UpperCAmelCase     ,					__UpperCAmelCase							)							) for t in zip(*data.values()							)]
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.scorer.predict(__UpperCAmelCase     ,					gpus=__UpperCAmelCase     ,					progress_bar=__UpperCAmelCase							)
						return {"mean_score": mean_score, "scores": scores}





"""simple docstring"""




import unittest

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 MobileViTImageProcessor





class  lowerCamelCase    (unittest.TestCase      ):

			def __init__(       self					:    Tuple     ,					__UpperCAmelCase					:    str     ,					__UpperCAmelCase					:    Any=7     ,					__UpperCAmelCase					:    Union[str, Any]=3     ,					__UpperCAmelCase					:    Any=1_8     ,					__UpperCAmelCase					:    Tuple=3_0     ,					__UpperCAmelCase					:    List[Any]=4_0_0     ,					__UpperCAmelCase					:    Dict=True     ,					__UpperCAmelCase					:    int=None     ,					__UpperCAmelCase					:    List[Any]=True     ,					__UpperCAmelCase					:    Any=None     ,					__UpperCAmelCase					:    Any=True     ,					) ->     Tuple:
						SCREAMING_SNAKE_CASE__										=   size if size is not None else {"""shortest_edge""": 2_0}
						SCREAMING_SNAKE_CASE__										=   crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}
						SCREAMING_SNAKE_CASE__										=   parent
						SCREAMING_SNAKE_CASE__										=   batch_size
						SCREAMING_SNAKE_CASE__										=   num_channels
						SCREAMING_SNAKE_CASE__										=   image_size
						SCREAMING_SNAKE_CASE__										=   min_resolution
						SCREAMING_SNAKE_CASE__										=   max_resolution
						SCREAMING_SNAKE_CASE__										=   do_resize
						SCREAMING_SNAKE_CASE__										=   size
						SCREAMING_SNAKE_CASE__										=   do_center_crop
						SCREAMING_SNAKE_CASE__										=   crop_size
						SCREAMING_SNAKE_CASE__										=   do_flip_channel_order





			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Any:
						return {
						    "do_resize": self.do_resize,
						    "size": self.size,
						    "do_center_crop": self.do_center_crop,
						    "crop_size": self.crop_size,
						    "do_flip_channel_order": self.do_flip_channel_order,
						}





@require_torch
@require_vision
class  lowerCamelCase    (A__      ,unittest.TestCase      ):
			lowerCamelCase__ :		Tuple       		=				MobileViTImageProcessor if is_vision_available() else None

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   MobileViTImageProcessingTester(self							)

			@property
			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     int:
						return self.image_processor_tester.prepare_image_processor_dict()

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__										=   self.image_processing_class(**self.image_processor_dict							)
						self.assertTrue(hasattr(__UpperCAmelCase     ,					"""do_resize"""							)							)
						self.assertTrue(hasattr(__UpperCAmelCase     ,					"""size"""							)							)
						self.assertTrue(hasattr(__UpperCAmelCase     ,					"""do_center_crop"""							)							)
						self.assertTrue(hasattr(__UpperCAmelCase     ,					"""center_crop"""							)							)
						self.assertTrue(hasattr(__UpperCAmelCase     ,					"""do_flip_channel_order"""							)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   self.image_processing_class.from_dict(self.image_processor_dict							)
						self.assertEqual(image_processor.size     ,					{"""shortest_edge""": 2_0}							)
						self.assertEqual(image_processor.crop_size     ,					{"""height""": 1_8, """width""": 1_8}							)

						SCREAMING_SNAKE_CASE__										=   self.image_processing_class.from_dict(self.image_processor_dict     ,					size=4_2     ,					crop_size=8_4							)
						self.assertEqual(image_processor.size     ,					{"""shortest_edge""": 4_2}							)
						self.assertEqual(image_processor.crop_size     ,					{"""height""": 8_4, """width""": 8_4}							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Dict:
						pass

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     List[str]:
						# Initialize image_processing
						SCREAMING_SNAKE_CASE__										=   self.image_processing_class(**self.image_processor_dict							)
						# create random PIL images
						SCREAMING_SNAKE_CASE__										=   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__										=   image_processing(image_inputs[0]     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)

						# Test batched
						SCREAMING_SNAKE_CASE__										=   image_processing(__UpperCAmelCase     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Optional[int]:
						# Initialize image_processing
						SCREAMING_SNAKE_CASE__										=   self.image_processing_class(**self.image_processor_dict							)
						# create random numpy tensors
						SCREAMING_SNAKE_CASE__										=   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__										=   image_processing(image_inputs[0]     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)

						# Test batched
						SCREAMING_SNAKE_CASE__										=   image_processing(__UpperCAmelCase     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)





			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     str:
						# Initialize image_processing
						SCREAMING_SNAKE_CASE__										=   self.image_processing_class(**self.image_processor_dict							)
						# create random PyTorch tensors
						SCREAMING_SNAKE_CASE__										=   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__										=   image_processing(image_inputs[0]     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)

						# Test batched
						SCREAMING_SNAKE_CASE__										=   image_processing(__UpperCAmelCase     ,					return_tensors="""pt"""							).pixel_values
						self.assertEqual(
						    encoded_images.shape     ,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["""height"""],
						        self.image_processor_tester.crop_size["""width"""],
						    )     ,					)


