
'''simple docstring'''





from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
  import PIL

lowercase_	 =						logging.get_logger(__name__)




def lowerCAmelCase						(__A):



     """simple docstring"""



     if isinstance(SCREAMING_SNAKE_CASE_						,			(list, tuple)) and isinstance(videos[0]						,			(list, tuple)) and is_valid_image(videos[0][0]):
          return videos

     elif isinstance(SCREAMING_SNAKE_CASE_						,			(list, tuple)) and is_valid_image(videos[0]):
          return [videos]

     elif is_valid_image(SCREAMING_SNAKE_CASE_):
          return [[videos]]

     raise ValueError(F'''Could not make batched video from {videos}''')






class __A    (						_UpperCAmelCase		):



 '''simple docstring'''







 __lowerCamelCase					: List[Any]    = ['pixel_values']



 def __init__(self				,     A = True				,     A = None				,     A = PILImageResampling.BILINEAR				,     A = True				,     A = None				,     A = True				,     A = 1 / 255				,     A = True				,     A = True				,     A = None				,     A = None				,     **A				,     )					->  Any:


      """simple docstring"""



      super().__init__(**lowercase__ )
      _a											=						size if size is not None else {"shortest_edge": 256}
      _a											=						get_size_dict(lowercase__				,     default_to_square=lowercase__ )
      _a											=						crop_size if crop_size is not None else {"height": 224, "width": 224}
      _a											=						get_size_dict(lowercase__				,     param_name='''crop_size''' )

      _a											=						do_resize
      _a											=						size
      _a											=						do_center_crop
      _a											=						crop_size
      _a											=						resample
      _a											=						do_rescale
      _a											=						rescale_factor
      _a											=						offset
      _a											=						do_normalize
      _a											=						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      _a											=						image_std if image_std is not None else IMAGENET_STANDARD_STD



 def       a__						(self				,     A				,     A				,     A = PILImageResampling.BILINEAR				,     A = None				,     **A				,     )					->  Optional[Any]:


      """simple docstring"""



      _a											=						get_size_dict(lowercase__				,     default_to_square=lowercase__ )
      if "shortest_edge" in size:
           _a											=						get_resize_output_image_size(lowercase__				,     size['''shortest_edge''']				,     default_to_square=lowercase__ )
      elif "height" in size and "width" in size:
           _a											=						(size["height"], size["width"])
      else:
           raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
      return resize(lowercase__				,     size=lowercase__				,     resample=lowercase__				,     data_format=lowercase__				,     **lowercase__ )



 def       a__						(self				,     A				,     A				,     A = None				,     **A				,     )					->  Optional[int]:


      """simple docstring"""



      _a											=						get_size_dict(lowercase__ )
      if "height" not in size or "width" not in size:
           raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' )
      return center_crop(lowercase__				,     size=(size['''height'''], size['''width'''])				,     data_format=lowercase__				,     **lowercase__ )



 def       a__						(self				,     A				,     A				,     A = True				,     A = None				,     **A				,     )					->  List[Any]:


      """simple docstring"""



      _a											=						image.astype(np.floataa )
      if offset:
           _a											=						image - (scale / 2)
      return rescale(lowercase__				,     scale=lowercase__				,     data_format=lowercase__				,     **lowercase__ )



 def       a__						(self				,     A				,     A				,     A				,     A = None				,     **A				,     )					->  Tuple:


      """simple docstring"""



      return normalize(lowercase__				,     mean=lowercase__				,     std=lowercase__				,     data_format=lowercase__				,     **lowercase__ )



 def       a__						(self				,     A				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = ChannelDimension.FIRST				,     )					->  Optional[Any]:


      """simple docstring"""



      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_center_crop and crop_size is None:
           raise ValueError('''Crop size must be specified if do_center_crop is True.''' )

      if do_rescale and rescale_factor is None:
           raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )

      if do_normalize and (image_mean is None or image_std is None):
           raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )

      if offset and not do_rescale:
           raise ValueError('''For offset, do_rescale must also be set to True.''' )

      # All transformations expect numpy arrays.
      _a											=						to_numpy_array(lowercase__ )

      if do_resize:
           _a											=						self.resize(image=lowercase__				,     size=lowercase__				,     resample=lowercase__ )

      if do_center_crop:
           _a											=						self.center_crop(lowercase__				,     size=lowercase__ )

      if do_rescale:
           _a											=						self.rescale(image=lowercase__				,     scale=lowercase__				,     offset=lowercase__ )

      if do_normalize:
           _a											=						self.normalize(image=lowercase__				,     mean=lowercase__				,     std=lowercase__ )

      _a											=						to_channel_dimension_format(lowercase__				,     lowercase__ )
      return image



 def       a__						(self				,     A				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = None				,     A = ChannelDimension.FIRST				,     **A				,     )					->  Optional[Any]:


      """simple docstring"""



      _a											=						do_resize if do_resize is not None else self.do_resize
      _a											=						resample if resample is not None else self.resample
      _a											=						do_center_crop if do_center_crop is not None else self.do_center_crop
      _a											=						do_rescale if do_rescale is not None else self.do_rescale
      _a											=						rescale_factor if rescale_factor is not None else self.rescale_factor
      _a											=						offset if offset is not None else self.offset
      _a											=						do_normalize if do_normalize is not None else self.do_normalize
      _a											=						image_mean if image_mean is not None else self.image_mean
      _a											=						image_std if image_std is not None else self.image_std

      _a											=						size if size is not None else self.size
      _a											=						get_size_dict(lowercase__				,     default_to_square=lowercase__ )
      _a											=						crop_size if crop_size is not None else self.crop_size
      _a											=						get_size_dict(lowercase__				,     param_name='''crop_size''' )

      if not valid_images(lowercase__ ):
           raise ValueError(
               '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
               '''torch.Tensor, tf.Tensor or jax.ndarray.''' )

      _a											=						make_batched(lowercase__ )

      _a											=						[
          [
              self._preprocess_image(
                  image=lowercase__				,     do_resize=lowercase__				,     size=lowercase__				,     resample=lowercase__				,     do_center_crop=lowercase__				,     crop_size=lowercase__				,     do_rescale=lowercase__				,     rescale_factor=lowercase__				,     offset=lowercase__				,     do_normalize=lowercase__				,     image_mean=lowercase__				,     image_std=lowercase__				,     data_format=lowercase__				,     )
              for img in video
          ]
          for video in videos
      ]

      _a											=						{"pixel_values": videos}
      return BatchFeature(data=lowercase__				,     tensor_type=lowercase__ )








'''simple docstring'''





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


lowercase_	 =						"\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

lowercase_	 =						"\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

lowercase_	 =						"\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"






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



 '''simple docstring'''







 def       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      return datasets.MetricInfo(
          description=_DESCRIPTION				,     citation=_CITATION				,     inputs_description=_KWARGS_DESCRIPTION				,     features=datasets.Features(
              {
                  '''predictions''': datasets.Sequence(datasets.Value('''string'''				,     id='''token''' )				,     id='''sequence''' ),
                  '''references''': datasets.Sequence(
                      datasets.Sequence(datasets.Value('''string'''				,     id='''token''' )				,     id='''sequence''' )				,     id='''references''' ),
              } )				,     codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py''']				,     reference_urls=[
              '''https://en.wikipedia.org/wiki/BLEU''',
              '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
          ]				,     )



 def       a__						(self				,     A				,     A				,     A=4				,     A=False )					->  Tuple:


      """simple docstring"""



      _a											=						compute_bleu(
          reference_corpus=A				,     translation_corpus=A				,     max_order=A				,     smooth=A )
      ((_a)						,					(_a)						,					(_a)						,					(_a)						,					(_a)						,					(_a))											=						score
      return {
          "bleu": bleu,
          "precisions": precisions,
          "brevity_penalty": bp,
          "length_ratio": ratio,
          "translation_length": translation_length,
          "reference_length": reference_length,
      }



