
'''simple docstring'''



import datasets

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


_lowercase          =						"""\
@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\",
}
"""

_lowercase          =						"""\
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.
"""

_lowercase          =						"""
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     UpperCAmelCase_	(						datasets.Metric					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""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    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase=4       ,  _lowercase=False ):

												"""simple docstring"""



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


'''simple docstring'''



from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_lowercase          =						logging.get_logger(__name__)




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[str]										=  ['''input_values''', '''padding_mask''']




						def __init__(   self       ,  _lowercase = 1       ,  _lowercase = 24_000       ,  _lowercase = 0.0       ,  _lowercase = None       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



												super().__init__(feature_size=_lowercase       ,  sampling_rate=_lowercase       ,  padding_value=_lowercase       ,  **_lowercase )
												_lowerCAmelCase    		=					chunk_length_s
												_lowerCAmelCase    		=					overlap




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None:
																		return None
												else:
																		return int(self.chunk_length_s * self.sampling_rate )




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None or self.overlap is None:
																		return None
												else:
																		return max(1       ,  int((1.0 - self.overlap) * self.chunk_length ) )




						def __call__(   self       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  ):

												"""simple docstring"""



												if sampling_rate is not None:
																		if sampling_rate != self.sampling_rate:
																								raise ValueError(
																								    F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
																								    F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'
																								    F' {self.sampling_rate} and not {sampling_rate}.' )
												else:
																		logger.warning(
																		    """It is strongly recommended to pass the `sampling_rate` argument to this function. """
																		    """Failing to do so can result in silent errors that might be hard to debug.""" )

												if padding and truncation:
																		raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" )
												elif padding is None:
																		# by default let's pad the inputs
																		_lowerCAmelCase    		=					True

												_lowerCAmelCase    		=					bool(
												    isinstance(_lowercase       ,  (list, tuple) ) and (isinstance(raw_audio[0]       ,  (np.ndarray, tuple, list) )) )

												if is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase       ,  dtype=np.floataa ).T for audio in raw_audio]
												elif not is_batched and not isinstance(_lowercase       ,  np.ndarray ):
																		_lowerCAmelCase    		=					np.asarray(_lowercase       ,  dtype=np.floataa )
												elif isinstance(_lowercase       ,  np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ):
																		_lowerCAmelCase    		=					raw_audio.astype(np.floataa )

												# always return batch
												if not is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase ).T]

												# verify inputs are valid
												for idx, example in enumerate(_lowercase ):
																		if example.ndim > 2:
																								raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' )
																		if self.feature_size == 1 and example.ndim != 1:
																								raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' )
																		if self.feature_size == 2 and example.shape[-1] != 2:
																								raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' )

												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					BatchFeature({"""input_values""": raw_audio} )
												if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
																		if truncation:
																								_lowerCAmelCase    		=					min(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.floor(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																		elif padding:
																								_lowerCAmelCase    		=					max(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.ceil(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																								_lowerCAmelCase    		=					"""max_length"""
																		else:
																								_lowerCAmelCase    		=					input_values

        # normal padding on batch
												if padded_inputs is None:
																		_lowerCAmelCase    		=					self.pad(
																		    _lowercase       ,  max_length=_lowercase       ,  truncation=_lowercase       ,  padding=_lowercase       ,  return_attention_mask=_lowercase       ,  )
																		if padding:
																								_lowerCAmelCase    		=					padded_inputs.pop("""attention_mask""" )

												_lowerCAmelCase    		=					[]
												for example in padded_inputs.pop("""input_values""" ):
																		if self.feature_size == 1:
																								_lowerCAmelCase    		=					example[..., None]
																		input_values.append(example.T )

												_lowerCAmelCase    		=					input_values
												if return_tensors is not None:
																		_lowerCAmelCase    		=					padded_inputs.convert_to_tensors(_lowercase )

												return padded_inputs
