






from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
	from PIL import Image

	from ..image_utils import load_image

if is_torch_available():
	import torch

	from transformers.modeling_outputs import BaseModelOutput

	from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

a__       =     logging.get_logger(__name__)


@add_end_docstrings(lowercase_      )
class    _lowerCAmelCase			(		lowercase_      ):



				"""simple docstring"""



				def __init__(      self    :    Dict			,		**UpperCamelCase__    :    List[Any]):






											'''simple docstring'''







											super().__init__(**UpperCamelCase__)

											if self.framework == "tf":
																		raise ValueError(F'''The {self.__class__} is only available in PyTorch.''')

											requires_backends(self			,		"""vision""")
											self.check_model_type(UpperCamelCase__)



				def __call__(      self    :    Optional[int]			,		UpperCamelCase__    :    Union[str, "Image.Image", List[Dict[str, Any]]]			,		UpperCamelCase__    :    Union[str, List[str]] = None			,		**UpperCamelCase__    :    str			,		):






											'''simple docstring'''







											if "text_queries" in kwargs:
																		snake_case__	  =       kwargs.pop("""text_queries""")

											if isinstance(UpperCamelCase__			,		(str, Image.Image)):
																		snake_case__	  =       {"""image""": image, """candidate_labels""": candidate_labels}
											else:
																		snake_case__	  =       image
											snake_case__	  =       super().__call__(UpperCamelCase__			,		**UpperCamelCase__)
											return results



				def 					__magic_name__							(      self    :    Tuple			,		**UpperCamelCase__    :    str):






											'''simple docstring'''







											snake_case__	  =       {}
											if "threshold" in kwargs:
																		snake_case__	  =       kwargs["""threshold"""]
											if "top_k" in kwargs:
																		snake_case__	  =       kwargs["""top_k"""]
											return {}, {}, postprocess_params



				def 					__magic_name__							(      self    :    int			,		UpperCamelCase__    :    int):






											'''simple docstring'''







											snake_case__	  =       load_image(inputs["""image"""])
											snake_case__	  =       inputs["""candidate_labels"""]
											if isinstance(UpperCamelCase__			,		UpperCamelCase__):
																		snake_case__	  =       candidate_labels.split(""",""")

											snake_case__	  =       torch.tensor([[image.height, image.width]]			,		dtype=torch.intaa)
											for i, candidate_label in enumerate(UpperCamelCase__):
																		snake_case__	  =       self.tokenizer(UpperCamelCase__			,		return_tensors=self.framework)
																		snake_case__	  =       self.image_processor(UpperCamelCase__			,		return_tensors=self.framework)
																		yield {
																		    "is_last": i == len(UpperCamelCase__) - 1,
																		    "target_size": target_size,
																		    "candidate_label": candidate_label,
																		    **text_inputs,
																		    **image_features,
																		}



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






											'''simple docstring'''







											snake_case__	  =       model_inputs.pop("""target_size""")
											snake_case__	  =       model_inputs.pop("""candidate_label""")
											snake_case__	  =       model_inputs.pop("""is_last""")

											snake_case__	  =       self.model(**UpperCamelCase__)

											snake_case__	  =       {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
											return model_outputs



				def 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    List[str]=0.1			,		UpperCamelCase__    :    Optional[Any]=None):






											'''simple docstring'''







											snake_case__	  =       []
											for model_output in model_outputs:
																		snake_case__	  =       model_output["""candidate_label"""]
																		snake_case__	  =       BaseModelOutput(UpperCamelCase__)
																		snake_case__	  =       self.image_processor.post_process_object_detection(
																		    outputs=UpperCamelCase__			,		threshold=UpperCamelCase__			,		target_sizes=model_output["""target_size"""])[0]

																		for index in outputs["scores"].nonzero():
																									snake_case__	  =       outputs["""scores"""][index].item()
																									snake_case__	  =       self._get_bounding_box(outputs["""boxes"""][index][0])

																									snake_case__	  =       {"""score""": score, """label""": label, """box""": box}
																									results.append(UpperCamelCase__)

											snake_case__	  =       sorted(UpperCamelCase__			,		key=lambda UpperCamelCase__: x["score"]			,		reverse=UpperCamelCase__)
											if top_k:
																		snake_case__	  =       results[:top_k]

											return results



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    "torch.Tensor"):






											'''simple docstring'''







											if self.framework != "pt":
																		raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""")
											snake_case__  , snake_case__  , snake_case__  , snake_case__	  =       box.int().tolist()
											snake_case__	  =       {
											    """xmin""": xmin,
											    """ymin""": ymin,
											    """xmax""": xmax,
											    """ymax""": ymax,
											}
											return bbox








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}
