





"""simple docstring"""






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

A	     =					random.Random()

def       __A (     a_  :Any				,    a_  :Dict=1.0				,    a_  :List[str]=None				,    a_  :List[str]=None)						->						Any:
				if rng is None:
								__a	:  Any         =					global_rng

				__a	:  Optional[int]         =					[]
				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 			__lowercase     (     unittest.TestCase							):







					'''simple docstring'''




					def __init__(  self		,     _UpperCAmelCase		,     _UpperCAmelCase=7		,     _UpperCAmelCase=400		,     _UpperCAmelCase=2000		,     _UpperCAmelCase=24		,     _UpperCAmelCase=24		,     _UpperCAmelCase=0.0		,     _UpperCAmelCase=16000		,     _UpperCAmelCase=True		,     _UpperCAmelCase=True		,     ):
									__a	:  List[str]         =					parent
									__a	:  int         =					batch_size
									__a	:  int         =					min_seq_length
									__a	:  Tuple         =					max_seq_length
									__a	:  List[Any]         =					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									__a	:  List[Any]         =					feature_size
									__a	:  Dict         =					num_mel_bins
									__a	:  str         =					padding_value
									__a	:  int         =					sampling_rate
									__a	:  Any         =					return_attention_mask
									__a	:  Dict         =					do_normalize







					def 	_lowerCamelCase						(  self       ):
									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		,     _UpperCAmelCase=False		,     _UpperCAmelCase=False       ):
									def _flatten(_UpperCAmelCase       ):
													return list(itertools.chain(*_UpperCAmelCase       )       )

									if equal_length:
													__a	:  Tuple         =					[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[Any]         =					[
													    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	:  Optional[int]         =					[np.asarray(_UpperCAmelCase       ) for x in speech_inputs]
									return speech_inputs






@require_torch
@require_torchaudio
class 			__lowercase     (     _UpperCamelCase				, unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase					=					SpeechaTextFeatureExtractor if is_speech_available() else None







					def 	_lowerCamelCase						(  self       ):
									__a	:  Optional[int]         =					SpeechaTextFeatureExtractionTester(self       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									self.assertTrue(np.all(np.mean(_UpperCAmelCase		,     axis=0       ) < 1e-3       )       )
									self.assertTrue(np.all(np.abs(np.var(_UpperCAmelCase		,     axis=0       ) - 1       ) < 1e-3       )       )







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

									# Test feature size
									__a	:  Optional[Any]         =					feature_extractor(_UpperCAmelCase		,     padding=_UpperCAmelCase		,     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
									__a	:  Dict         =					feature_extractor(speech_inputs[0]		,     return_tensors='''np'''       ).input_features
									__a	:  Tuple         =					feature_extractor(np_speech_inputs[0]		,     return_tensors='''np'''       ).input_features
									self.assertTrue(np.allclose(_UpperCAmelCase		,     _UpperCAmelCase		,     atol=1e-3       )       )

									# Test batched
									__a	:  Dict         =					feature_extractor(_UpperCAmelCase		,     return_tensors='''np'''       ).input_features
									__a	:  Any         =					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.
									__a	:  Optional[int]         =					[floats_list((1, x)       )[0] for x in (800, 800, 800)]
									__a	:  Union[str, Any]         =					np.asarray(_UpperCAmelCase       )
									__a	:  Any         =					feature_extractor(_UpperCAmelCase		,     return_tensors='''np'''       ).input_features
									__a	:  List[str]         =					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 	_lowerCamelCase						(  self       ):
									__a	:  int         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  Dict         =					[floats_list((1, x)       )[0] for x in range(800		,     1400		,     200       )]

									__a	:  Any         =					['''longest''', '''max_length''', '''do_not_pad''']
									__a	:  int         =					[None, 16, None]
									for max_length, padding in zip(_UpperCAmelCase		,     _UpperCAmelCase       ):
													__a	:  Dict         =					feature_extractor(
													    _UpperCAmelCase		,     padding=_UpperCAmelCase		,     max_length=_UpperCAmelCase		,     return_attention_mask=_UpperCAmelCase       )
													__a	:  Optional[int]         =					inputs.input_features
													__a	:  int         =					inputs.attention_mask
													__a	:  Dict         =					[np.sum(_UpperCAmelCase       ) 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       ):
									__a	:  List[str]         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  Tuple         =					[floats_list((1, x)       )[0] for x in range(800		,     1400		,     200       )]

									__a	:  Dict         =					['''longest''', '''max_length''', '''do_not_pad''']
									__a	:  Optional[int]         =					[None, 16, None]
									for max_length, padding in zip(_UpperCAmelCase		,     _UpperCAmelCase       ):
													__a	:  List[Any]         =					feature_extractor(
													    _UpperCAmelCase		,     max_length=_UpperCAmelCase		,     padding=_UpperCAmelCase		,     return_tensors='''np'''		,     return_attention_mask=_UpperCAmelCase       )
													__a	:  Any         =					inputs.input_features
													__a	:  Optional[Any]         =					inputs.attention_mask
													__a	:  List[Any]         =					[np.sum(_UpperCAmelCase       ) 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       ):
									__a	:  Union[str, Any]         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  int         =					[floats_list((1, x)       )[0] for x in range(800		,     1400		,     200       )]
									__a	:  str         =					feature_extractor(
									    _UpperCAmelCase		,     padding='''max_length'''		,     max_length=4		,     truncation=_UpperCAmelCase		,     return_tensors='''np'''		,     return_attention_mask=_UpperCAmelCase		,     )
									__a	:  int         =					inputs.input_features
									__a	:  Any         =					inputs.attention_mask
									__a	:  Optional[int]         =					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       ):
									__a	:  Optional[Any]         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  Optional[int]         =					[floats_list((1, x)       )[0] for x in range(800		,     1400		,     200       )]
									__a	:  Tuple         =					feature_extractor(
									    _UpperCAmelCase		,     padding='''longest'''		,     max_length=4		,     truncation=_UpperCAmelCase		,     return_tensors='''np'''		,     return_attention_mask=_UpperCAmelCase		,     )
									__a	:  Optional[int]         =					inputs.input_features
									__a	:  Optional[int]         =					inputs.attention_mask
									__a	:  Dict         =					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)       )

									__a	:  Dict         =					[floats_list((1, x)       )[0] for x in range(800		,     1400		,     200       )]
									__a	:  Tuple         =					feature_extractor(
									    _UpperCAmelCase		,     padding='''longest'''		,     max_length=16		,     truncation=_UpperCAmelCase		,     return_tensors='''np'''		,     return_attention_mask=_UpperCAmelCase		,     )
									__a	:  Optional[int]         =					inputs.input_features
									__a	:  str         =					inputs.attention_mask
									__a	:  int         =					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       ):
									import torch

									__a	:  Union[str, Any]         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  Union[str, Any]         =					np.random.rand(100		,     32       ).astype(np.floataa       )
									__a	:  List[str]         =					np_speech_inputs.tolist()

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







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									from datasets import load_dataset

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

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







					def 	_lowerCamelCase						(  self       ):
									# fmt: off
									__a	:  List[str]         =					np.array([
									    -1.5_7_4_5, -1.7_7_1_3, -1.7_0_2_0, -1.6_0_6_9, -1.2_2_5_0, -1.1_1_0_5, -0.9_0_7_2, -0.8_2_4_1,
									    -1.2_3_1_0, -0.8_0_9_8, -0.3_3_2_0, -0.4_1_0_1, -0.7_9_8_5, -0.4_9_9_6, -0.8_2_1_3, -0.9_1_2_8,
									    -1.0_4_2_0, -1.1_2_8_6, -1.0_4_4_0, -0.7_9_9_9, -0.8_4_0_5, -1.2_2_7_5, -1.5_4_4_3, -1.4_6_2_5,
									]       )
									# fmt: on

									__a	:  List[str]         =					self._load_datasamples(1       )
									__a	:  Dict         =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
									__a	:  Optional[int]         =					feature_extractor(_UpperCAmelCase		,     return_tensors='''pt'''       ).input_features
									self.assertEquals(input_features.shape		,     (1, 584, 24)       )
									self.assertTrue(np.allclose(input_features[0, 0, :30]		,     _UpperCAmelCase		,     atol=1e-4       )       )






"""simple docstring"""






def       __A (     a_  :int				,    a_  :int)						->						str:
				if a < 0 or b < 0:
								raise ValueError('''the value of both inputs must be positive''')

				__a	:  Union[str, Any]         =					str(bin(a_))[2:]  # remove the leading "0b"
				__a	:  Union[str, Any]         =					str(bin(a_))[2:]  # remove the leading "0b"

				__a	:  Optional[Any]         =					max(len(a_)				,    len(a_))

				return "0b" + "".join(
				    str(int(char_a != char_b))
				    for char_a, char_b in zip(a_binary.zfill(a_)				,    b_binary.zfill(a_)))


if __name__ == "__main__":
		import doctest

		doctest.testmod()