


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

import numpy as np
import torch

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


__UpperCAmelCase      :List[str]			    =       logging.get_logger(__name__)



class      a    (		_a	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			str							       =       ["input_features", "is_longer"]

     def __init__(    self					:		Optional[Any]							,			snake_case					:		int=64							,			snake_case					:		List[str]=4_8000							,			snake_case					:		int=480							,			snake_case					:		Optional[int]=10							,			snake_case					:		List[str]=1024							,			snake_case					:		List[str]=0.0							,			snake_case					:		Union[str, Any]=False							,			snake_case					:		float = 0							,			snake_case					:		float = 1_4000							,			snake_case					:		int = None							,			snake_case					:		str = "fusion"							,			snake_case					:		str = "repeatpad"							,			**snake_case					:		Dict							,			)						->							Union[str, Any]:
          super().__init__(
              feature_size=snake_case							,			sampling_rate=snake_case							,			padding_value=snake_case							,			return_attention_mask=snake_case							,			**snake_case							,			)
          __UpperCAmelCase     :			str  							=      top_db
          __UpperCAmelCase     :			List[str]  							=      truncation
          __UpperCAmelCase     :			Union[str, Any]  							=      padding
          __UpperCAmelCase     :			str  							=      fft_window_size
          __UpperCAmelCase     :			List[str]  							=      (fft_window_size >> 1) + 1
          __UpperCAmelCase     :			Any  							=      hop_length
          __UpperCAmelCase     :			Optional[Any]  							=      max_length_s
          __UpperCAmelCase     :			str  							=      max_length_s * sampling_rate
          __UpperCAmelCase     :			Any  							=      sampling_rate
          __UpperCAmelCase     :			Optional[int]  							=      frequency_min
          __UpperCAmelCase     :			Dict  							=      frequency_max
          __UpperCAmelCase     :			Optional[int]  							=      mel_filter_bank(
              num_frequency_bins=self.nb_frequency_bins							,			num_mel_filters=snake_case							,			min_frequency=snake_case							,			max_frequency=snake_case							,			sampling_rate=snake_case							,			norm=snake_case							,			mel_scale='''htk'''							,			)
          __UpperCAmelCase     :			List[Any]  							=      mel_filter_bank(
              num_frequency_bins=self.nb_frequency_bins							,			num_mel_filters=snake_case							,			min_frequency=snake_case							,			max_frequency=snake_case							,			sampling_rate=snake_case							,			norm='''slaney'''							,			mel_scale='''slaney'''							,			)

     def 			lowerCamelCase__			(    self					:		str      )						->							Dict[str, Any]:
          __UpperCAmelCase     :			int  							=      copy.deepcopy(self.__dict__      )
          __UpperCAmelCase     :			Optional[int]  							=      self.__class__.__name__
          if "mel_filters" in output:
               del output["mel_filters"]
          if "mel_filters_slaney" in output:
               del output["mel_filters_slaney"]
          return output

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		np.array							,			snake_case					:		Optional[np.array] = None      )						->							np.ndarray:
          __UpperCAmelCase     :			Dict  							=      spectrogram(
              snake_case							,			window_function(self.fft_window_size							,			'''hann'''      )							,			frame_length=self.fft_window_size							,			hop_length=self.hop_length							,			power=2.0							,			mel_filters=snake_case							,			log_mel='''dB'''							,			)
          return log_mel_spectrogram.T

     def 			lowerCamelCase__			(    self					:		Optional[int]							,			snake_case					:		List[str]							,			snake_case					:		List[Any]							,			snake_case					:		Tuple      )						->							List[str]:
          __UpperCAmelCase     :			int  							=      np.array_split(list(range(0							,			total_frames - chunk_frames + 1      )      )							,			3      )
          if len(ranges[1]      ) == 0:
               # if the audio is too short, we just use the first chunk
               __UpperCAmelCase     :			List[Any]  							=      [0]
          if len(ranges[2]      ) == 0:
               # if the audio is too short, we just use the first chunk
               __UpperCAmelCase     :			str  							=      [0]
          # randomly choose index for each part
          __UpperCAmelCase     :			Any  							=      np.random.choice(ranges[0]      )
          __UpperCAmelCase     :			List[str]  							=      np.random.choice(ranges[1]      )
          __UpperCAmelCase     :			Dict  							=      np.random.choice(ranges[2]      )

          __UpperCAmelCase     :			Dict  							=      mel[idx_front : idx_front + chunk_frames, :]
          __UpperCAmelCase     :			Optional[int]  							=      mel[idx_middle : idx_middle + chunk_frames, :]
          __UpperCAmelCase     :			Any  							=      mel[idx_back : idx_back + chunk_frames, :]

          __UpperCAmelCase     :			Any  							=      torch.tensor(mel[None, None, :]      )
          __UpperCAmelCase     :			List[str]  							=      torch.nn.functional.interpolate(
              snake_case							,			size=[chunk_frames, 64]							,			mode='''bilinear'''							,			align_corners=snake_case      )
          __UpperCAmelCase     :			List[Any]  							=      mel_shrink[0][0].numpy()
          __UpperCAmelCase     :			int  							=      np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]							,			axis=0      )
          return mel_fusion

     def 			lowerCamelCase__			(    self					:		Dict							,			snake_case					:		np.array							,			snake_case					:		Optional[Any]							,			snake_case					:		List[Any]							,			snake_case					:		Optional[Any]      )						->							np.array:
          if waveform.shape[0] > max_length:
               if truncation == "rand_trunc":
                    __UpperCAmelCase     :			Optional[Any]  							=      True
                    # random crop to max_length (for compatibility) -> this should be handled by self.pad
                    __UpperCAmelCase     :			Dict  							=      len(snake_case      ) - max_length
                    __UpperCAmelCase     :			Optional[int]  							=      np.random.randint(0							,			overflow + 1      )
                    __UpperCAmelCase     :			Dict  							=      waveform[idx : idx + max_length]
                    __UpperCAmelCase     :			List[str]  							=      self._np_extract_fbank_features(snake_case							,			self.mel_filters_slaney      )[None, :]
               elif truncation == "fusion":
                    __UpperCAmelCase     :			Dict  							=      self._np_extract_fbank_features(snake_case							,			self.mel_filters      )
                    __UpperCAmelCase     :			Tuple  							=      max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
                    __UpperCAmelCase     :			int  							=      mel.shape[0]
                    if chunk_frames == total_frames:
                         # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
                         # In this case, we just use the whole audio.
                         __UpperCAmelCase     :			str  							=      np.stack([mel, mel, mel, mel]							,			axis=0      )
                         __UpperCAmelCase     :			Union[str, Any]  							=      False
                    else:
                         __UpperCAmelCase     :			List[Any]  							=      self._random_mel_fusion(snake_case							,			snake_case							,			snake_case      )
                         __UpperCAmelCase     :			Optional[Any]  							=      True
               else:
                    raise NotImplementedError(f'data_truncating {truncation} not implemented'      )

          else:
               __UpperCAmelCase     :			Dict  							=      False
               # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
               if waveform.shape[0] < max_length:
                    if padding == "repeat":
                         __UpperCAmelCase     :			Tuple  							=      int(max_length / len(snake_case      )      )
                         __UpperCAmelCase     :			Tuple  							=      np.stack(np.tile(snake_case							,			n_repeat + 1      )      )[:max_length]
                    if padding == "repeatpad":
                         __UpperCAmelCase     :			Union[str, Any]  							=      int(max_length / len(snake_case      )      )
                         __UpperCAmelCase     :			Tuple  							=      np.stack(np.tile(snake_case							,			snake_case      )      )
                    __UpperCAmelCase     :			List[Any]  							=      np.pad(snake_case							,			(0, max_length - waveform.shape[0])							,			mode='''constant'''							,			constant_values=0      )

               if truncation == "fusion":
                    __UpperCAmelCase     :			Optional[int]  							=      self._np_extract_fbank_features(snake_case							,			self.mel_filters      )
                    __UpperCAmelCase     :			Optional[int]  							=      np.stack([input_mel, input_mel, input_mel, input_mel]							,			axis=0      )
               else:
                    __UpperCAmelCase     :			List[str]  							=      self._np_extract_fbank_features(snake_case							,			self.mel_filters_slaney      )[None, :]

          return input_mel, longer






     def __call__(    self					:		str							,			snake_case					:		Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,			snake_case					:		str = None							,			snake_case					:		Optional[str] = None							,			snake_case					:		Optional[int] = None							,			snake_case					:		Optional[int] = None							,			snake_case					:		Optional[Union[str, TensorType]] = None							,			**snake_case					:		Dict							,			)						->							BatchFeature:
          __UpperCAmelCase     :			List[Any]  							=      truncation if truncation is not None else self.truncation
          __UpperCAmelCase     :			Union[str, Any]  							=      padding if padding else self.padding

          if sampling_rate is not None:
               if sampling_rate != self.sampling_rate:
                    raise ValueError(
                        f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'
                        f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'
                        f' was sampled with {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.'''      )

          __UpperCAmelCase     :			Optional[int]  							=      isinstance(snake_case							,			np.ndarray      ) and len(raw_speech.shape      ) > 1
          if is_batched_numpy and len(raw_speech.shape      ) > 2:
               raise ValueError(f'Only mono-channel audio is supported for input to {self}'      )
          __UpperCAmelCase     :			int  							=      is_batched_numpy or (
              isinstance(snake_case							,			(list, tuple)      ) and (isinstance(raw_speech[0]							,			(np.ndarray, tuple, list)      ))
          )

          if is_batched:
               __UpperCAmelCase     :			int  							=      [np.asarray(snake_case							,			dtype=np.floataa      ) for speech in raw_speech]
          elif not is_batched and not isinstance(snake_case							,			np.ndarray      ):
               __UpperCAmelCase     :			Union[str, Any]  							=      np.asarray(snake_case							,			dtype=np.floataa      )
          elif isinstance(snake_case							,			np.ndarray      ) and raw_speech.dtype is np.dtype(np.floataa      ):
               __UpperCAmelCase     :			Optional[Any]  							=      raw_speech.astype(np.floataa      )

          # always return batch
          if not is_batched:
               __UpperCAmelCase     :			Any  							=      [np.asarray(snake_case      )]

          # convert to mel spectrogram, truncate and pad if needed.
          __UpperCAmelCase     :			Optional[Any]  							=      [
              self._get_input_mel(snake_case							,			max_length if max_length else self.nb_max_samples							,			snake_case							,			snake_case      )
              for waveform in raw_speech
          ]

          __UpperCAmelCase     :			Any  							=      []
          __UpperCAmelCase     :			Any  							=      []
          for mel, longer in padded_inputs:
               input_mel.append(snake_case      )
               is_longer.append(snake_case      )

          if truncation == "fusion" and sum(snake_case      ) == 0:
               # if no audio is longer than 10s, then randomly select one audio to be longer
               __UpperCAmelCase     :			int  							=      np.random.randint(0							,			len(snake_case      )      )
               __UpperCAmelCase     :			List[str]  							=      True

          if isinstance(input_mel[0]							,			snake_case      ):
               __UpperCAmelCase     :			str  							=      [np.asarray(snake_case							,			dtype=np.floataa      ) for feature in input_mel]

          # is_longer is a list of bool
          __UpperCAmelCase     :			Optional[int]  							=      [[longer] for longer in is_longer]

          __UpperCAmelCase     :			List[str]  							=      {'''input_features''': input_mel, '''is_longer''': is_longer}
          __UpperCAmelCase     :			Optional[Any]  							=      BatchFeature(snake_case      )

          if return_tensors is not None:
               __UpperCAmelCase     :			List[Any]  							=      input_features.convert_to_tensors(snake_case      )

          return input_features



'''simple docstring'''



import os
import sys
import unittest


__UpperCAmelCase      :Optional[int]			    =       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__UpperCAmelCase      :Dict			    =       os.path.join(git_repo_path, "src", "diffusers")



class      a    (		unittest.TestCase	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Any      )						->							int:
          __UpperCAmelCase     :			Optional[Any]  							=      find_backend('''    if not is_torch_available():'''      )
          self.assertEqual(snake_case							,			'''torch'''      )

          # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
          # self.assertEqual(backend_with_underscore, "tensorflow_text")

          __UpperCAmelCase     :			Union[str, Any]  							=      find_backend('''    if not (is_torch_available() and is_transformers_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers'''      )

          # double_backend_with_underscore = find_backend(
          #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
          # )
          # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

          __UpperCAmelCase     :			List[str]  							=      find_backend(
              '''    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers_and_onnx'''      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							int:
          __UpperCAmelCase     :			Tuple  							=      read_init()
          # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
          self.assertIn('''torch'''							,			snake_case      )
          self.assertIn('''torch_and_transformers'''							,			snake_case      )
          self.assertIn('''flax_and_transformers'''							,			snake_case      )
          self.assertIn('''torch_and_transformers_and_onnx'''							,			snake_case      )

          # Likewise, we can't assert on the exact content of a key
          self.assertIn('''UNet2DModel'''							,			objects['''torch''']      )
          self.assertIn('''FlaxUNet2DConditionModel'''							,			objects['''flax''']      )
          self.assertIn('''StableDiffusionPipeline'''							,			objects['''torch_and_transformers''']      )
          self.assertIn('''FlaxStableDiffusionPipeline'''							,			objects['''flax_and_transformers''']      )
          self.assertIn('''LMSDiscreteScheduler'''							,			objects['''torch_and_scipy''']      )
          self.assertIn('''OnnxStableDiffusionPipeline'''							,			objects['''torch_and_transformers_and_onnx''']      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							List[Any]:
          __UpperCAmelCase     :			str  							=      create_dummy_object('''CONSTANT'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			'''\nCONSTANT = None\n'''      )

          __UpperCAmelCase     :			Union[str, Any]  							=      create_dummy_object('''function'''							,			'''\'torch\''''      )
          self.assertEqual(
              snake_case							,			'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'''      )

          __UpperCAmelCase     :			Optional[int]  							=      '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')
'''
          __UpperCAmelCase     :			Optional[Any]  							=      create_dummy_object('''FakeClass'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			snake_case      )






     def 			lowerCamelCase__			(    self					:		int      )						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])
'''
          __UpperCAmelCase     :			Optional[int]  							=      create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']}      )
          self.assertEqual(dummy_files['''torch''']							,			snake_case      )