
import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


A     :  Optional[Any]					     =       logging.get_logger(__name__)


class   lowerCamelCase					(__SCREAMING_SNAKE_CASE					):
  """simple docstring"""







  lowerCamelCase__     =						['''input_values''', '''attention_mask''']







  def __init__(							self :       int  ,     __magic_name__ :       int = 1  ,     __magic_name__ :       int = 16_000  ,     __magic_name__ :       float = 0.0  ,     __magic_name__ :       bool = False  ,     __magic_name__ :       int = 80  ,     __magic_name__ :       int = 16  ,     __magic_name__ :       int = 64  ,     __magic_name__ :       str = "hann_window"  ,     __magic_name__ :       float = 1.0  ,     __magic_name__ :       float = 80  ,     __magic_name__ :       float = 7_600  ,     __magic_name__ :       float = 1e-10  ,     __magic_name__ :       int = 2  ,     __magic_name__ :       bool = True  ,     **__magic_name__ :       str  ,     )  ->	List[str]:
        super().__init__(feature_size=_a  ,     sampling_rate=_a  ,     padding_value=_a  ,     **_a   )
        SCREAMING_SNAKE_CASE_          =  do_normalize
        SCREAMING_SNAKE_CASE_          =  return_attention_mask

        SCREAMING_SNAKE_CASE_          =  num_mel_bins
        SCREAMING_SNAKE_CASE_          =  hop_length
        SCREAMING_SNAKE_CASE_          =  win_length
        SCREAMING_SNAKE_CASE_          =  win_function
        SCREAMING_SNAKE_CASE_          =  frame_signal_scale
        SCREAMING_SNAKE_CASE_          =  fmin
        SCREAMING_SNAKE_CASE_          =  fmax
        SCREAMING_SNAKE_CASE_          =  mel_floor
        SCREAMING_SNAKE_CASE_          =  reduction_factor

        SCREAMING_SNAKE_CASE_          =  win_length * sampling_rate // 1_000
        SCREAMING_SNAKE_CASE_          =  hop_length * sampling_rate // 1_000
        SCREAMING_SNAKE_CASE_          =  optimal_fft_length(self.sample_size   )
        SCREAMING_SNAKE_CASE_          =  (self.n_fft // 2) + 1

        SCREAMING_SNAKE_CASE_          =  window_function(window_length=self.sample_size  ,     name=self.win_function  ,     periodic=_a   )

        SCREAMING_SNAKE_CASE_          =  mel_filter_bank(
            num_frequency_bins=self.n_freqs  ,     num_mel_filters=self.num_mel_bins  ,     min_frequency=self.fmin  ,     max_frequency=self.fmax  ,     sampling_rate=self.sampling_rate  ,     norm="slaney"  ,     mel_scale="slaney"  ,     )

        if frame_signal_scale != 1.0:
              warnings.warn(
                  "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"  ,     _a  ,     )
        if reduction_factor != 2.0:
              warnings.warn(
                  "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"  ,     _a  ,     )







  @staticmethod
  # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
  def    __A     (							__magic_name__ :       List[np.ndarray]  ,     __magic_name__ :       List[np.ndarray]  ,     __magic_name__ :       float = 0.0   )  ->	List[str]:




        if attention_mask is not None:
              SCREAMING_SNAKE_CASE_          =  np.array(_a  ,     np.intaa   )
              SCREAMING_SNAKE_CASE_          =  []

              for vector, length in zip(_a  ,     attention_mask.sum(-1   )   ):
                    SCREAMING_SNAKE_CASE_          =  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7   )
                    if length < normed_slice.shape[0]:
                          SCREAMING_SNAKE_CASE_          =  padding_value

                    normed_input_values.append(_a   )
        else:
              SCREAMING_SNAKE_CASE_          =  [(x - x.mean()) / np.sqrt(x.var() + 1e-7   ) for x in input_values]

        return normed_input_values







  def    __A     (							self :       List[Any]  ,     __magic_name__ :       np.ndarray  ,     )  ->	Optional[int]:
        SCREAMING_SNAKE_CASE_          =  spectrogram(
            _a  ,     window=self.window  ,     frame_length=self.sample_size  ,     hop_length=self.sample_stride  ,     fft_length=self.n_fft  ,     mel_filters=self.mel_filters  ,     mel_floor=self.mel_floor  ,     log_mel="log10"  ,     )
        return log_mel_spec.T







  def __call__(							self :       Optional[Any]  ,     __magic_name__ :       Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None  ,     __magic_name__ :       Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None  ,     __magic_name__ :       Union[bool, str, PaddingStrategy] = False  ,     __magic_name__ :       Optional[int] = None  ,     __magic_name__ :       bool = False  ,     __magic_name__ :       Optional[int] = None  ,     __magic_name__ :       Optional[bool] = None  ,     __magic_name__ :       Optional[Union[str, TensorType]] = None  ,     __magic_name__ :       Optional[int] = None  ,     **__magic_name__ :       int  ,     )  ->	List[str]:




        if audio is None and audio_target is None:
              raise ValueError("You must provide either `audio` or `audio_target` values."   )

        if sampling_rate is not None:
              if sampling_rate != self.sampling_rate:
                    raise ValueError(
                        F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
                        F''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'''
                        F''' {self.sampling_rate} and not {sampling_rate}.'''   )
        else:
              logger.warning(
                  "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
                  "Failing to do so can result in silent errors that might be hard to debug."   )

        if audio is not None:
              SCREAMING_SNAKE_CASE_          =  self._process_audio(
                  _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     **_a  ,     )
        else:
              SCREAMING_SNAKE_CASE_          =  None

        if audio_target is not None:
              SCREAMING_SNAKE_CASE_          =  self._process_audio(
                  _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     _a  ,     **_a  ,     )

              if inputs is None:
                    return inputs_target
              else:
                    SCREAMING_SNAKE_CASE_          =  inputs_target["""input_values"""]
                    SCREAMING_SNAKE_CASE_          =  inputs_target.get("attention_mask"   )
                    if decoder_attention_mask is not None:
                          SCREAMING_SNAKE_CASE_          =  decoder_attention_mask

        return inputs







  def    __A     (							self :       Union[str, Any]  ,     __magic_name__ :       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]  ,     __magic_name__ :       bool = False  ,     __magic_name__ :       Union[bool, str, PaddingStrategy] = False  ,     __magic_name__ :       Optional[int] = None  ,     __magic_name__ :       bool = False  ,     __magic_name__ :       Optional[int] = None  ,     __magic_name__ :       Optional[bool] = None  ,     __magic_name__ :       Optional[Union[str, TensorType]] = None  ,     **__magic_name__ :       Any  ,     )  ->	List[Any]:
        SCREAMING_SNAKE_CASE_          =  isinstance(_a  ,     np.ndarray   ) and len(speech.shape   ) > 1
        if is_batched_numpy and len(speech.shape   ) > 2:
              raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''   )
        SCREAMING_SNAKE_CASE_          =  is_batched_numpy or (
            isinstance(_a  ,     (list, tuple)   ) and (isinstance(speech[0]  ,     (np.ndarray, tuple, list)   ))
        )

        if is_batched:
              SCREAMING_SNAKE_CASE_          =  [np.asarray(_a  ,     dtype=np.floataa   ) for speech in speech]
        elif not is_batched and not isinstance(_a  ,     np.ndarray   ):
              SCREAMING_SNAKE_CASE_          =  np.asarray(_a  ,     dtype=np.floataa   )
        elif isinstance(_a  ,     np.ndarray   ) and speech.dtype is np.dtype(np.floataa   ):
              SCREAMING_SNAKE_CASE_          =  speech.astype(np.floataa   )

        # always return batch
        if not is_batched:
              SCREAMING_SNAKE_CASE_          =  [speech]

        # needed to make pad() work on spectrogram inputs
        SCREAMING_SNAKE_CASE_          =  self.feature_size

        # convert into correct format for padding
        if is_target:
              SCREAMING_SNAKE_CASE_          =  [self._extract_mel_features(_a   ) for waveform in speech]
              SCREAMING_SNAKE_CASE_          =  BatchFeature({"input_values": features}   )
              SCREAMING_SNAKE_CASE_          =  self.num_mel_bins
        else:
              SCREAMING_SNAKE_CASE_          =  BatchFeature({"input_values": speech}   )

        SCREAMING_SNAKE_CASE_          =  self.pad(
            _a  ,     padding=_a  ,     max_length=_a  ,     truncation=_a  ,     pad_to_multiple_of=_a  ,     return_attention_mask=_a  ,     **_a  ,     )

        SCREAMING_SNAKE_CASE_          =  feature_size_hack

        # convert input values to correct format
        SCREAMING_SNAKE_CASE_          =  padded_inputs["""input_values"""]
        if not isinstance(input_values[0]  ,     np.ndarray   ):
              SCREAMING_SNAKE_CASE_          =  [np.asarray(_a  ,     dtype=np.floataa   ) for array in input_values]
        elif (
            not isinstance(_a  ,     np.ndarray   )
            and isinstance(input_values[0]  ,     np.ndarray   )
            and input_values[0].dtype is np.dtype(np.floataa   )
        ):
              SCREAMING_SNAKE_CASE_          =  [array.astype(np.floataa   ) for array in input_values]
        elif isinstance(_a  ,     np.ndarray   ) and input_values.dtype is np.dtype(np.floataa   ):
              SCREAMING_SNAKE_CASE_          =  input_values.astype(np.floataa   )

        # convert attention_mask to correct format
        SCREAMING_SNAKE_CASE_          =  padded_inputs.get("attention_mask"   )
        if attention_mask is not None:
              SCREAMING_SNAKE_CASE_          =  [np.asarray(_a  ,     dtype=np.intaa   ) for array in attention_mask]

        # zero-mean and unit-variance normalization
        if not is_target and self.do_normalize:
              SCREAMING_SNAKE_CASE_          =  (
                  attention_mask
                  if self._get_padding_strategies(_a  ,     max_length=_a   ) is not PaddingStrategy.DO_NOT_PAD
                  else None
              )
              SCREAMING_SNAKE_CASE_          =  self.zero_mean_unit_var_norm(
                  padded_inputs["input_values"]  ,     attention_mask=_a  ,     padding_value=self.padding_value   )

        if return_tensors is not None:
              SCREAMING_SNAKE_CASE_          =  padded_inputs.convert_to_tensors(_a   )

        return padded_inputs







  def    __A     (							self :       Any   )  ->	Union[str, Any]:
        SCREAMING_SNAKE_CASE_          =  super().to_dict()

        # Don't serialize these as they are derived from the other properties.
        SCREAMING_SNAKE_CASE_          =  ["""window""", """mel_filters""", """sample_size""", """sample_stride""", """n_fft""", """n_freqs"""]
        for name in names:
              if name in output:
                    del output[name]

        return output



import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar


class   lowerCamelCase					(unittest.TestCase					):
  """simple docstring"""







  def    __A     (							self :       List[Any]   )  ->	Optional[int]:
        SCREAMING_SNAKE_CASE_          =  logging.get_logger()

        # the current default level is logging.WARNING
        SCREAMING_SNAKE_CASE_          =  logging.get_verbosity()

        logging.set_verbosity_error()
        self.assertEqual(logger.getEffectiveLevel()  ,     logging.get_verbosity()   )

        logging.set_verbosity_warning()
        self.assertEqual(logger.getEffectiveLevel()  ,     logging.get_verbosity()   )

        logging.set_verbosity_info()
        self.assertEqual(logger.getEffectiveLevel()  ,     logging.get_verbosity()   )

        logging.set_verbosity_debug()
        self.assertEqual(logger.getEffectiveLevel()  ,     logging.get_verbosity()   )

        # restore to the original level
        logging.set_verbosity(__magic_name__   )







  def    __A     (							self :       Union[str, Any]   )  ->	Tuple:
        SCREAMING_SNAKE_CASE_          =  logging.get_verbosity()

        SCREAMING_SNAKE_CASE_          =  logging.get_logger("transformers.models.bart.tokenization_bart"   )
        SCREAMING_SNAKE_CASE_          =  "Testing 1, 2, 3"

        # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
        if level_origin <= logging.WARNING:
              with CaptureLogger(__magic_name__   ) as cl:
                    logger.warning(__magic_name__   )
              self.assertEqual(cl.out  ,     msg + "\n"   )

        # this is setting the level for all of `transformers.*` loggers
        logging.set_verbosity_error()

        # should not be able to log warnings
        with CaptureLogger(__magic_name__   ) as cl:
              logger.warning(__magic_name__   )
        self.assertEqual(cl.out  ,     ""   )

        # should be able to log warnings again
        logging.set_verbosity_warning()
        with CaptureLogger(__magic_name__   ) as cl:
              logger.warning(__magic_name__   )
        self.assertEqual(cl.out  ,     msg + "\n"   )

        # restore to the original level
        logging.set_verbosity(__magic_name__   )







  @mockenv(TRANSFORMERS_VERBOSITY="error"   )
  def    __A     (							self :       int   )  ->	Optional[Any]:
        # reset for the env var to take effect, next time some logger call is made
        transformers.utils.logging._reset_library_root_logger()
        # this action activates the env var
        SCREAMING_SNAKE_CASE_          =  logging.get_logger("transformers.models.bart.tokenization_bart"   )

        SCREAMING_SNAKE_CASE_          =  os.getenv("TRANSFORMERS_VERBOSITY"  ,     __magic_name__   )
        SCREAMING_SNAKE_CASE_          =  logging.log_levels[env_level_str]

        SCREAMING_SNAKE_CASE_          =  logging.get_verbosity()
        self.assertEqual(
            __magic_name__  ,     __magic_name__  ,     F'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'''  ,     )

        # restore to the original level
        SCREAMING_SNAKE_CASE_          =  ""
        transformers.utils.logging._reset_library_root_logger()







  @mockenv(TRANSFORMERS_VERBOSITY="super-error"   )
  def    __A     (							self :       Dict   )  ->	List[Any]:
        # reset for the env var to take effect, next time some logger call is made
        transformers.utils.logging._reset_library_root_logger()
        SCREAMING_SNAKE_CASE_          =  logging.logging.getLogger()
        with CaptureLogger(__magic_name__   ) as cl:
              # this action activates the env var
              logging.get_logger("transformers.models.bart.tokenization_bart"   )
        self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error"  ,     cl.out   )

        # no need to restore as nothing was changed







  def    __A     (							self :       Dict   )  ->	Optional[int]:
        # testing `logger.warning_advice()`
        transformers.utils.logging._reset_library_root_logger()

        SCREAMING_SNAKE_CASE_          =  logging.get_logger("transformers.models.bart.tokenization_bart"   )
        SCREAMING_SNAKE_CASE_          =  "Testing 1, 2, 3"

        with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1"   ):
              # nothing should be logged as env var disables this method
              with CaptureLogger(__magic_name__   ) as cl:
                    logger.warning_advice(__magic_name__   )
              self.assertEqual(cl.out  ,     ""   )

        with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""   ):
              # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
              with CaptureLogger(__magic_name__   ) as cl:
                    logger.warning_advice(__magic_name__   )
              self.assertEqual(cl.out  ,     msg + "\n"   )



def      a__ (		):
      disable_progress_bar()
      assert are_progress_bars_disabled()

      enable_progress_bar()
      assert not are_progress_bars_disabled()


