





"""simple docstring"""



import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
       import torch

if is_datasets_available():
       from datasets import load_dataset

a_			=      random.Random()







def 		__lowercase					(       snake_case_  :  Dict    ,snake_case_  :  Optional[Any]=1.0    ,snake_case_  :  Any=None    ,snake_case_  :  str=None						)       ->str:



    '''simple docstring'''







    if rng is None:
        __A   :						Any									=					global_rng

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

    return values






class 		__snake_case (		unittest.TestCase					):





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase ,						__lowerCamelCase=7 ,						__lowerCamelCase=400 ,						__lowerCamelCase=2000 ,						__lowerCamelCase=2048 ,						__lowerCamelCase=128 ,						__lowerCamelCase=1 ,						__lowerCamelCase=512 ,						__lowerCamelCase=30 ,						__lowerCamelCase=4_4100 ,						):



     '''simple docstring'''




     __A   :						Union[str, Any]									=					parent
     __A   :						str									=					batch_size
     __A   :						Tuple									=					min_seq_length
     __A   :						Optional[int]									=					max_seq_length
     __A   :						Union[str, Any]									=					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __A   :						List[Any]									=					spectrogram_length
     __A   :						List[str]									=					feature_size
     __A   :						Any									=					num_audio_channels
     __A   :						Optional[int]									=					hop_length
     __A   :						str									=					chunk_length
     __A   :						int									=					sampling_rate

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     return {
         "spectrogram_length": self.spectrogram_length,
         "feature_size": self.feature_size,
         "num_audio_channels": self.num_audio_channels,
         "hop_length": self.hop_length,
         "chunk_length": self.chunk_length,
         "sampling_rate": self.sampling_rate,
     }







 def  UpperCamelCase__(   self ,						__lowerCamelCase=False ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     def _flatten(__lowerCamelCase  ):
         return list(itertools.chain(*__lowerCamelCase  )  )

     if equal_length:
         __A   :						int									=					[floats_list((self.max_seq_length, self.feature_size)  ) for _ in range(self.batch_size  )]
     else:
         # make sure that inputs increase in size
         __A   :						List[str]									=					[
             floats_list((x, self.feature_size)  )
             for x in range(self.min_seq_length ,						self.max_seq_length ,						self.seq_length_diff  )
         ]
     if numpify:
         __A   :						Union[str, Any]									=					[np.asarray(__lowerCamelCase  ) for x in speech_inputs]
     return speech_inputs






@require_torch
@require_torchaudio
class 		__snake_case (		SCREAMING_SNAKE_CASE__							,							unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					TvltFeatureExtractor

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					TvltFeatureExtractionTester(self  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					self.feature_extraction_class(**self.feat_extract_dict  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''spectrogram_length'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''feature_size'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''num_audio_channels'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''hop_length'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''chunk_length'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase ,						'''sampling_rate'''  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					self.feature_extraction_class(**self.feat_extract_dict  )

     with tempfile.TemporaryDirectory() as tmpdirname:
         __A   :						Dict									=					feat_extract_first.save_pretrained(__lowerCamelCase  )[0]
         check_json_file_has_correct_format(__lowerCamelCase  )
         __A   :						Optional[int]									=					self.feature_extraction_class.from_pretrained(__lowerCamelCase  )

     __A   :						Optional[int]									=					feat_extract_first.to_dict()
     __A   :						Optional[Any]									=					feat_extract_second.to_dict()
     __A   :						Dict									=					dict_first.pop('''mel_filters'''  )
     __A   :						List[Any]									=					dict_second.pop('''mel_filters'''  )
     self.assertTrue(np.allclose(__lowerCamelCase ,						__lowerCamelCase  )  )
     self.assertEqual(__lowerCamelCase ,						__lowerCamelCase  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					self.feature_extraction_class(**self.feat_extract_dict  )

     with tempfile.TemporaryDirectory() as tmpdirname:
         __A   :						List[str]									=					os.path.join(__lowerCamelCase ,						'''feat_extract.json'''  )
         feat_extract_first.to_json_file(__lowerCamelCase  )
         __A   :						Tuple									=					self.feature_extraction_class.from_json_file(__lowerCamelCase  )

     __A   :						int									=					feat_extract_first.to_dict()
     __A   :						Optional[int]									=					feat_extract_second.to_dict()
     __A   :						Union[str, Any]									=					dict_first.pop('''mel_filters'''  )
     __A   :						Any									=					dict_second.pop('''mel_filters'''  )
     self.assertTrue(np.allclose(__lowerCamelCase ,						__lowerCamelCase  )  )
     self.assertEqual(__lowerCamelCase ,						__lowerCamelCase  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						str									=					self.feature_extraction_class(**self.feat_extract_dict  )

     # create three inputs of length 800, 1000, and 1200
     __A   :						Optional[Any]									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]
     __A   :						str									=					[np.asarray(__lowerCamelCase  ) for speech_input in speech_inputs]

     # Test not batched input
     __A   :						Any									=					feature_extractor(np_speech_inputs[0] ,						return_tensors='''np''' ,						sampling_rate=4_4100  ).audio_values

     self.assertTrue(encoded_audios.ndim == 4  )
     self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size  )
     self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length  )
     self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels  )

     # Test batched
     __A   :						List[Any]									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np''' ,						sampling_rate=4_4100  ).audio_values

     self.assertTrue(encoded_audios.ndim == 4  )
     self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size  )
     self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length  )
     self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels  )

     # Test audio masking
     __A   :						Tuple									=					feature_extractor(
         __lowerCamelCase ,						return_tensors='''np''' ,						sampling_rate=4_4100 ,						mask_audio=__lowerCamelCase  ).audio_values

     self.assertTrue(encoded_audios.ndim == 4  )
     self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size  )
     self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length  )
     self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels  )

     # Test 2-D numpy arrays are batched.
     __A   :						int									=					[floats_list((1, x)  )[0] for x in (800, 800, 800)]
     __A   :						Optional[Any]									=					np.asarray(__lowerCamelCase  )
     __A   :						str									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np''' ,						sampling_rate=4_4100  ).audio_values
     self.assertTrue(encoded_audios.ndim == 4  )
     self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size  )
     self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length  )
     self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

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







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Any									=					self._load_datasamples(1  )
     __A   :						Dict									=					TvltFeatureExtractor()
     __A   :						Optional[Any]									=					feature_extractor(__lowerCamelCase ,						return_tensors='''pt'''  ).audio_values

     self.assertEquals(audio_values.shape ,						(1, 1, 192, 128)  )

     __A   :						List[Any]									=					torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]]  )
     self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,						__lowerCamelCase ,						atol=1e-4  )  )











"""simple docstring"""



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
a_			=      pytest.mark.integration


a_			=      {"""comet"""}
a_			=      importlib.util.find_spec("""fairseq""") is not None

a_			=      {"""code_eval"""}
a_			=      os.name == """nt"""

a_			=      {"""bertscore""", """frugalscore""", """perplexity"""}
a_			=      importlib.util.find_spec("""transformers""") is not None







def 		__lowercase					(       snake_case_  :  str						)       ->Any:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  List[Any]    ,snake_case_  :  int						):
        if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
            self.skipTest('''"test requires Fairseq"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       snake_case_  :  int						)       ->str:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  List[Any]    ,snake_case_  :  List[str]						):
        if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
            self.skipTest('''"test requires transformers"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       snake_case_  :  Union[str, Any]						)       ->Tuple:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  int    ,snake_case_  :  Dict						):
        if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
            self.skipTest('''"test not supported on Windows"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       )       ->Tuple:



    '''simple docstring'''







    __A   :						int									=					[metric_dir.split(os.sep						)[-2] for metric_dir in glob.glob('''./metrics/*/'''						)]
    return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished






@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__					)
@local
class 		__snake_case (		parameterized.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					{}
 _lowerCamelCase				=					None

 @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''  )
 @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''  )
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						int									=					'''[...]'''
     __A   :						Any									=					importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics''' ,						__lowerCamelCase  )  ).module_path  )
     __A   :						str									=					datasets.load.import_main_class(metric_module.__name__ ,						dataset=__lowerCamelCase  )
     # check parameters
     __A   :						Optional[int]									=					inspect.signature(metric._compute  ).parameters
     self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()  )  )  # no **kwargs
     # run doctest
     with self.patch_intensive_calls(__lowerCamelCase ,						metric_module.__name__  ):
         with self.use_local_metrics():
             try:
                 __A   :						Tuple									=					doctest.testmod(__lowerCamelCase ,						verbose=__lowerCamelCase ,						raise_on_error=__lowerCamelCase  )
             except doctest.UnexpectedException as e:
                 raise e.exc_info[1]  # raise the exception that doctest caught
     self.assertEqual(results.failed ,						0  )
     self.assertGreater(results.attempted ,						1  )

 @slow
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Any									=					'''[...]'''
     __A   :						Union[str, Any]									=					importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics''' ,						__lowerCamelCase  )  ).module_path  )
     # run doctest
     with self.use_local_metrics():
         __A   :						Union[str, Any]									=					doctest.testmod(__lowerCamelCase ,						verbose=__lowerCamelCase ,						raise_on_error=__lowerCamelCase  )
     self.assertEqual(results.failed ,						0  )
     self.assertGreater(results.attempted ,						1  )

 @contextmanager
 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     if metric_name in self.INTENSIVE_CALLS_PATCHER:
         with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowerCamelCase  ):
             yield
     else:
         yield

 @contextmanager
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     def load_local_metric(__lowerCamelCase ,						*__lowerCamelCase ,						**__lowerCamelCase  ):
         return load_metric(os.path.join('''metrics''' ,						__lowerCamelCase  ) ,						*__lowerCamelCase ,						**__lowerCamelCase  )

     with patch('''datasets.load_metric'''  ) as mock_load_metric:
         __A   :						List[Any]									=					load_local_metric
         yield







 @classmethod
 def  UpperCamelCase__(   cls ,						__lowerCamelCase  ):



     '''simple docstring'''




     def wrapper(__lowerCamelCase  ):
         __A   :						Any									=					contextmanager(__lowerCamelCase  )
         __A   :						Optional[Any]									=					patcher
         return patcher

     return wrapper







@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''						)
def 		__lowercase					(       snake_case_  :  Tuple						)       ->int:



    '''simple docstring'''







    import tensorflow.compat.va as tf
    from bleurt.score import Predictor

    tf.flags.DEFINE_string('''sv'''    ,''''''    ,''''''						)  # handle pytest cli flags






    class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





     """simple docstring"""


     def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



         '''simple docstring'''




         assert len(input_dict['''input_ids''']  ) == 2
         return np.array([1.0_3, 1.0_4]  )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
    with patch('''bleurt.score._create_predictor'''						) as mock_create_predictor:
        __A   :						List[str]									=					MockedPredictor()
        yield







@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''						)
def 		__lowercase					(       snake_case_  :  List[str]						)       ->Dict:



    '''simple docstring'''







    import torch

    def bert_cos_score_idf(snake_case_  :  Union[str, Any]    ,snake_case_  :  List[str]    ,*snake_case_  :  List[str]    ,**snake_case_  :  Dict						):
        return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case_						)						)

    # mock get_model which is supposed to do download a bert model
    # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
    with patch('''bert_score.scorer.get_model'''						), patch(
        '''bert_score.scorer.bert_cos_score_idf'''						) as mock_bert_cos_score_idf:
        __A   :						str									=					bert_cos_score_idf
        yield







@LocalMetricTest.register_intensive_calls_patcher('''comet'''						)
def 		__lowercase					(       snake_case_  :  Optional[int]						)       ->List[Any]:



    '''simple docstring'''







    def load_from_checkpoint(snake_case_  :  str						):






        class 		__snake_case :





         """simple docstring"""


         def  UpperCamelCase__(   self ,						__lowerCamelCase ,						*__lowerCamelCase ,						**__lowerCamelCase  ):



             '''simple docstring'''




             assert len(__lowerCamelCase  ) == 2
             __A   :						str									=					[0.1_9, 0.9_2]
             return scores, sum(__lowerCamelCase  ) / len(__lowerCamelCase  )






        return Model()

    # mock load_from_checkpoint which is supposed to do download a bert model
    # mock load_from_checkpoint which is supposed to do download a bert model
    with patch('''comet.download_model'''						) as mock_download_model:
        __A   :						int									=					None
        with patch('''comet.load_from_checkpoint'''						) as mock_load_from_checkpoint:
            __A   :						Dict									=					load_from_checkpoint
            yield







def 		__lowercase					(       )       ->str:



    '''simple docstring'''







    __A   :						Optional[Any]									=					load_metric(os.path.join('''metrics'''    ,'''seqeval'''						)						)
    __A   :						Optional[int]									=					'''ERROR'''
    __A   :						str									=					F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
    with pytest.raises(snake_case_    ,match=re.escape(snake_case_						)						):
        metric.compute(predictions=[]    ,references=[]    ,scheme=snake_case_						)




