


import datasets

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


__lowerCAmelCase			=							'''\
@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			=							'''\
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			=							'''
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   __a      (   datasets.Metric				):
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    str:




        '''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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__=4    ,			lowerCAmelCase__=False			) ->    Dict:




        '''simple docstring'''
        lowercase__:       int        =       compute_bleu(
            reference_corpus=lowerCAmelCase__    ,			translation_corpus=lowerCAmelCase__    ,			max_order=lowerCAmelCase__    ,			smooth=lowerCAmelCase__			)
        ((lowercase__)      ,						(lowercase__)      ,						(lowercase__)      ,						(lowercase__)      ,						(lowercase__)      ,						(lowercase__)):       Any        =       score
        return {
            "bleu": bleu,
            "precisions": precisions,
            "brevity_penalty": bp,
            "length_ratio": ratio,
            "translation_length": translation_length,
            "reference_length": reference_length,
        }






import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


__lowerCAmelCase			=							logging.get_logger(__name__)





class   __a      (   __UpperCamelCase				):
 __lowercase			:							Tuple       					=			['input_values', 'attention_mask']
 def __init__(       self    ,			lowerCAmelCase__ = 1    ,			lowerCAmelCase__ = 16_000    ,			lowerCAmelCase__ = 0.0    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = 80    ,			lowerCAmelCase__ = 16    ,			lowerCAmelCase__ = 64    ,			lowerCAmelCase__ = "hann_window"    ,			lowerCAmelCase__ = 1.0    ,			lowerCAmelCase__ = 80    ,			lowerCAmelCase__ = 7_600    ,			lowerCAmelCase__ = 1E-10    ,			lowerCAmelCase__ = 2    ,			lowerCAmelCase__ = True    ,			**lowerCAmelCase__    ,			) ->    List[Any]:




        '''simple docstring'''
        super().__init__(feature_size=lowerCAmelCase__    ,			sampling_rate=lowerCAmelCase__    ,			padding_value=lowerCAmelCase__    ,			**lowerCAmelCase__			)
        lowercase__:       Dict        =       do_normalize
        lowercase__:       Optional[Any]        =       return_attention_mask

        lowercase__:       str        =       num_mel_bins
        lowercase__:       Dict        =       hop_length
        lowercase__:       Dict        =       win_length
        lowercase__:       Optional[int]        =       win_function
        lowercase__:       Any        =       frame_signal_scale
        lowercase__:       Tuple        =       fmin
        lowercase__:       Tuple        =       fmax
        lowercase__:       Dict        =       mel_floor
        lowercase__:       int        =       reduction_factor

        lowercase__:       List[Any]        =       win_length * sampling_rate // 1_000
        lowercase__:       Optional[Any]        =       hop_length * sampling_rate // 1_000
        lowercase__:       Optional[int]        =       optimal_fft_length(self.sample_size			)
        lowercase__:       Optional[Any]        =       (self.n_fft // 2) + 1

        lowercase__:       str        =       window_function(window_length=self.sample_size    ,			name=self.win_function    ,			periodic=lowerCAmelCase__			)

        lowercase__:       Optional[Any]        =       mel_filter_bank(
            num_frequency_bins=self.n_freqs    ,			num_mel_filters=self.num_mel_bins    ,			min_frequency=self.fmin    ,			max_frequency=self.fmax    ,			sampling_rate=self.sampling_rate    ,			norm='slaney'    ,			mel_scale='slaney'    ,			)

        if frame_signal_scale != 1.0:
               warnings.warn(
                   'The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers'    ,			lowerCAmelCase__    ,			)
        if reduction_factor != 2.0:
               warnings.warn(
                   'The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers'    ,			lowerCAmelCase__    ,			)
 @staticmethod
 # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
 def 		SCREAMING_SNAKE_CASE__       (       lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__ = 0.0			) ->    List[np.ndarray]:




        '''simple docstring'''
        if attention_mask is not None:
               lowercase__:       List[str]        =       np.array(lowerCAmelCase__    ,			np.intaa			)
               lowercase__:       Tuple        =       []

               for vector, length in zip(lowerCAmelCase__    ,			attention_mask.sum(-1			)			):
                      lowercase__:       int        =       (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7			)
                      if length < normed_slice.shape[0]:
                             lowercase__:       Tuple        =       padding_value

                      normed_input_values.append(lowerCAmelCase__			)
        else:
               lowercase__:       Union[str, Any]        =       [(x - x.mean()) / np.sqrt(x.var() + 1E-7			) for x in input_values]

        return normed_input_values
 def 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			) ->    np.ndarray:




        '''simple docstring'''
        lowercase__:       List[str]        =       spectrogram(
            lowerCAmelCase__    ,			window=self.window    ,			frame_length=self.sample_size    ,			hop_length=self.sample_stride    ,			fft_length=self.n_fft    ,			mel_filters=self.mel_filters    ,			mel_floor=self.mel_floor    ,			log_mel='log10'    ,			)
        return log_mel_spec.T
 def __call__(       self    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			**lowerCAmelCase__    ,			) ->    BatchFeature:




        '''simple docstring'''
        if audio is None and audio_target is None:
               raise ValueError('You must provide either `audio` or `audio_target` values.'			)

        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 audio is not None:
               lowercase__:       Dict        =       self._process_audio(
                   lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			**lowerCAmelCase__    ,			)
        else:
               lowercase__:       str        =       None

        if audio_target is not None:
               lowercase__:       List[str]        =       self._process_audio(
                   lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			**lowerCAmelCase__    ,			)

               if inputs is None:
                      return inputs_target
               else:
                      lowercase__:       int        =       inputs_target['input_values']
                      lowercase__:       List[str]        =       inputs_target.get('attention_mask'			)
                      if decoder_attention_mask is not None:
                             lowercase__:       Optional[int]        =       decoder_attention_mask

        return inputs
 def 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = False    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			lowerCAmelCase__ = None    ,			**lowerCAmelCase__    ,			) ->    BatchFeature:




        '''simple docstring'''
        lowercase__:       int        =       isinstance(lowerCAmelCase__    ,			np.ndarray			) and len(speech.shape			) > 1
        if is_batched_numpy and len(speech.shape			) > 2:
               raise ValueError(F'Only mono-channel audio is supported for input to {self}'			)
        lowercase__:       Tuple        =       is_batched_numpy or (
            isinstance(lowerCAmelCase__    ,			(list, tuple)			) and (isinstance(speech[0]    ,			(np.ndarray, tuple, list)			))
        )

        if is_batched:
               lowercase__:       Dict        =       [np.asarray(lowerCAmelCase__    ,			dtype=np.floataa			) for speech in speech]
        elif not is_batched and not isinstance(lowerCAmelCase__    ,			np.ndarray			):
               lowercase__:       Optional[Any]        =       np.asarray(lowerCAmelCase__    ,			dtype=np.floataa			)
        elif isinstance(lowerCAmelCase__    ,			np.ndarray			) and speech.dtype is np.dtype(np.floataa			):
               lowercase__:       Optional[Any]        =       speech.astype(np.floataa			)

        # always return batch
        if not is_batched:
               lowercase__:       Optional[int]        =       [speech]

        # needed to make pad() work on spectrogram inputs
        lowercase__:       str        =       self.feature_size

        # convert into correct format for padding
        if is_target:
               lowercase__:       int        =       [self._extract_mel_features(lowerCAmelCase__			) for waveform in speech]
               lowercase__:       Dict        =       BatchFeature({'input_values': features}			)
               lowercase__:       Union[str, Any]        =       self.num_mel_bins
        else:
               lowercase__:       Union[str, Any]        =       BatchFeature({'input_values': speech}			)

        lowercase__:       Dict        =       self.pad(
            lowerCAmelCase__    ,			padding=lowerCAmelCase__    ,			max_length=lowerCAmelCase__    ,			truncation=lowerCAmelCase__    ,			pad_to_multiple_of=lowerCAmelCase__    ,			return_attention_mask=lowerCAmelCase__    ,			**lowerCAmelCase__    ,			)

        lowercase__:       List[str]        =       feature_size_hack

        # convert input values to correct format
        lowercase__:       Union[str, Any]        =       padded_inputs['input_values']
        if not isinstance(input_values[0]    ,			np.ndarray			):
               lowercase__:       List[Any]        =       [np.asarray(lowerCAmelCase__    ,			dtype=np.floataa			) for array in input_values]
        elif (
            not isinstance(lowerCAmelCase__    ,			np.ndarray			)
            and isinstance(input_values[0]    ,			np.ndarray			)
            and input_values[0].dtype is np.dtype(np.floataa			)
        ):
               lowercase__:       Dict        =       [array.astype(np.floataa			) for array in input_values]
        elif isinstance(lowerCAmelCase__    ,			np.ndarray			) and input_values.dtype is np.dtype(np.floataa			):
               lowercase__:       Tuple        =       input_values.astype(np.floataa			)

        # convert attention_mask to correct format
        lowercase__:       Tuple        =       padded_inputs.get('attention_mask'			)
        if attention_mask is not None:
               lowercase__:       str        =       [np.asarray(lowerCAmelCase__    ,			dtype=np.intaa			) for array in attention_mask]

        # zero-mean and unit-variance normalization
        if not is_target and self.do_normalize:
               lowercase__:       Tuple        =       (
                   attention_mask
                   if self._get_padding_strategies(lowerCAmelCase__    ,			max_length=lowerCAmelCase__			) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               lowercase__:       str        =       self.zero_mean_unit_var_norm(
                   padded_inputs['input_values']    ,			attention_mask=lowerCAmelCase__    ,			padding_value=self.padding_value			)

        if return_tensors is not None:
               lowercase__:       Union[str, Any]        =       padded_inputs.convert_to_tensors(lowerCAmelCase__			)

        return padded_inputs
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict[str, Any]:




        '''simple docstring'''
        lowercase__:       int        =       super().to_dict()

        # Don't serialize these as they are derived from the other properties.
        lowercase__:       str        =       ['window', 'mel_filters', 'sample_size', 'sample_stride', 'n_fft', 'n_freqs']
        for name in names:
               if name in output:
                      del output[name]

        return output


