


import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


SCREAMING_SNAKE_CASE						:int			=  version.parse(importlib_metadata.version('''nltk'''))
if NLTK_VERSION >= version.Version('''3.6.4'''):
   from nltk import word_tokenize


SCREAMING_SNAKE_CASE						:Any			=  '''\
@inproceedings{banarjee2005,
  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},
  author    = {Banerjee, Satanjeev  and Lavie, Alon},
  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},
  month     = jun,
  year      = {2005},
  address   = {Ann Arbor, Michigan},
  publisher = {Association for Computational Linguistics},
  url       = {https://www.aclweb.org/anthology/W05-0909},
  pages     = {65--72},
}
'''

SCREAMING_SNAKE_CASE						:str			=  '''\
METEOR, an automatic metric for machine translation evaluation
that is based on a generalized concept of unigram matching between the
machine-produced translation and human-produced reference translations.
Unigrams can be matched based on their surface forms, stemmed forms,
and meanings; furthermore, METEOR can be easily extended to include more
advanced matching strategies. Once all generalized unigram matches
between the two strings have been found, METEOR computes a score for
this matching using a combination of unigram-precision, unigram-recall, and
a measure of fragmentation that is designed to directly capture how
well-ordered the matched words in the machine translation are in relation
to the reference.

METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic
data and 0.331 on the Chinese data. This is shown to be an improvement on
using simply unigram-precision, unigram-recall and their harmonic F1
combination.
'''

SCREAMING_SNAKE_CASE						:Tuple			=  '''
Computes METEOR score of translated segments against one or more references.
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9
    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3
    gamma: Relative weight assigned to fragmentation penalty. default: 0.5
Returns:
    \'meteor\': meteor score.
Examples:

    >>> meteor = datasets.load_metric(\'meteor\')
    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]
    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]
    >>> results = meteor.compute(predictions=predictions, references=references)
    >>> print(round(results["meteor"], 4))
    0.6944
'''


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






  """simple docstring"""





  def        lowerCAmelCase__	(  self							:							int	) ->			Dict:




     """simple docstring"""
     return datasets.MetricInfo(
         description=_DESCRIPTION     ,					citation=_CITATION     ,					inputs_description=_KWARGS_DESCRIPTION     ,					features=datasets.Features(
             {
                 "predictions": datasets.Value("string"     ,					id="sequence"	),
                 "references": datasets.Value("string"     ,					id="sequence"	),
             }	)     ,					codebase_urls=["https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"]     ,					reference_urls=[
             "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score",
             "https://en.wikipedia.org/wiki/METEOR",
         ]     ,					)



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




     """simple docstring"""
     import nltk

     nltk.download("wordnet"	)
     if NLTK_VERSION >= version.Version("3.6.5"	):
        nltk.download("punkt"	)
     if NLTK_VERSION >= version.Version("3.6.6"	):
        nltk.download("omw-1.4"	)



  def        lowerCAmelCase__	(  self							:							int     ,					_lowerCAmelCase							:							Union[str, Any]     ,					_lowerCAmelCase							:							Any     ,					_lowerCAmelCase							:							Optional[int]=0.9     ,					_lowerCAmelCase							:							List[str]=3     ,					_lowerCAmelCase							:							int=0.5	) ->			Dict:




     """simple docstring"""
     if NLTK_VERSION >= version.Version("3.6.5"	):
        snake_case_            =       [
            meteor_score.single_meteor_score(
                word_tokenize(_lowerCAmelCase	)     ,					word_tokenize(_lowerCAmelCase	)     ,					alpha=_lowerCAmelCase     ,					beta=_lowerCAmelCase     ,					gamma=_lowerCAmelCase	)
            for ref, pred in zip(_lowerCAmelCase     ,					_lowerCAmelCase	)
        ]
     else:
        snake_case_            =       [
            meteor_score.single_meteor_score(_lowerCAmelCase     ,					_lowerCAmelCase     ,					alpha=_lowerCAmelCase     ,					beta=_lowerCAmelCase     ,					gamma=_lowerCAmelCase	)
            for ref, pred in zip(_lowerCAmelCase     ,					_lowerCAmelCase	)
        ]

     return {"meteor": np.mean(_lowerCAmelCase	)}








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 center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    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						:List[Any]			=  logging.get_logger(__name__)


class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		     =							['pixel_values']



  def __init__(  self							:							Optional[int]     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							PILImageResampling = PIL.Image.BICUBIC     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							Union[int, float] = 1 / 2_5_5     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					**_lowerCAmelCase							:							Optional[Any]     ,					) ->			None:




     """simple docstring"""
     super().__init__(**_lowerCAmelCase	)
     snake_case_            =       size if size is not None else {"height": 2_5_6, "width": 2_5_6}
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

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



  def        lowerCAmelCase__	(  self							:							List[str]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							PILImageResampling = PIL.Image.BICUBIC     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							int     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     if "height" not in size or "width" not in size:
        raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
     return resize(
         _lowerCAmelCase     ,					size=(size["height"], size["width"])     ,					resample=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							int     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     if "height" not in size or "width" not in size:
        raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''	)
     return center_crop(_lowerCAmelCase     ,					size=(size["height"], size["width"])     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Union[int, float]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							Union[str, Any]     ,					) ->			Optional[Any]:




     """simple docstring"""
     return rescale(_lowerCAmelCase     ,					scale=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Union[float, List[float]]     ,					_lowerCAmelCase							:							Union[float, List[float]]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							Any     ,					) ->			np.ndarray:




     """simple docstring"""
     return normalize(_lowerCAmelCase     ,					mean=_lowerCAmelCase     ,					std=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							ImageInput     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							int=None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							float = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[float, List[float]]] = None     ,					_lowerCAmelCase							:							Optional[Union[str, TensorType]] = None     ,					_lowerCAmelCase							:							ChannelDimension = ChannelDimension.FIRST     ,					**_lowerCAmelCase							:							Tuple     ,					) ->			PIL.Image.Image:




     """simple docstring"""
     snake_case_            =       do_resize if do_resize is not None else self.do_resize
     snake_case_            =       resample if resample is not None else self.resample
     snake_case_            =       do_center_crop if do_center_crop is not None else self.do_center_crop
     snake_case_            =       do_rescale if do_rescale is not None else self.do_rescale
     snake_case_            =       rescale_factor if rescale_factor is not None else self.rescale_factor
     snake_case_            =       do_normalize if do_normalize is not None else self.do_normalize
     snake_case_            =       image_mean if image_mean is not None else self.image_mean
     snake_case_            =       image_std if image_std is not None else self.image_std

     snake_case_            =       size if size is not None else self.size
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else self.crop_size
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

     snake_case_            =       make_list_of_images(_lowerCAmelCase	)

     if not valid_images(_lowerCAmelCase	):
        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_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."	)

     # All transformations expect numpy arrays.
     snake_case_            =       [to_numpy_array(_lowerCAmelCase	) for image in images]

     if do_resize:
        snake_case_            =       [self.resize(image=_lowerCAmelCase     ,					size=_lowerCAmelCase     ,					resample=_lowerCAmelCase	) for image in images]

     if do_center_crop:
        snake_case_            =       [self.center_crop(image=_lowerCAmelCase     ,					size=_lowerCAmelCase	) for image in images]

     if do_rescale:
        snake_case_            =       [self.rescale(image=_lowerCAmelCase     ,					scale=_lowerCAmelCase	) for image in images]

     if do_normalize:
        snake_case_            =       [self.normalize(image=_lowerCAmelCase     ,					mean=_lowerCAmelCase     ,					std=_lowerCAmelCase	) for image in images]

     snake_case_            =       [to_channel_dimension_format(_lowerCAmelCase     ,					_lowerCAmelCase	) for image in images]

     snake_case_            =       {"pixel_values": images}
     return BatchFeature(data=_lowerCAmelCase     ,					tensor_type=_lowerCAmelCase	)




