





'''simple docstring'''
import itertools
import random
import unittest

import numpy as np

from transformers import EncodecFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
    import torch


a__							:							Tuple			=			random.Random()
def     lowercase__       (       __lowercase						:  Optional[Any]    ,  __lowercase						:  Optional[Any]=1.0    ,  __lowercase						:  Optional[Any]=None    ,  __lowercase						:  int=None					)			->				int:



       """simple docstring"""






       if rng is None:
              __UpperCamelCase	=  global_rng

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

       return values

@require_torch
class 					snake_case					(   unittest.TestCase	):




 """simple docstring"""



 def __init__(	self	:							Any							,     __A	:							Optional[int]							,     __A	:							Union[str, Any]=7							,     __A	:							Any=4_0_0							,     __A	:							Optional[int]=2_0_0_0							,     __A	:							str=1							,     __A	:							Optional[Any]=0.0							,     __A	:							Union[str, Any]=2_4_0_0_0							,     __A	:							str=True							,     ):
        __UpperCamelCase	=  parent
        __UpperCamelCase	=  batch_size
        __UpperCamelCase	=  min_seq_length
        __UpperCamelCase	=  max_seq_length
        __UpperCamelCase	=  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        __UpperCamelCase	=  feature_size
        __UpperCamelCase	=  padding_value
        __UpperCamelCase	=  sampling_rate
        __UpperCamelCase	=  return_attention_mask






 def 	_lowerCamelCase (	self	:							int     ):
        return {
            "feature_size": self.feature_size,
            "padding_value": self.padding_value,
            "sampling_rate": self.sampling_rate,
            "return_attention_mask": self.return_attention_mask,
        }






 def 	_lowerCamelCase (	self	:							Union[str, Any]							,     __A	:							int=False							,     __A	:							List[Any]=False     ):





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

        if equal_length:
               __UpperCamelCase	=  floats_list((self.batch_size, self.max_seq_length)     )
        else:
               # make sure that inputs increase in size
               __UpperCamelCase	=  [
                   _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:
               __UpperCamelCase	=  [np.asarray(_UpperCamelCase     ) for x in audio_inputs]

        return audio_inputs






@require_torch
class 					snake_case					(   __lowerCamelCase      ,	unittest.TestCase	):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_     : Optional[Any]      		=EncodecFeatureExtractor






 def 	_lowerCamelCase (	self	:							Optional[Any]     ):
        __UpperCamelCase	=  EnCodecFeatureExtractionTester(self     )






 def 	_lowerCamelCase (	self	:							Dict     ):
        __UpperCamelCase	=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
        # create three inputs of length 800, 1000, and 1200
        __UpperCamelCase	=  [floats_list((1, x)     )[0] for x in range(8_0_0							,     1_4_0_0							,     2_0_0     )]
        __UpperCamelCase	=  [np.asarray(_UpperCamelCase     ) for audio_input in audio_inputs]

        # Test not batched input
        __UpperCamelCase	=  feat_extract(audio_inputs[0]							,     return_tensors='np'     ).input_values
        __UpperCamelCase	=  feat_extract(np_audio_inputs[0]							,     return_tensors='np'     ).input_values
        self.assertTrue(np.allclose(_UpperCamelCase							,     _UpperCamelCase							,     atol=1e-3     )     )

        # Test batched
        __UpperCamelCase	=  feat_extract(_UpperCamelCase							,     padding=_UpperCamelCase							,     return_tensors='np'     ).input_values
        __UpperCamelCase	=  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     )     )






 def 	_lowerCamelCase (	self	:							Any     ):
        __UpperCamelCase	=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
        __UpperCamelCase	=  np.random.rand(1_0_0     ).astype(np.floataa     )
        __UpperCamelCase	=  np_audio_inputs.tolist()

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






 def 	_lowerCamelCase (	self	:							Tuple							,     __A	:							int     ):
        from datasets import load_dataset

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

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






 def 	_lowerCamelCase (	self	:							List[str]     ):
        __UpperCamelCase	=  torch.tensor(
            [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
             3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
             2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
             4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
             7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
             4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03]     )
        # fmt: on
        __UpperCamelCase	=  self._load_datasamples(1     )
        __UpperCamelCase	=  EncodecFeatureExtractor()
        __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(input_values.shape							,     (1, 1, 9_3_6_8_0)     )
        self.assertTrue(torch.allclose(input_values[0, 0, :3_0]							,     _UpperCamelCase							,     atol=1e-6     )     )






 def 	_lowerCamelCase (	self	:							Optional[int]     ):
        __UpperCamelCase	=  torch.tensor(
            [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
             3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
             2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
             4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
             7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
             4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03]     )
        # fmt: on
        __UpperCamelCase	=  self._load_datasamples(1     )
        __UpperCamelCase	=  [np.tile(input_audio[0][None]							,     reps=(2, 1)     )]
        input_audio[0][1] *= 0.5
        __UpperCamelCase	=  EncodecFeatureExtractor(feature_size=2     )
        __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(input_values.shape							,     (1, 2, 9_3_6_8_0)     )
        self.assertTrue(torch.allclose(input_values[0, 0, :3_0]							,     _UpperCamelCase							,     atol=1e-6     )     )
        self.assertTrue(torch.allclose(input_values[0, 1, :3_0]							,     EXPECTED_INPUT_VALUES * 0.5							,     atol=1e-6     )     )






 def 	_lowerCamelCase (	self	:							Optional[Any]     ):
        __UpperCamelCase	=  self._load_datasamples(2     )
        # would be easier if the stride was like
        __UpperCamelCase	=  EncodecFeatureExtractor(feature_size=1							,     chunk_length_s=1							,     overlap=0.01     )

        # pad and trunc raise an error ?
        with self.assertRaisesRegex(
            _UpperCamelCase							,     '^Both padding and truncation were set. Make sure you only set one.$'							,     ):
               __UpperCamelCase	=  feature_extractor(
                   _UpperCamelCase							,     padding='max_length'							,     truncation=_UpperCamelCase							,     return_tensors='pt'     ).input_values

        # truncate to chunk
        __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     truncation=_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (2, 1, 7_1_5_2_0)     )  # 2 chunks

        # force truncate to max_length
        __UpperCamelCase	=  feature_extractor(
            _UpperCamelCase							,     truncation=_UpperCamelCase							,     max_length=4_8_0_0_0							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (2, 1, 4_8_0_0_0)     )

        # pad to chunk
        __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(padded_outputs.shape							,     (2, 1, 9_5_2_8_0)     )

        # pad to chunk
        __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (2, 1, 9_5_2_8_0)     )

        # force pad to max length
        __UpperCamelCase	=  feature_extractor(
            _UpperCamelCase							,     padding='max_length'							,     max_length=1_0_0_0_0_0							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (2, 1, 1_0_0_0_0_0)     )

        # force no pad
        with self.assertRaisesRegex(
            _UpperCamelCase							,     '^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'							,     ):
               __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values

        __UpperCamelCase	=  feature_extractor(input_audio[0]							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (1, 1, 9_3_6_8_0)     )

        # no pad if no chunk_length_s
        __UpperCamelCase	=  None
        with self.assertRaisesRegex(
            _UpperCamelCase							,     '^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'							,     ):
               __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values

        __UpperCamelCase	=  feature_extractor(input_audio[0]							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (1, 1, 9_3_6_8_0)     )

        # no pad if no overlap
        __UpperCamelCase	=  2
        __UpperCamelCase	=  None
        with self.assertRaisesRegex(
            _UpperCamelCase							,     '^Unable to create tensor, you should probably activate padding with \'padding=True\' to have batched tensors with the same length.$'							,     ):
               __UpperCamelCase	=  feature_extractor(_UpperCamelCase							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values

        __UpperCamelCase	=  feature_extractor(input_audio[0]							,     padding=_UpperCamelCase							,     return_tensors='pt'     ).input_values
        self.assertEquals(truncated_outputs.shape							,     (1, 1, 9_3_6_8_0)     )







'''simple docstring'''
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

from tqdm import auto as tqdm_lib


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

a__							:							Optional[Any]			={
    '''debug''': logging.DEBUG,
    '''info''': logging.INFO,
    '''warning''': logging.WARNING,
    '''error''': logging.ERROR,
    '''critical''': logging.CRITICAL,
}

a__							:							List[Any]			=logging.WARNING

a__							:							str			=True
def     lowercase__       (       )			->				int:



       """simple docstring"""






       __UpperCamelCase	=  os.getenv('DIFFUSERS_VERBOSITY'    ,  __lowercase					)
       if env_level_str:
              if env_level_str in log_levels:
                     return log_levels[env_level_str]
              else:
                     logging.getLogger().warning(
                         F'''Unknown option DIFFUSERS_VERBOSITY={env_level_str}, '''
                         F'''has to be one of: { ', '.join(log_levels.keys()					) }'''					)
       return _default_log_level
def     lowercase__       (       )			->				str:



       """simple docstring"""






       return __name__.split('.'					)[0]
def     lowercase__       (       )			->				logging.Logger:



       """simple docstring"""






       return logging.getLogger(_get_library_name()					)
def     lowercase__       (       )			->				None:



       """simple docstring"""






       global _default_handler

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

              # Apply our default configuration to the library root logger.
              __UpperCamelCase	=  _get_library_root_logger()
              library_root_logger.addHandler(_default_handler					)
              library_root_logger.setLevel(_get_default_logging_level()					)
              __UpperCamelCase	=  False
def     lowercase__       (       )			->				None:



       """simple docstring"""






       global _default_handler

       with _lock:
              if not _default_handler:
                     return

              __UpperCamelCase	=  _get_library_root_logger()
              library_root_logger.removeHandler(_default_handler					)
              library_root_logger.setLevel(logging.NOTSET					)
              __UpperCamelCase	=  None
def     lowercase__       (       )			->				str:



       """simple docstring"""






       return log_levels
def     lowercase__       (       __lowercase						:  Optional[str] = None					)			->				logging.Logger:



       """simple docstring"""






       if name is None:
              __UpperCamelCase	=  _get_library_name()

       _configure_library_root_logger()
       return logging.getLogger(__lowercase					)
def     lowercase__       (       )			->				int:



       """simple docstring"""






       _configure_library_root_logger()
       return _get_library_root_logger().getEffectiveLevel()
def     lowercase__       (       __lowercase						:  int					)			->				None:



       """simple docstring"""






       _configure_library_root_logger()
       _get_library_root_logger().setLevel(__lowercase					)
def     lowercase__       (       )			->				Tuple:



       """simple docstring"""






       return set_verbosity(__lowercase					)
def     lowercase__       (       )			->				Union[str, Any]:



       """simple docstring"""






       return set_verbosity(__lowercase					)
def     lowercase__       (       )			->				Any:



       """simple docstring"""






       return set_verbosity(__lowercase					)
def     lowercase__       (       )			->				int:



       """simple docstring"""






       return set_verbosity(__lowercase					)
def     lowercase__       (       )			->				None:



       """simple docstring"""






       _configure_library_root_logger()

       assert _default_handler is not None
       _get_library_root_logger().removeHandler(_default_handler					)
def     lowercase__       (       )			->				None:



       """simple docstring"""






       _configure_library_root_logger()

       assert _default_handler is not None
       _get_library_root_logger().addHandler(_default_handler					)
def     lowercase__       (       __lowercase						:  logging.Handler					)			->				None:



       """simple docstring"""






       _configure_library_root_logger()

       assert handler is not None
       _get_library_root_logger().addHandler(__lowercase					)
def     lowercase__       (       __lowercase						:  logging.Handler					)			->				None:



       """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(__lowercase					)
def     lowercase__       (       )			->				None:



       """simple docstring"""






       _configure_library_root_logger()
       __UpperCamelCase	=  False
def     lowercase__       (       )			->				None:



       """simple docstring"""






       _configure_library_root_logger()
       __UpperCamelCase	=  True
def     lowercase__       (       )			->				None:



       """simple docstring"""






       __UpperCamelCase	=  _get_library_root_logger().handlers

       for handler in handlers:
              __UpperCamelCase	=  logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'					)
              handler.setFormatter(__lowercase					)
def     lowercase__       (       )			->				None:



       """simple docstring"""






       __UpperCamelCase	=  _get_library_root_logger().handlers

       for handler in handlers:
              handler.setFormatter(__lowercase					)
def     lowercase__       (       self						:  int    ,  *__lowercase						:  List[str]    ,  **__lowercase						:  List[Any]					)			->				Any:



       """simple docstring"""






       __UpperCamelCase	=  os.getenv('DIFFUSERS_NO_ADVISORY_WARNINGS'    ,  __lowercase					)
       if no_advisory_warnings:
              return
       self.warning(*__lowercase    ,  **__lowercase					)


a__							:							Dict			=warning_advice

class 					snake_case					:




 """simple docstring"""



 def __init__(	self	:							Optional[int]							,     *__A	:							int							,     **__A	:							Dict     ):  # pylint: disable=unused-argument
        __UpperCamelCase	=  args[0] if args else None






 def __iter__(	self	:							str     ):
        return iter(self._iterator     )






 def __getattr__(	self	:							Tuple							,     __A	:							Any     ):

        def empty_fn(*__A	:							Any							,     **__A	:							List[str]     ):  # pylint: disable=unused-argument
               return

        return empty_fn






 def __enter__(	self	:							str     ):
        return self






 def __exit__(	self	:							Optional[Any]							,     __A	:							Dict							,     __A	:							str							,     __A	:							Dict     ):
        return






class 					snake_case					:




 """simple docstring"""



 def __call__(	self	:							Union[str, Any]							,     *__A	:							Union[str, Any]							,     **__A	:							Dict     ):
        if _tqdm_active:
               return tqdm_lib.tqdm(*__A							,     **__A     )
        else:
               return EmptyTqdm(*__A							,     **__A     )






 def 	_lowerCamelCase (	self	:							Any							,     *__A	:							str							,     **__A	:							Optional[int]     ):
        __UpperCamelCase	=  None
        if _tqdm_active:
               return tqdm_lib.tqdm.set_lock(*__A							,     **__A     )






 def 	_lowerCamelCase (	self	:							Optional[int]     ):
        if _tqdm_active:
               return tqdm_lib.tqdm.get_lock()






a__							:							List[Any]			=_tqdm_cls()
def     lowercase__       (       )			->				bool:



       """simple docstring"""






       global _tqdm_active
       return bool(_tqdm_active					)
def     lowercase__       (       )			->				List[str]:



       """simple docstring"""






       global _tqdm_active
       __UpperCamelCase	=  True


def     lowercase__       (       )			->				str:



       """simple docstring"""






       global _tqdm_active
       __UpperCamelCase	=  False
