



'''simple docstring'''





import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_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_speech_available():
 from transformers import WhisperFeatureExtractor

if is_torch_available():
 import torch

SCREAMING_SNAKE_CASE__      					=     random.Random()




def        lowerCamelCase  (				_snake_case  :						List[Any]     ,_snake_case  :						int=1.0     ,_snake_case  :						Dict=None     ,_snake_case  :						Any=None       ):





    '''simple docstring'''


    if rng is None:
        lowercase__		       =						global_rng

    lowercase__		       =						[]
    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 				snake_case (unittest.TestCase   ):



       def __init__(				self     ,UpperCAmelCase_     ,UpperCAmelCase_=7     ,UpperCAmelCase_=400     ,UpperCAmelCase_=2_000     ,UpperCAmelCase_=10     ,UpperCAmelCase_=160     ,UpperCAmelCase_=8     ,UpperCAmelCase_=0.0     ,UpperCAmelCase_=4_000     ,UpperCAmelCase_=False     ,UpperCAmelCase_=True     ,)  ->							str:
           lowercase__		       =						parent
           lowercase__		       =						batch_size
           lowercase__		       =						min_seq_length
           lowercase__		       =						max_seq_length
           lowercase__		       =						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
           lowercase__		       =						padding_value
           lowercase__		       =						sampling_rate
           lowercase__		       =						return_attention_mask
           lowercase__		       =						do_normalize
           lowercase__		       =						feature_size
           lowercase__		       =						chunk_length
           lowercase__		       =						hop_length



       def 							_a      (				self      )  ->							Union[str, Any]:
           return {
               "feature_size": self.feature_size,
               "hop_length": self.hop_length,
               "chunk_length": self.chunk_length,
               "padding_value": self.padding_value,
               "sampling_rate": self.sampling_rate,
               "return_attention_mask": self.return_attention_mask,
               "do_normalize": self.do_normalize,
           }







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

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





@require_torch
@require_torchaudio
class 				snake_case (UpperCamelCase		,      unittest.TestCase   ):
       lowerCAmelCase__  :Tuple						   =					WhisperFeatureExtractor if is_speech_available() else None



       def 							_a      (				self      )  ->							int:
           lowercase__		       =						WhisperFeatureExtractionTester(self      )



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						self.feature_extraction_class(**self.feat_extract_dict      )

           with tempfile.TemporaryDirectory() as tmpdirname:
               lowercase__		       =						feat_extract_first.save_pretrained(UpperCAmelCase_      )[0]
               check_json_file_has_correct_format(UpperCAmelCase_      )
               lowercase__		       =						self.feature_extraction_class.from_pretrained(UpperCAmelCase_      )

           lowercase__		       =						feat_extract_first.to_dict()
           lowercase__		       =						feat_extract_second.to_dict()
           lowercase__		       =						feat_extract_first.mel_filters
           lowercase__		       =						feat_extract_second.mel_filters
           self.assertTrue(np.allclose(UpperCAmelCase_     ,UpperCAmelCase_      )      )
           self.assertEqual(UpperCAmelCase_     ,UpperCAmelCase_      )



       def 							_a      (				self      )  ->							List[Any]:
           lowercase__		       =						self.feature_extraction_class(**self.feat_extract_dict      )

           with tempfile.TemporaryDirectory() as tmpdirname:
               lowercase__		       =						os.path.join(UpperCAmelCase_     ,"feat_extract.json"      )
               feat_extract_first.to_json_file(UpperCAmelCase_      )
               lowercase__		       =						self.feature_extraction_class.from_json_file(UpperCAmelCase_      )

           lowercase__		       =						feat_extract_first.to_dict()
           lowercase__		       =						feat_extract_second.to_dict()
           lowercase__		       =						feat_extract_first.mel_filters
           lowercase__		       =						feat_extract_second.mel_filters
           self.assertTrue(np.allclose(UpperCAmelCase_     ,UpperCAmelCase_      )      )
           self.assertEqual(UpperCAmelCase_     ,UpperCAmelCase_      )



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

           # Test feature size
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,padding="max_length"     ,return_tensors="np"      ).input_features
           self.assertTrue(input_features.ndim == 3      )
           self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames      )
           self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size      )

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

           # Test batched
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           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.
           lowercase__		       =						[floats_list((1, x)      )[0] for x in (800, 800, 800)]
           lowercase__		       =						np.asarray(UpperCAmelCase_      )
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           for enc_seq_a, enc_seq_a in zip(UpperCAmelCase_     ,UpperCAmelCase_      ):
               self.assertTrue(np.allclose(UpperCAmelCase_     ,UpperCAmelCase_     ,atol=1E-3      )      )

           # Test truncation required
           lowercase__		       =						[floats_list((1, x)      )[0] for x in range(200     ,(feature_extractor.n_samples + 500)     ,200      )]
           lowercase__		       =						[np.asarray(UpperCAmelCase_      ) for speech_input in speech_inputs]

           lowercase__		       =						[x[: feature_extractor.n_samples] for x in speech_inputs]
           lowercase__		       =						[np.asarray(UpperCAmelCase_      ) for speech_input in speech_inputs_truncated]

           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="np"      ).input_features
           for enc_seq_a, enc_seq_a in zip(UpperCAmelCase_     ,UpperCAmelCase_      ):
               self.assertTrue(np.allclose(UpperCAmelCase_     ,UpperCAmelCase_     ,atol=1E-3      )      )



       def 							_a      (				self      )  ->							Union[str, Any]:
           import torch

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

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



       def 							_a      (				self     ,UpperCAmelCase_      )  ->							List[Any]:
           lowercase__		       =						load_dataset("hf-internal-testing/librispeech_asr_dummy"     ,"clean"     ,split="validation"      )
           # automatic decoding with librispeech
           lowercase__		       =						ds.sort("id"      ).select(range(UpperCAmelCase_      )      )[:num_samples]["audio"]

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



       def 							_a      (				self      )  ->							Union[str, Any]:
           # fmt: off
           lowercase__		       =						torch.tensor(
               [
                   0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51,
                   0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78,
                   0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54,
                   -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54
               ]      )
           # fmt: on

           lowercase__		       =						self._load_datasamples(1      )
           lowercase__		       =						WhisperFeatureExtractor()
           lowercase__		       =						feature_extractor(UpperCAmelCase_     ,return_tensors="pt"      ).input_features
           self.assertEqual(input_features.shape     ,(1, 80, 3_000)      )
           self.assertTrue(torch.allclose(input_features[0, 0, :30]     ,UpperCAmelCase_     ,atol=1E-4      )      )







       def 							_a      (				self      )  ->							int:
           lowercase__		       =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
           lowercase__		       =						self._load_datasamples(1      )[0]
           lowercase__		       =						((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
           lowercase__		       =						feat_extract.zero_mean_unit_var_norm([audio]     ,attention_mask=UpperCAmelCase_      )[0]

           self.assertTrue(np.all(np.mean(UpperCAmelCase_      ) < 1E-3      )      )
           self.assertTrue(np.all(np.abs(np.var(UpperCAmelCase_      ) - 1      ) < 1E-3      )      )









'''simple docstring'''





import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


class 				snake_case (unittest.TestCase		,      UpperCamelCase   ):



       def 							_a      (				self      )  ->							List[str]:
           lowercase__		       =						load_tool("text-classification"      )
           self.tool.setup()
           lowercase__		       =						load_tool("text-classification"     ,remote=UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Any:
           lowercase__		       =						self.tool("That's quite cool"     ,["positive", "negative"]      )
           self.assertEqual(UpperCAmelCase_     ,"positive"      )



       def 							_a      (				self      )  ->							Optional[int]:
           lowercase__		       =						self.remote_tool("That's quite cool"     ,["positive", "negative"]      )
           self.assertEqual(UpperCAmelCase_     ,"positive"      )



       def 							_a      (				self      )  ->							List[Any]:
           lowercase__		       =						self.tool(text="That's quite cool"     ,labels=["positive", "negative"]      )
           self.assertEqual(UpperCAmelCase_     ,"positive"      )







       def 							_a      (				self      )  ->							List[Any]:
           lowercase__		       =						self.remote_tool(text="That's quite cool"     ,labels=["positive", "negative"]      )
           self.assertEqual(UpperCAmelCase_     ,"positive"      )




