



import datasets

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


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

_lowerCamelCase    :		List[Any]		      =    """\
BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.
Quality 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,
the 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
remains one of the most popular automated and inexpensive metrics.

Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.
Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness
are not taken into account[citation needed].

BLEU'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
representing 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
reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional
reference translations will increase the BLEU score.
"""

_lowerCamelCase    :		Union[str, Any]		      =    """
Computes BLEU score of translated segments against one or more references.
Args:
    predictions: list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    max_order: Maximum n-gram order to use when computing BLEU score.
    smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
    'bleu': bleu score,
    'precisions': geometric mean of n-gram precisions,
    'brevity_penalty': brevity penalty,
    'length_ratio': ratio of lengths,
    'translation_length': translation_length,
    'reference_length': reference_length
Examples:

    >>> predictions = [
    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample
    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample
    ... ]
    >>> references = [
    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)
    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)
    ... ]
    >>> bleu = datasets.load_metric(\"bleu\")
    >>> results = bleu.compute(predictions=predictions, references=references)
    >>> print(results[\"bleu\"])
    1.0
"""


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,    _KWARGS_DESCRIPTION)
class 						lowercase    (							datasets.Metric):
						'''simple docstring'''


						def       lowerCamelCase_				(  self    :				List[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       lowerCamelCase_				(  self    :				Tuple       ,	snake_case    :				str       ,	snake_case    :				str       ,	snake_case    :				Dict=4       ,	snake_case    :				Optional[int]=False	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Any						=				compute_bleu(
											    reference_corpus=snake_case       ,	translation_corpus=snake_case       ,	max_order=snake_case       ,	smooth=snake_case	)
											((SCREAMING_SNAKE_CASE)					,  (SCREAMING_SNAKE_CASE)					,  (SCREAMING_SNAKE_CASE)					,  (SCREAMING_SNAKE_CASE)					,  (SCREAMING_SNAKE_CASE)					,  (SCREAMING_SNAKE_CASE))							:     Union[str, Any]						=				score
											return {
											    "bleu": bleu,
											    "precisions": precisions,
											    "brevity_penalty": bp,
											    "length_ratio": ratio,
											    "translation_length": translation_length,
											    "reference_length": reference_length,
											}




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,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase    :		List[str]		      =    logging.get_logger(__name__)


class 						lowercase    (							SCREAMING_SNAKE_CASE_):
						'''simple docstring'''


						UpperCAmelCase			:		List[str]		=		['pixel_values']







						def __init__(  self    :				List[Any]       ,	snake_case    :				bool = True       ,	snake_case    :				Optional[Dict[str, int]] = None       ,	snake_case    :				PILImageResampling = PILImageResampling.BICUBIC       ,	snake_case    :				bool = True       ,	snake_case    :				bool = True       ,	snake_case    :				Union[int, float] = 1 / 255       ,	snake_case    :				Dict[str, int] = None       ,	snake_case    :				bool = True       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	**snake_case    :				Optional[int]       ,	):



											'''simple docstring'''


											super().__init__(**snake_case	)
											SCREAMING_SNAKE_CASE							:     List[str]						=				size if size is not None else {'height': 224, 'width': 224}
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				get_size_dict(snake_case	)
											SCREAMING_SNAKE_CASE							:     Any						=				crop_size if crop_size is not None else {'height': 224, 'width': 224}
											SCREAMING_SNAKE_CASE							:     int						=				get_size_dict(snake_case       ,	default_to_square=snake_case       ,	param_name='crop_size'	)

											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				do_resize
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				do_rescale
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				do_normalize
											SCREAMING_SNAKE_CASE							:     Dict						=				do_center_crop
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				crop_size
											SCREAMING_SNAKE_CASE							:     str						=				size
											SCREAMING_SNAKE_CASE							:     List[str]						=				resample
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				rescale_factor
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				image_std if image_std is not None else IMAGENET_DEFAULT_STD







						def       lowerCamelCase_				(  self    :				int       ,	snake_case    :				np.ndarray       ,	snake_case    :				Dict[str, int]       ,	snake_case    :				PILImageResampling = PILImageResampling.BILINEAR       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				Any       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[Any]						=				get_size_dict(snake_case	)

											if "shortest_edge" in size:
																SCREAMING_SNAKE_CASE							:     Tuple						=				get_resize_output_image_size(snake_case       ,	size=size['shortest_edge']       ,	default_to_square=snake_case	)
																# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
											elif "height" in size and "width" in size:
																SCREAMING_SNAKE_CASE							:     int						=				(size['height'], size['width'])
											else:
																raise ValueError(f'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'''	)
											return resize(snake_case       ,	size=snake_case       ,	resample=snake_case       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				List[str]       ,	snake_case    :				np.ndarray       ,	snake_case    :				Dict[str, int]       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				int       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				get_size_dict(snake_case	)
											if "height" not in size or "width" not in size:
																raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''	)
											return center_crop(snake_case       ,	size=(size['height'], size['width'])       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				Any       ,	snake_case    :				np.ndarray       ,	snake_case    :				float       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				Dict	):



											'''simple docstring'''


											return rescale(snake_case       ,	scale=snake_case       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				np.ndarray       ,	snake_case    :				Union[float, List[float]]       ,	snake_case    :				Union[float, List[float]]       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				List[Any]       ,	):



											'''simple docstring'''


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







						def       lowerCamelCase_				(  self    :				str       ,	snake_case    :				ImageInput       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Dict[str, int] = None       ,	snake_case    :				PILImageResampling = None       ,	snake_case    :				bool = None       ,	snake_case    :				int = None       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Optional[float] = None       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	snake_case    :				Optional[Union[str, TensorType]] = None       ,	snake_case    :				Union[str, ChannelDimension] = ChannelDimension.FIRST       ,	**snake_case    :				Optional[Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Any						=				do_resize if do_resize is not None else self.do_resize
											SCREAMING_SNAKE_CASE							:     int						=				do_rescale if do_rescale is not None else self.do_rescale
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				do_normalize if do_normalize is not None else self.do_normalize
											SCREAMING_SNAKE_CASE							:     List[str]						=				do_center_crop if do_center_crop is not None else self.do_center_crop
											SCREAMING_SNAKE_CASE							:     List[str]						=				crop_size if crop_size is not None else self.crop_size
											SCREAMING_SNAKE_CASE							:     List[Any]						=				get_size_dict(snake_case       ,	param_name='crop_size'       ,	default_to_square=snake_case	)
											SCREAMING_SNAKE_CASE							:     Any						=				resample if resample is not None else self.resample
											SCREAMING_SNAKE_CASE							:     Any						=				rescale_factor if rescale_factor is not None else self.rescale_factor
											SCREAMING_SNAKE_CASE							:     str						=				image_mean if image_mean is not None else self.image_mean
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				image_std if image_std is not None else self.image_std

											SCREAMING_SNAKE_CASE							:     List[str]						=				size if size is not None else self.size
											SCREAMING_SNAKE_CASE							:     str						=				get_size_dict(snake_case	)

											if not is_batched(snake_case	):
																SCREAMING_SNAKE_CASE							:     str						=				[images]

											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:
																raise ValueError('Size 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.'	)

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

											if do_resize:
																SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				[self.resize(image=snake_case       ,	size=snake_case       ,	resample=snake_case	) for image in images]

											if do_center_crop:
																SCREAMING_SNAKE_CASE							:     str						=				[self.center_crop(image=snake_case       ,	size=snake_case	) for image in images]

											if do_rescale:
																SCREAMING_SNAKE_CASE							:     Tuple						=				[self.rescale(image=snake_case       ,	scale=snake_case	) for image in images]

											if do_normalize:
																SCREAMING_SNAKE_CASE							:     int						=				[self.normalize(image=snake_case       ,	mean=snake_case       ,	std=snake_case	) for image in images]

											SCREAMING_SNAKE_CASE							:     List[str]						=				[to_channel_dimension_format(snake_case       ,	snake_case	) for image in images]

											SCREAMING_SNAKE_CASE							:     Any						=				{'pixel_values': images}
											return BatchFeature(data=snake_case       ,	tensor_type=snake_case	)