





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

_lowerCamelCase 					=      random.Random()






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				int       , UpperCamelCase__:				Union[str, Any]=1.0       , UpperCamelCase__:				str=None       , UpperCamelCase__:				int=None     ):
		if rng is None:
				SCREAMING_SNAKE_CASE__								=   global_rng

		SCREAMING_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     :Optional[Any]				,					__A     :str				,					__A     :int=7				,					__A     :Optional[Any]=400				,					__A     :Tuple=2000				,					__A     :Any=24				,					__A     :Optional[Any]=24				,					__A     :List[str]=0.0				,					__A     :Optional[int]=1_6000				,					__A     :Dict=True				,					__A     :List[Any]=True				,					) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   parent
									SCREAMING_SNAKE_CASE__								=   batch_size
									SCREAMING_SNAKE_CASE__								=   min_seq_length
									SCREAMING_SNAKE_CASE__								=   max_seq_length
									SCREAMING_SNAKE_CASE__								=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									SCREAMING_SNAKE_CASE__								=   feature_size
									SCREAMING_SNAKE_CASE__								=   num_mel_bins
									SCREAMING_SNAKE_CASE__								=   padding_value
									SCREAMING_SNAKE_CASE__								=   sampling_rate
									SCREAMING_SNAKE_CASE__								=   return_attention_mask
									SCREAMING_SNAKE_CASE__								=   do_normalize


							def   _snake_case	(				self     :Tuple		) -> Optional[int]:



									"""simple docstring"""



									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   _snake_case	(				self     :List[str]				,					__A     :str=False				,					__A     :Any=False		) -> Any:



									"""simple docstring"""



									def _flatten(__A     :Tuple		):
											return list(itertools.chain(*__A		)		)

									if equal_length:
											SCREAMING_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
											SCREAMING_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:
											SCREAMING_SNAKE_CASE__								=   [np.asarray(__A		) for x in speech_inputs]
									return speech_inputs




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


							def   _snake_case	(				self     :Tuple		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   SpeechaTextFeatureExtractionTester(self		)


							def   _snake_case	(				self     :Dict				,					__A     :Union[str, Any]		) -> Union[str, Any]:



									"""simple docstring"""



									self.assertTrue(np.all(np.mean(__A				,					axis=0		) < 1E-3		)		)
									self.assertTrue(np.all(np.abs(np.var(__A				,					axis=0		) - 1		) < 1E-3		)		)


							def   _snake_case	(				self     :Optional[Any]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
									# create three inputs of length 800, 1000, and 1200
									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]
									SCREAMING_SNAKE_CASE__								=   [np.asarray(__A		) for speech_input in speech_inputs]

									# Test feature size
									SCREAMING_SNAKE_CASE__								=   feature_extractor(__A				,					padding=__A				,					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
									SCREAMING_SNAKE_CASE__								=   feature_extractor(speech_inputs[0]				,					return_tensors="""np"""		).input_features
									SCREAMING_SNAKE_CASE__								=   feature_extractor(np_speech_inputs[0]				,					return_tensors="""np"""		).input_features
									self.assertTrue(np.allclose(__A				,					__A				,					atol=1E-3		)		)

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

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


							def   _snake_case	(				self     :Dict		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]

									SCREAMING_SNAKE_CASE__								=   ["""longest""", """max_length""", """do_not_pad"""]
									SCREAMING_SNAKE_CASE__								=   [None, 16, None]
									for max_length, padding in zip(__A				,					__A		):
											SCREAMING_SNAKE_CASE__								=   feature_extractor(
											    __A				,					padding=__A				,					max_length=__A				,					return_attention_mask=__A		)
											SCREAMING_SNAKE_CASE__								=   inputs.input_features
											SCREAMING_SNAKE_CASE__								=   inputs.attention_mask
											SCREAMING_SNAKE_CASE__								=   [np.sum(__A		) 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   _snake_case	(				self     :Tuple		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]

									SCREAMING_SNAKE_CASE__								=   ["""longest""", """max_length""", """do_not_pad"""]
									SCREAMING_SNAKE_CASE__								=   [None, 16, None]
									for max_length, padding in zip(__A				,					__A		):
											SCREAMING_SNAKE_CASE__								=   feature_extractor(
											    __A				,					max_length=__A				,					padding=__A				,					return_tensors="""np"""				,					return_attention_mask=__A		)
											SCREAMING_SNAKE_CASE__								=   inputs.input_features
											SCREAMING_SNAKE_CASE__								=   inputs.attention_mask
											SCREAMING_SNAKE_CASE__								=   [np.sum(__A		) 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   _snake_case	(				self     :Union[str, Any]		) -> Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]
									SCREAMING_SNAKE_CASE__								=   feature_extractor(
									    __A				,					padding="""max_length"""				,					max_length=4				,					truncation=__A				,					return_tensors="""np"""				,					return_attention_mask=__A				,					)
									SCREAMING_SNAKE_CASE__								=   inputs.input_features
									SCREAMING_SNAKE_CASE__								=   inputs.attention_mask
									SCREAMING_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   _snake_case	(				self     :Optional[Any]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]
									SCREAMING_SNAKE_CASE__								=   feature_extractor(
									    __A				,					padding="""longest"""				,					max_length=4				,					truncation=__A				,					return_tensors="""np"""				,					return_attention_mask=__A				,					)
									SCREAMING_SNAKE_CASE__								=   inputs.input_features
									SCREAMING_SNAKE_CASE__								=   inputs.attention_mask
									SCREAMING_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)		)

									SCREAMING_SNAKE_CASE__								=   [floats_list((1, x)		)[0] for x in range(800				,					1400				,					200		)]
									SCREAMING_SNAKE_CASE__								=   feature_extractor(
									    __A				,					padding="""longest"""				,					max_length=16				,					truncation=__A				,					return_tensors="""np"""				,					return_attention_mask=__A				,					)
									SCREAMING_SNAKE_CASE__								=   inputs.input_features
									SCREAMING_SNAKE_CASE__								=   inputs.attention_mask
									SCREAMING_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   _snake_case	(				self     :Any		) -> Union[str, Any]:



									"""simple docstring"""



									import torch

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

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


							def   _snake_case	(				self     :Union[str, Any]				,					__A     :Union[str, Any]		) -> Tuple:



									"""simple docstring"""



									from datasets import load_dataset

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

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


							def   _snake_case	(				self     :Dict		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   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

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

"""simple docstring"""




import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


A__ :       int				= threading.Lock()
A__ :       Optional[logging.Handler]				= None

A__ :       str				= {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

A__ :       str				= logging.WARNING

A__ :       Union[str, Any]				= True




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      List[Any]   			=  os.getenv('''TRANSFORMERS_VERBOSITY'''			,					_UpperCamelCase    )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '''
          f'''has to be one of: { ", ".join(log_levels.keys()    ) }'''    )
  return _default_log_level




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return __name__.split('''.'''    )[0]




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return logging.getLogger(_get_library_name()    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    _lowercase:      int   			=  logging.StreamHandler()  # Set sys.stderr as stream.
    _lowercase:      Dict   			=  sys.stderr.flush

    # Apply our default configuration to the library root logger.
    _lowercase:      Dict   			=  _get_library_root_logger()
    library_root_logger.addHandler(_default_handler    )
    library_root_logger.setLevel(_get_default_logging_level()    )
    _lowercase:      Optional[Any]   			=  False




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _default_handler

  with _lock:
    if not _default_handler:
      return

    _lowercase:      Tuple   			=  _get_library_root_logger()
    library_root_logger.removeHandler(_default_handler    )
    library_root_logger.setLevel(logging.NOTSET    )
    _lowercase:      Dict   			=  None




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return log_levels




def 			_lowerCAmelCase		(		_UpperCamelCase = None    ):






  """simple docstring"""



  if name is None:
    _lowercase:      Tuple   			=  _get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()
  _get_library_root_logger().setLevel(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  return set_verbosity(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler    )




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(_UpperCamelCase    )




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  _lowercase:      str   			=  False




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _configure_library_root_logger()
  _lowercase:      List[str]   			=  True




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Any   			=  _get_library_root_logger().handlers

  for handler in handlers:
    _lowercase:      int   			=  logging.Formatter('''[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'''    )
    handler.setFormatter(_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      List[str]   			=  _get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(_UpperCamelCase    )




def 			_lowerCAmelCase		(		self			,					*_UpperCamelCase			,					**_UpperCamelCase    ):






  """simple docstring"""



  _lowercase:      Any   			=  os.getenv('''TRANSFORMERS_NO_ADVISORY_WARNINGS'''			,					_UpperCamelCase    )
  if no_advisory_warnings:
    return
  self.warning(*_UpperCamelCase			,					**_UpperCamelCase    )


A__ :       Optional[int]				= warning_advice




@functools.lru_cache(_UpperCamelCase    )
def 			_lowerCAmelCase		(		self			,					*_UpperCamelCase			,					**_UpperCamelCase    ):






  """simple docstring"""



  self.warning(*_UpperCamelCase			,					**_UpperCamelCase    )


A__ :       List[Any]				= warning_once


class       __magic_name__							:
       def __init__(  self			,					*A_			,					**A_							)  ->						Any:  # pylint: disable=unused-argument





         """simple docstring"""




         _lowercase:      Tuple   			=  args[0] if args else None
       def __iter__(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         return iter(self._iterator							)
       def __getattr__(  self			,					A_							)  ->						List[Any]:





         """simple docstring"""




         def empty_fn(*A_			,					**A_							):  # pylint: disable=unused-argument
           return

         return empty_fn
       def __enter__(  self							)  ->						Tuple:





         """simple docstring"""




         return self



       def __exit__(  self			,					A_			,					A_			,					A_							)  ->						Optional[Any]:





         """simple docstring"""




         return


class       __magic_name__							:
       def __call__(  self			,					*A_			,					**A_							)  ->						Dict:





         """simple docstring"""




         if _tqdm_active:
           return tqdm_lib.tqdm(*A_			,					**A_							)
         else:
           return EmptyTqdm(*A_			,					**A_							)
       def 				lowercase_				(  self			,					*A_			,					**A_							)  ->						List[str]:





         """simple docstring"""




         _lowercase:      Optional[Any]   			=  None
         if _tqdm_active:
           return tqdm_lib.tqdm.set_lock(*A_			,					**A_							)



       def 				lowercase_				(  self							)  ->						Optional[Any]:





         """simple docstring"""




         if _tqdm_active:
           return tqdm_lib.tqdm.get_lock()

A__ :       str				= _tqdm_cls()




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  return bool(_tqdm_active    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  _lowercase:      str   			=  True
  hf_hub_utils.enable_progress_bars()







def 			_lowerCAmelCase		(		):






  """simple docstring"""



  global _tqdm_active
  _lowercase:      Union[str, Any]   			=  False
  hf_hub_utils.disable_progress_bars()
