
"""simple docstring"""






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


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)





class 				a__					(						A__       ):
     UpperCAmelCase__         =      ['''input_values''', '''attention_mask''']



     def __init__(							self :List[Any]      ,  _lowerCamelCase :int = 1      ,  _lowerCamelCase :int = 16_000      ,  _lowerCamelCase :float = 0.0      ,  _lowerCamelCase :bool = False      ,  _lowerCamelCase :int = 80      ,  _lowerCamelCase :int = 16      ,  _lowerCamelCase :int = 64      ,  _lowerCamelCase :str = "hann_window"      ,  _lowerCamelCase :float = 1.0      ,  _lowerCamelCase :float = 80      ,  _lowerCamelCase :float = 7_600      ,  _lowerCamelCase :float = 1E-1_0      ,  _lowerCamelCase :int = 2      ,  _lowerCamelCase :bool = True      ,  **_lowerCamelCase :Union[str, Any]      ,  ):







      '''simple docstring'''



      super().__init__(feature_size=_lowerCamelCase      ,  sampling_rate=_lowerCamelCase      ,  padding_value=_lowerCamelCase      ,  **_lowerCamelCase   )
      UpperCamelCase_     :					Union[str, Any]   	=do_normalize
      UpperCamelCase_     :					Dict   	=return_attention_mask

      UpperCamelCase_     :					Any   	=num_mel_bins
      UpperCamelCase_     :					Union[str, Any]   	=hop_length
      UpperCamelCase_     :					List[str]   	=win_length
      UpperCamelCase_     :					int   	=win_function
      UpperCamelCase_     :					Any   	=frame_signal_scale
      UpperCamelCase_     :					List[str]   	=fmin
      UpperCamelCase_     :					str   	=fmax
      UpperCamelCase_     :					Optional[int]   	=mel_floor
      UpperCamelCase_     :					Any   	=reduction_factor

      UpperCamelCase_     :					Optional[int]   	=win_length * sampling_rate // 1_000
      UpperCamelCase_     :					List[Any]   	=hop_length * sampling_rate // 1_000
      UpperCamelCase_     :					Dict   	=optimal_fft_length(self.sample_size   )
      UpperCamelCase_     :					Any   	=(self.n_fft // 2) + 1

      UpperCamelCase_     :					Optional[Any]   	=window_function(window_length=self.sample_size      ,  name=self.win_function      ,  periodic=_lowerCamelCase   )

      UpperCamelCase_     :					Any   	=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'      ,  _lowerCamelCase      ,  )
      if reduction_factor != 2.0:
       warnings.warn(
           'The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers'      ,  _lowerCamelCase      ,  )



     @staticmethod
     # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
     def  lowerCamelCase_						(							_lowerCamelCase :List[np.ndarray]      ,  _lowerCamelCase :List[np.ndarray]      ,  _lowerCamelCase :float = 0.0   ):







      '''simple docstring'''



      if attention_mask is not None:
       UpperCamelCase_     :					Dict   	=np.array(_lowerCamelCase      ,  np.intaa   )
       UpperCamelCase_     :					Any   	=[]

       for vector, length in zip(_lowerCamelCase      ,  attention_mask.sum(-1   )   ):
        UpperCamelCase_     :					Union[str, Any]   	=(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7   )
        if length < normed_slice.shape[0]:
         UpperCamelCase_     :					str   	=padding_value

        normed_input_values.append(_lowerCamelCase   )
      else:
       UpperCamelCase_     :					int   	=[(x - x.mean()) / np.sqrt(x.var() + 1E-7   ) for x in input_values]

      return normed_input_values



     def  lowerCamelCase_						(							self :List[str]      ,  _lowerCamelCase :np.ndarray      ,  ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=spectrogram(
          _lowerCamelCase      ,  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 :str      ,  _lowerCamelCase :Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None      ,  _lowerCamelCase :Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None      ,  _lowerCamelCase :Union[bool, str, PaddingStrategy] = False      ,  _lowerCamelCase :Optional[int] = None      ,  _lowerCamelCase :bool = False      ,  _lowerCamelCase :Optional[int] = None      ,  _lowerCamelCase :Optional[bool] = None      ,  _lowerCamelCase :Optional[Union[str, TensorType]] = None      ,  _lowerCamelCase :Optional[int] = None      ,  **_lowerCamelCase :int      ,  ):







      '''simple docstring'''



      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:
       UpperCamelCase_     :					int   	=self._process_audio(
           _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  **_lowerCamelCase      ,  )
      else:
       UpperCamelCase_     :					Any   	=None

      if audio_target is not None:
       UpperCamelCase_     :					List[Any]   	=self._process_audio(
           _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  _lowerCamelCase      ,  **_lowerCamelCase      ,  )

       if inputs is None:
        return inputs_target
       else:
        UpperCamelCase_     :					List[Any]   	=inputs_target['input_values']
        UpperCamelCase_     :					Any   	=inputs_target.get('attention_mask'   )
        if decoder_attention_mask is not None:
         UpperCamelCase_     :					Union[str, Any]   	=decoder_attention_mask

      return inputs



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







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	=isinstance(_lowerCamelCase      ,  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}'''   )
      UpperCamelCase_     :					Union[str, Any]   	=is_batched_numpy or (
          isinstance(_lowerCamelCase      ,  (list, tuple)   ) and (isinstance(speech[0]      ,  (np.ndarray, tuple, list)   ))
      )

      if is_batched:
       UpperCamelCase_     :					List[str]   	=[np.asarray(_lowerCamelCase      ,  dtype=np.floataa   ) for speech in speech]
      elif not is_batched and not isinstance(_lowerCamelCase      ,  np.ndarray   ):
       UpperCamelCase_     :					List[str]   	=np.asarray(_lowerCamelCase      ,  dtype=np.floataa   )
      elif isinstance(_lowerCamelCase      ,  np.ndarray   ) and speech.dtype is np.dtype(np.floataa   ):
       UpperCamelCase_     :					Optional[int]   	=speech.astype(np.floataa   )

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

      # needed to make pad() work on spectrogram inputs
      UpperCamelCase_     :					Optional[Any]   	=self.feature_size

      # convert into correct format for padding
      if is_target:
       UpperCamelCase_     :					Optional[int]   	=[self._extract_mel_features(_lowerCamelCase   ) for waveform in speech]
       UpperCamelCase_     :					Dict   	=BatchFeature({'input_values': features}   )
       UpperCamelCase_     :					Optional[int]   	=self.num_mel_bins
      else:
       UpperCamelCase_     :					Union[str, Any]   	=BatchFeature({'input_values': speech}   )

      UpperCamelCase_     :					int   	=self.pad(
          _lowerCamelCase      ,  padding=_lowerCamelCase      ,  max_length=_lowerCamelCase      ,  truncation=_lowerCamelCase      ,  pad_to_multiple_of=_lowerCamelCase      ,  return_attention_mask=_lowerCamelCase      ,  **_lowerCamelCase      ,  )

      UpperCamelCase_     :					int   	=feature_size_hack

      # convert input values to correct format
      UpperCamelCase_     :					Dict   	=padded_inputs['input_values']
      if not isinstance(input_values[0]      ,  np.ndarray   ):
       UpperCamelCase_     :					int   	=[np.asarray(_lowerCamelCase      ,  dtype=np.floataa   ) for array in input_values]
      elif (
          not isinstance(_lowerCamelCase      ,  np.ndarray   )
          and isinstance(input_values[0]      ,  np.ndarray   )
          and input_values[0].dtype is np.dtype(np.floataa   )
      ):
       UpperCamelCase_     :					Union[str, Any]   	=[array.astype(np.floataa   ) for array in input_values]
      elif isinstance(_lowerCamelCase      ,  np.ndarray   ) and input_values.dtype is np.dtype(np.floataa   ):
       UpperCamelCase_     :					Optional[Any]   	=input_values.astype(np.floataa   )

      # convert attention_mask to correct format
      UpperCamelCase_     :					int   	=padded_inputs.get('attention_mask'   )
      if attention_mask is not None:
       UpperCamelCase_     :					str   	=[np.asarray(_lowerCamelCase      ,  dtype=np.intaa   ) for array in attention_mask]

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

      if return_tensors is not None:
       UpperCamelCase_     :					Optional[int]   	=padded_inputs.convert_to_tensors(_lowerCamelCase   )

      return padded_inputs




     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=super().to_dict()

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

      return output


"""simple docstring"""






from manim import *





class 				a__					(						A__       ):



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=Rectangle(height=0.5      ,  width=0.5   )
      UpperCamelCase_     :					Any   	=Rectangle(height=0.46      ,  width=0.46   ).set_stroke(width=0   )

      UpperCamelCase_     :					Any   	=[mem.copy() for i in range(6   )]
      UpperCamelCase_     :					Optional[int]   	=[mem.copy() for i in range(6   )]
      UpperCamelCase_     :					List[str]   	=VGroup(*_lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )
      UpperCamelCase_     :					Optional[int]   	=VGroup(*_lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )
      UpperCamelCase_     :					Union[str, Any]   	=VGroup(_lowerCamelCase      ,  _lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )
      UpperCamelCase_     :					str   	=Text('CPU'      ,  font_size=24   )
      UpperCamelCase_     :					str   	=Group(_lowerCamelCase      ,  _lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0.5      ,  aligned_edge=_lowerCamelCase   )
      cpu.move_to([-2.5, -0.5, 0]   )
      self.add(_lowerCamelCase   )

      UpperCamelCase_     :					int   	=[mem.copy() for i in range(4   )]
      UpperCamelCase_     :					Any   	=VGroup(*_lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )
      UpperCamelCase_     :					List[Any]   	=Text('GPU'      ,  font_size=24   )
      UpperCamelCase_     :					Any   	=Group(_lowerCamelCase      ,  _lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0.5      ,  aligned_edge=_lowerCamelCase   )
      gpu.move_to([-1, -1, 0]   )
      self.add(_lowerCamelCase   )

      UpperCamelCase_     :					List[str]   	=[mem.copy() for i in range(6   )]
      UpperCamelCase_     :					str   	=VGroup(*_lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )

      UpperCamelCase_     :					Optional[int]   	=Text('Model'      ,  font_size=24   )
      UpperCamelCase_     :					List[Any]   	=Group(_lowerCamelCase      ,  _lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0.5      ,  aligned_edge=_lowerCamelCase   )
      model.move_to([3, -1.0, 0]   )
      self.add(_lowerCamelCase   )

      UpperCamelCase_     :					int   	=[]
      for i, rect in enumerate(_lowerCamelCase   ):
       rect.set_stroke(_lowerCamelCase   )
       # target = fill.copy().set_fill(YELLOW, opacity=0.7)
       # target.move_to(rect)
       # self.add(target)

       UpperCamelCase_     :					str   	=Rectangle(height=0.46 / 4      ,  width=0.46 / 3   ).set_stroke(width=0.0   ).set_fill(_lowerCamelCase      ,  opacity=0.7   )

       if i == 0:
        cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT   )      ,  buff=0.02      ,  direction=_lowerCamelCase   )
        cpu_target.set_x(cpu_target.get_x() + 0.1   )
       elif i == 3:
        cpu_target.next_to(cpu_targs[0]      ,  direction=_lowerCamelCase      ,  buff=0.0   )
       else:
        cpu_target.next_to(cpu_targs[i - 1]      ,  direction=_lowerCamelCase      ,  buff=0.0   )
       self.add(_lowerCamelCase   )
       cpu_targs.append(_lowerCamelCase   )

      UpperCamelCase_     :					List[str]   	=[mem.copy() for i in range(6   )]
      UpperCamelCase_     :					Any   	=VGroup(*_lowerCamelCase   ).arrange(_lowerCamelCase      ,  buff=0   )

      UpperCamelCase_     :					Optional[int]   	=Text('Loaded Checkpoint'      ,  font_size=24   )
      UpperCamelCase_     :					List[Any]   	=Group(_lowerCamelCase      ,  _lowerCamelCase   ).arrange(_lowerCamelCase      ,  aligned_edge=_lowerCamelCase      ,  buff=0.4   )
      checkpoint.move_to([3, 0.5, 0]   )

      UpperCamelCase_     :					int   	=Square(side_length=2.2   )
      key.move_to([-5, 2, 0]   )

      UpperCamelCase_     :					Optional[Any]   	=MarkupText(
          f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'''      ,  font_size=18      ,  )

      key_text.move_to([-5, 2.4, 0]   )

      self.add(_lowerCamelCase      ,  _lowerCamelCase   )

      UpperCamelCase_     :					Any   	=MarkupText(
          f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'''      ,  font_size=18      ,  )

      blue_text.next_to(_lowerCamelCase      ,  DOWN * 2.4      ,  aligned_edge=key_text.get_left()   )

      UpperCamelCase_     :					Dict   	=MarkupText(
          f'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.'''      ,  font_size=24      ,  )
      step_a.move_to([2, 2, 0]   )
      self.play(Write(_lowerCamelCase   )      ,  Write(_lowerCamelCase   )   )

      self.play(Write(_lowerCamelCase      ,  run_time=1   )      ,  Create(_lowerCamelCase      ,  run_time=1   )   )

      UpperCamelCase_     :					Union[str, Any]   	=[]
      UpperCamelCase_     :					List[Any]   	=[]
      for i, rect in enumerate(_lowerCamelCase   ):
       UpperCamelCase_     :					str   	=fill.copy().set_fill(_lowerCamelCase      ,  opacity=0.7   )
       target.move_to(_lowerCamelCase   )
       first_animations.append(GrowFromCenter(_lowerCamelCase      ,  run_time=1   )   )

       UpperCamelCase_     :					Any   	=target.copy()
       cpu_target.generate_target()
       if i < 5:
        cpu_target.target.move_to(cpu_left_col_base[i + 1]   )
       else:
        cpu_target.target.move_to(cpu_right_col_base[i - 5]   )
       second_animations.append(MoveToTarget(_lowerCamelCase      ,  run_time=1.5   )   )

      self.play(*_lowerCamelCase   )
      self.play(*_lowerCamelCase   )
      self.wait()
