


'''simple docstring'''




import datasets

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


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

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

__snake_case    						="""
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		):





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  int:
        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 							__UpperCAmelCase      ( self       :      Optional[int]    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Union[str, Any]=4    ,      UpperCAmelCase__       :      Optional[int]=False    )				->  int:
        lowerCAmelCase     =			compute_bleu(
            reference_corpus=UpperCAmelCase__    ,      translation_corpus=UpperCAmelCase__    ,      max_order=UpperCAmelCase__    ,      smooth=UpperCAmelCase__    )
        ((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'''




import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__snake_case    						=random.Random()

if is_torch_available():
       import torch





def 	a_					( lowerCamelCase	:     Dict	, lowerCamelCase	:     Dict=1.0	, lowerCamelCase	:     List[Any]=None	, lowerCamelCase	:     Union[str, Any]=None				):
   if rng is None:
      lowerCAmelCase     =			global_rng

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

   return values

class 		UpperCAmelCase_      (  unittest.TestCase		):





     def __init__( self       :      List[Any]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      List[str]=7    ,      UpperCAmelCase__       :      int=4_0_0    ,      UpperCAmelCase__       :      int=2_0_0_0    ,      UpperCAmelCase__       :      List[str]=1    ,      UpperCAmelCase__       :      Tuple=0.0    ,      UpperCAmelCase__       :      Tuple=1_6_0_0_0    ,      UpperCAmelCase__       :      Tuple=True    ,      UpperCAmelCase__       :      Union[str, Any]=True    ,      )				->  Any:
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			min_seq_length
        lowerCAmelCase     =			max_seq_length
        lowerCAmelCase     =			(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        lowerCAmelCase     =			feature_size
        lowerCAmelCase     =			padding_value
        lowerCAmelCase     =			sampling_rate
        lowerCAmelCase     =			return_attention_mask
        lowerCAmelCase     =			do_normalize





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[str]:
        return {
            "feature_size": self.feature_size,
            "padding_value": self.padding_value,
            "sampling_rate": self.sampling_rate,
            "return_attention_mask": self.return_attention_mask,
            "do_normalize": self.do_normalize,
        }





     def 							__UpperCAmelCase      ( self       :      str    ,      UpperCAmelCase__       :      Union[str, Any]=False    ,      UpperCAmelCase__       :      Union[str, Any]=False    )				->  Optional[Any]:
        def _flatten(UpperCAmelCase__       :      int    ):
           return list(itertools.chain(*UpperCAmelCase__    )    )

        if equal_length:
           lowerCAmelCase     =			floats_list((self.batch_size, self.max_seq_length)    )
        else:
           # make sure that inputs increase in size
           lowerCAmelCase     =			[
               _flatten(floats_list((x, self.feature_size)    )    )
               for x in range(self.min_seq_length    ,      self.max_seq_length    ,      self.seq_length_diff    )
           ]

        if numpify:
           lowerCAmelCase     =			[np.asarray(UpperCAmelCase__    ) for x in speech_inputs]

        return speech_inputs




@require_torch
@require_torchaudio
class 		UpperCAmelCase_      (  __lowercase       ,	unittest.TestCase		):
     lowerCamelCase				:	Dict		=     ASTFeatureExtractor





     def 							__UpperCAmelCase      ( self       :      str    )				->  Optional[int]:
        lowerCAmelCase     =			ASTFeatureExtractionTester(self    )





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Optional[int]:
        # Tests that all call wrap to encode_plus and batch_encode_plus
        lowerCAmelCase     =			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
        # create three inputs of length 800, 1000, and 1200
        lowerCAmelCase     =			[floats_list((1, x)    )[0] for x in range(8_0_0    ,      1_4_0_0    ,      2_0_0    )]
        lowerCAmelCase     =			[np.asarray(UpperCAmelCase__    ) for speech_input in speech_inputs]

        # Test not batched input
        lowerCAmelCase     =			feat_extract(speech_inputs[0]    ,      return_tensors='np'    ).input_values
        lowerCAmelCase     =			feat_extract(np_speech_inputs[0]    ,      return_tensors='np'    ).input_values
        self.assertTrue(np.allclose(UpperCAmelCase__    ,      UpperCAmelCase__    ,      atol=1E-3    )    )

        # Test batched
        lowerCAmelCase     =			feat_extract(UpperCAmelCase__    ,      padding=UpperCAmelCase__    ,      return_tensors='np'    ).input_values
        lowerCAmelCase     =			feat_extract(UpperCAmelCase__    ,      padding=UpperCAmelCase__    ,      return_tensors='np'    ).input_values
        for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__    ,      UpperCAmelCase__    ):
           self.assertTrue(np.allclose(UpperCAmelCase__    ,      UpperCAmelCase__    ,      atol=1E-3    )    )

        # Test 2-D numpy arrays are batched.
        lowerCAmelCase     =			[floats_list((1, x)    )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
        lowerCAmelCase     =			np.asarray(UpperCAmelCase__    )
        lowerCAmelCase     =			feat_extract(UpperCAmelCase__    ,      return_tensors='np'    ).input_values
        lowerCAmelCase     =			feat_extract(UpperCAmelCase__    ,      return_tensors='np'    ).input_values
        for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__    ,      UpperCAmelCase__    ):
           self.assertTrue(np.allclose(UpperCAmelCase__    ,      UpperCAmelCase__    ,      atol=1E-3    )    )





     @require_torch
     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  Optional[int]:
        import torch

        lowerCAmelCase     =			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
        lowerCAmelCase     =			np.random.rand(1_0_0    ).astype(np.floataa    )
        lowerCAmelCase     =			np_speech_inputs.tolist()

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





     def 							__UpperCAmelCase      ( self       :      int    ,      UpperCAmelCase__       :      str    )				->  Tuple:
        from datasets import load_dataset

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

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





     @require_torch
     def 							__UpperCAmelCase      ( self       :      str    )				->  Optional[Any]:
        # fmt: off
        lowerCAmelCase     =			torch.tensor(
            [-0.9_894, -1.2_776, -0.9_066, -1.2_776, -0.9_349, -1.2_609, -1.0_386, -1.2_776,
             -1.1_561, -1.2_776, -1.2_052, -1.2_723, -1.2_190, -1.2_132, -1.2_776, -1.1_133,
             -1.1_953, -1.1_343, -1.1_584, -1.2_203, -1.1_770, -1.2_474, -1.2_381, -1.1_936,
             -0.9_270, -0.8_317, -0.8_049, -0.7_706, -0.7_565, -0.7_869]    )
        # fmt: on

        lowerCAmelCase     =			self._load_datasamples(1    )
        lowerCAmelCase     =			ASTFeatureExtractor()
        lowerCAmelCase     =			feature_extractor(UpperCAmelCase__    ,      return_tensors='pt'    ).input_values
        self.assertEquals(input_values.shape    ,      (1, 1_0_2_4, 1_2_8)    )
        self.assertTrue(torch.allclose(input_values[0, 0, :3_0]    ,      UpperCAmelCase__    ,      atol=1E-4    )    )





