





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
					from transformers import SpeechaTextFeatureExtractor

UpperCAmelCase_ 							=       random.Random()





def   lowerCamelCase__       (       UpperCamelCase__     :    str    ,      UpperCamelCase__     :    Optional[int]=1.0    ,      UpperCamelCase__     :    Dict=None    ,      UpperCamelCase__     :    Optional[Any]=None  )     ->	Any:



					'''simple docstring'''




					if rng is None:
										_snake_case													=			global_rng

					_snake_case													=			[]
					for batch_idx in range(shape[0]  ):
										values.append([]  )
										for _ in range(shape[1]  ):
															values[-1].append(rng.random() * scale  )

					return values
@require_torch
@require_torchaudio
class      UpperCamelCase_						(					unittest.TestCase   ):




					def __init__(						self			,  lowerCAmelCase_			,  lowerCAmelCase_=7			,  lowerCAmelCase_=400			,  lowerCAmelCase_=2000			,  lowerCAmelCase_=24			,  lowerCAmelCase_=24			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=1_6000			,  lowerCAmelCase_=True			,  lowerCAmelCase_=True			,  )						->							Optional[Any]:
										_snake_case													=			parent
										_snake_case													=			batch_size
										_snake_case													=			min_seq_length
										_snake_case													=			max_seq_length
										_snake_case													=			(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										_snake_case													=			feature_size
										_snake_case													=			num_mel_bins
										_snake_case													=			padding_value
										_snake_case													=			sampling_rate
										_snake_case													=			return_attention_mask
										_snake_case													=			do_normalize




					def 		lowerCAmelCase     (						self					)						->							Dict:
										return {
										    "feature_size": self.feature_size,
										    "num_mel_bins": self.num_mel_bins,
										    "padding_value": self.padding_value,
										    "sampling_rate": self.sampling_rate,
										    "return_attention_mask": self.return_attention_mask,
										    "do_normalize": self.do_normalize,
										}






					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_=False			,  lowerCAmelCase_=False					)						->							Optional[Any]:
										def _flatten(lowerCAmelCase_					):
															return list(itertools.chain(*lowerCAmelCase_					)					)

										if equal_length:
															_snake_case													=			[floats_list((self.max_seq_length, self.feature_size)					) for _ in range(self.batch_size					)]
										else:
															# make sure that inputs increase in size
															_snake_case													=			[
															    floats_list((x, self.feature_size)					)
															    for x in range(self.min_seq_length			,  self.max_seq_length			,  self.seq_length_diff					)
															]
										if numpify:
															_snake_case													=			[np.asarray(lowerCAmelCase_					) for x in speech_inputs]
										return speech_inputs





@require_torch
@require_torchaudio
class      UpperCamelCase_						(					_lowerCamelCase							,					unittest.TestCase   ):
					lowerCAmelCase_							=		SpeechaTextFeatureExtractor if is_speech_available() else None




					def 		lowerCAmelCase     (						self					)						->							Optional[int]:
										_snake_case													=			SpeechaTextFeatureExtractionTester(self					)




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							Union[str, Any]:
										self.assertTrue(np.all(np.mean(lowerCAmelCase_			,  axis=0					) < 1E-3					)					)
										self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_			,  axis=0					) - 1					) < 1E-3					)					)




					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										# Tests that all call wrap to encode_plus and batch_encode_plus
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										# create three inputs of length 800, 1000, and 1200
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			[np.asarray(lowerCAmelCase_					) for speech_input in speech_inputs]

										# Test feature size
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  padding=lowerCAmelCase_			,  return_tensors='np'					).input_features
										self.assertTrue(input_features.ndim == 3					)
										self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size					)

										# Test not batched input
										_snake_case													=			feature_extractor(speech_inputs[0]			,  return_tensors='np'					).input_features
										_snake_case													=			feature_extractor(np_speech_inputs[0]			,  return_tensors='np'					).input_features
										self.assertTrue(np.allclose(lowerCAmelCase_			,  lowerCAmelCase_			,  atol=1E-3					)					)

										# Test batched
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															self.assertTrue(np.allclose(lowerCAmelCase_			,  lowerCAmelCase_			,  atol=1E-3					)					)

										# Test 2-D numpy arrays are batched.
										_snake_case													=			[floats_list((1, x)					)[0] for x in (800, 800, 800)]
										_snake_case													=			np.asarray(lowerCAmelCase_					)
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										for enc_seq_a, enc_seq_a in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															self.assertTrue(np.allclose(lowerCAmelCase_			,  lowerCAmelCase_			,  atol=1E-3					)					)




					def 		lowerCAmelCase     (						self					)						->							Dict:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]

										_snake_case													=			['longest', 'max_length', 'do_not_pad']
										_snake_case													=			[None, 16, None]
										for max_length, padding in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															_snake_case													=			feature_extractor(
															    lowerCAmelCase_			,  padding=lowerCAmelCase_			,  max_length=lowerCAmelCase_			,  return_attention_mask=lowerCAmelCase_					)
															_snake_case													=			inputs.input_features
															_snake_case													=			inputs.attention_mask
															_snake_case													=			[np.sum(lowerCAmelCase_					) for x in attention_mask]

															self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]					)
															self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]					)
															self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]					)




					def 		lowerCAmelCase     (						self					)						->							List[Any]:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]

										_snake_case													=			['longest', 'max_length', 'do_not_pad']
										_snake_case													=			[None, 16, None]
										for max_length, padding in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															_snake_case													=			feature_extractor(
															    lowerCAmelCase_			,  max_length=lowerCAmelCase_			,  padding=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_					)
															_snake_case													=			inputs.input_features
															_snake_case													=			inputs.attention_mask
															_snake_case													=			[np.sum(lowerCAmelCase_					) for x in attention_mask]

															self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]					)
															self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6					)
															self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]					)
															self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6					)
															self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]					)




					def 		lowerCAmelCase     (						self					)						->							Optional[int]:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='max_length'			,  max_length=4			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1]					)
										self._check_zero_mean_unit_variance(input_features[2]					)




					def 		lowerCAmelCase     (						self					)						->							str:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='longest'			,  max_length=4			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]					)
										self._check_zero_mean_unit_variance(input_features[2]					)

										# make sure that if max_length < longest -> then pad to max_length
										self.assertEqual(input_features.shape			,  (3, 4, 24)					)

										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='longest'			,  max_length=16			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]					)
										self._check_zero_mean_unit_variance(input_features[2]					)

										# make sure that if max_length < longest -> then pad to max_length
										self.assertEqual(input_features.shape			,  (3, 6, 24)					)




					def 		lowerCAmelCase     (						self					)						->							Any:
										import torch

										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			np.random.rand(100			,  32					).astype(np.floataa					)
										_snake_case													=			np_speech_inputs.tolist()

										for inputs in [py_speech_inputs, np_speech_inputs]:
															_snake_case													=			feature_extractor.pad([{'input_features': inputs}]			,  return_tensors='np'					)
															self.assertTrue(np_processed.input_features.dtype == np.floataa					)
															_snake_case													=			feature_extractor.pad([{'input_features': inputs}]			,  return_tensors='pt'					)
															self.assertTrue(pt_processed.input_features.dtype == torch.floataa					)




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							str:
										from datasets import load_dataset

										_snake_case													=			load_dataset('hf-internal-testing/librispeech_asr_dummy'			,  'clean'			,  split='validation'					)
										# automatic decoding with librispeech
										_snake_case													=			ds.sort('id'					).select(range(lowerCAmelCase_					)					)[:num_samples]['audio']

										return [x["array"] for x in speech_samples]






					def 		lowerCAmelCase     (						self					)						->							Any:
										# fmt: off
										_snake_case													=			np.array([
										    -1.57_45, -1.77_13, -1.70_20, -1.60_69, -1.22_50, -1.11_05, -0.90_72, -0.82_41,
										    -1.23_10, -0.80_98, -0.33_20, -0.41_01, -0.79_85, -0.49_96, -0.82_13, -0.91_28,
										    -1.04_20, -1.12_86, -1.04_40, -0.79_99, -0.84_05, -1.22_75, -1.54_43, -1.46_25,
										]					)
										# fmt: on

										_snake_case													=			self._load_datasamples(1					)
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='pt'					).input_features
										self.assertEquals(input_features.shape			,  (1, 584, 24)					)
										self.assertTrue(np.allclose(input_features[0, 0, :30]			,  lowerCAmelCase_			,  atol=1E-4					)					)










from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


UpperCAmelCase_ 							=       """\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

UpperCAmelCase_ 							=       """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

UpperCAmelCase_ 							=       """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,					_KWARGS_DESCRIPTION   )
class      UpperCamelCase_						(					datasets.Metric   ):




					def 		lowerCAmelCase     (						self					)						->							MetricInfo:
										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'					),
										        }					)			,  )






					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_ = 1			,  lowerCAmelCase_ = 4			,  )						->							Dict[str, float]:
										return {
										    "google_bleu": gleu_score.corpus_gleu(
										        list_of_references=lowerCAmelCase_			,  hypotheses=lowerCAmelCase_			,  min_len=lowerCAmelCase_			,  max_len=lowerCAmelCase_					)
										}



