





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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


SCREAMING_SNAKE_CASE__							:      Dict         =    logging.get_logger(__name__)






def    _A	(   lowerCamelCase				,			lowerCamelCase ):
   a__						:    List[Any]   		=	b.T
   a__						:    Tuple   		=	np.sum(np.square(lowerCamelCase )				,			axis=1 )
   a__						:    int   		=	np.sum(np.square(lowerCamelCase )				,			axis=0 )
   a__						:    Any   		=	np.matmul(lowerCamelCase				,			lowerCamelCase )
   a__						:    str   		=	aa[:, None] - 2 * ab + ba[None, :]
   return d






def    _A	(   lowerCamelCase				,			lowerCamelCase ):
   a__						:    Tuple   		=	x.reshape(-1				,			3 )
   a__						:    Union[str, Any]   		=	squared_euclidean_distance(lowerCamelCase				,			lowerCamelCase )
   return np.argmin(lowerCamelCase				,			axis=1 )







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    List[Any]  		=					["""pixel_values"""]





   def __init__(			self       ,      snake_case = None       ,      snake_case = True       ,      snake_case = None       ,      snake_case = PILImageResampling.BILINEAR       ,      snake_case = True       ,      snake_case = True       ,      **snake_case       ,      )					->	None:
      """simple docstring"""





      super().__init__(**snake_case   )
      a__						:    str   		=	size if size is not None else {"height": 256, "width": 256}
      a__						:    Any   		=	get_size_dict(snake_case   )
      a__						:    int   		=	np.array(snake_case   ) if clusters is not None else None
      a__						:    Union[str, Any]   		=	do_resize
      a__						:    Tuple   		=	size
      a__						:    Dict   		=	resample
      a__						:    Tuple   		=	do_normalize
      a__						:    Optional[int]   		=	do_color_quantize





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = PILImageResampling.BILINEAR       ,      snake_case = None       ,      **snake_case       ,      )					->	np.ndarray:
      """simple docstring"""





      a__						:    Tuple   		=	get_size_dict(snake_case   )
      if "height" not in size or "width" not in size:
         raise ValueError(F"""Size dictionary must contain both height and width keys. Got {size.keys()}"""   )
      return resize(
          snake_case       ,      size=(size["height"], size["width"])       ,      resample=snake_case       ,      data_format=snake_case       ,      **snake_case   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None       ,      )					->	np.ndarray:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	rescale(image=snake_case       ,      scale=1 / 127.5       ,      data_format=snake_case   )
      a__						:    List[str]   		=	image - 1
      return image





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = ChannelDimension.FIRST       ,      **snake_case       ,      )					->	PIL.Image.Image:
      """simple docstring"""





      a__						:    str   		=	do_resize if do_resize is not None else self.do_resize
      a__						:    Optional[Any]   		=	size if size is not None else self.size
      a__						:    List[Any]   		=	get_size_dict(snake_case   )
      a__						:    str   		=	resample if resample is not None else self.resample
      a__						:    str   		=	do_normalize if do_normalize is not None else self.do_normalize
      a__						:    List[str]   		=	do_color_quantize if do_color_quantize is not None else self.do_color_quantize
      a__						:    Optional[Any]   		=	clusters if clusters is not None else self.clusters
      a__						:    str   		=	np.array(snake_case   )

      a__						:    Union[str, Any]   		=	make_list_of_images(snake_case   )

      if not valid_images(snake_case   ):
         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 or resample is None:
         raise ValueError("Size and resample must be specified if do_resize is True."   )

      if do_color_quantize and clusters is None:
         raise ValueError("Clusters must be specified if do_color_quantize is True."   )

      # All transformations expect numpy arrays.
      a__						:    str   		=	[to_numpy_array(snake_case   ) for image in images]

      if do_resize:
         a__						:    int   		=	[self.resize(image=snake_case       ,      size=snake_case       ,      resample=snake_case   ) for image in images]

      if do_normalize:
         a__						:    str   		=	[self.normalize(image=snake_case   ) for image in images]

      if do_color_quantize:
         a__						:    Optional[int]   		=	[to_channel_dimension_format(snake_case       ,      ChannelDimension.LAST   ) for image in images]
         # color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
         a__						:    str   		=	np.array(snake_case   )
         a__						:    Optional[int]   		=	color_quantize(snake_case       ,      snake_case   ).reshape(images.shape[:-1]   )

         # flatten to (batch_size, height*width)
         a__						:    Any   		=	images.shape[0]
         a__						:    Optional[Any]   		=	images.reshape(snake_case       ,      -1   )

         # We need to convert back to a list of images to keep consistent behaviour across processors.
         a__						:    Dict   		=	list(snake_case   )
      else:
         a__						:    Optional[Any]   		=	[to_channel_dimension_format(snake_case       ,      snake_case   ) for image in images]

      a__						:    Optional[int]   		=	{"input_ids": images}
      return BatchFeature(data=snake_case       ,      tensor_type=snake_case   )








import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


SCREAMING_SNAKE_CASE__							:      List[Any]         =    """\
@inproceedings{snover-etal-2006-study,
    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",
    author = \"Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John\",
    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",
    month = aug # \" 8-12\",
    year = \"2006\",
    address = \"Cambridge, Massachusetts, USA\",
    publisher = \"Association for Machine Translation in the Americas\",
    url = \"https://aclanthology.org/2006.amta-papers.25\",
    pages = \"223--231\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    """\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
"""

SCREAMING_SNAKE_CASE__							:      int         =    """
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    'score' (float): TER score (num_edits / sum_ref_lengths * 100)
    'num_edits' (int): The cumulative number of edits
    'ref_length' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\",
        ...                     \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}

    Example 2:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}

    Example 3:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}

    Example 4:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}

    Example 5:
        >>> predictions = [\"does this sentence match??\",
        ...                    \"what about this sentence?\",
        ...                    \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}
"""







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,_KWARGS_DESCRIPTION	)
class 	__lowerCAmelCase      (       datasets.Metric	):





   def 						_snake_case			(			self   )					->	Optional[int]:
      """simple docstring"""





      if version.parse(scb.__version__   ) < version.parse("1.4.12"   ):
         raise ImportWarning(
             "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
             "You can install it with `pip install \"sacrebleu>=1.4.12\"`."   )
      return datasets.MetricInfo(
          description=_DESCRIPTION       ,      citation=_CITATION       ,      homepage="http://www.cs.umd.edu/~snover/tercom/"       ,      inputs_description=_KWARGS_DESCRIPTION       ,      features=datasets.Features(
              {
                  "predictions": datasets.Value("string"       ,      id="sequence"   ),
                  "references": datasets.Sequence(datasets.Value("string"       ,      id="sequence"   )       ,      id="references"   ),
              }   )       ,      codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]       ,      reference_urls=[
              "https://github.com/jhclark/tercom",
          ]       ,      )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = False       ,      snake_case = False       ,      snake_case = False       ,      snake_case = False       ,      )					->	Optional[Any]:
      """simple docstring"""





      a__						:    int   		=	len(references[0]   )
      if any(len(snake_case   ) != references_per_prediction for refs in references   ):
         raise ValueError("Sacrebleu requires the same number of references for each prediction"   )
      a__						:    int   		=	[[refs[i] for refs in references] for i in range(snake_case   )]

      a__						:    Optional[Any]   		=	TER(
          normalized=snake_case       ,      no_punct=snake_case       ,      asian_support=snake_case       ,      case_sensitive=snake_case       ,      )
      a__						:    Union[str, Any]   		=	sb_ter.corpus_score(snake_case       ,      snake_case   )

      return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}

