






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      ):



				"""simple docstring"""



				def __init__(      self    :    Union[str, Any]			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Optional[Any]=7			,		UpperCamelCase__    :    Optional[int]=3			,		UpperCamelCase__    :    int=1_8			,		UpperCamelCase__    :    Optional[Any]=3_0			,		UpperCamelCase__    :    int=4_0_0			,		UpperCamelCase__    :    Tuple=True			,		UpperCamelCase__    :    Tuple=None			,		UpperCamelCase__    :    str=True			,		UpperCamelCase__    :    Any=None			,		UpperCamelCase__    :    List[Any]=True			,		):






											'''simple docstring'''







											snake_case__	  =       size if size is not None else {"""shortest_edge""": 2_0}
											snake_case__	  =       crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}
											snake_case__	  =       parent
											snake_case__	  =       batch_size
											snake_case__	  =       num_channels
											snake_case__	  =       image_size
											snake_case__	  =       min_resolution
											snake_case__	  =       max_resolution
											snake_case__	  =       do_resize
											snake_case__	  =       size
											snake_case__	  =       do_center_crop
											snake_case__	  =       crop_size
											snake_case__	  =       do_flip_channel_order



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											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			(		lowercase_     ,      unittest.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Union[str, Any]      =  MobileViTImageProcessor if is_vision_available() else None



				def 					__magic_name__							(      self    :    int):






											'''simple docstring'''







											snake_case__	  =       MobileViTImageProcessingTester(self)



				@property
				def 					__magic_name__							(      self    :    int):






											'''simple docstring'''







											return self.image_processor_tester.prepare_image_processor_dict()



				def 					__magic_name__							(      self    :    Optional[int]):






											'''simple docstring'''







											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 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







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

											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 					__magic_name__							(      self    :    int):






											'''simple docstring'''







											pass



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											snake_case__	  =       self.image_processing_class(**self.image_processor_dict)
											# create random PIL images
											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
											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
											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 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       self.image_processing_class(**self.image_processor_dict)
											# create random numpy tensors
											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
											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
											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 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       self.image_processing_class(**self.image_processor_dict)
											# create random PyTorch tensors
											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
											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
											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"""],
											    )			,		)








import comet  # From: unbabel-comet
import torch

import datasets


a__       =     datasets.logging.get_logger(__name__)

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

a__       =     """\
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.
"""

a__       =     """
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    _lowerCAmelCase			(		datasets.Metric      ):



				"""simple docstring"""



				def 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







											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 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    Dict):






											'''simple docstring'''







											if self.config_name == "default":
																		snake_case__	  =       comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""))
											else:
																		snake_case__	  =       comet.load_from_checkpoint(comet.download_model(self.config_name))



				def 					__magic_name__							(      self    :    List[str]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    int=None			,		UpperCamelCase__    :    List[Any]=False):






											'''simple docstring'''







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