

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


_lowercase		:				Union[str, Any]      		=logging.get_logger(__name__)

class        snake_case__    (A__		):







						"""simple docstring"""




						__lowerCAmelCase					:Optional[int]      =					["input_values", "attention_mask"]

						def __init__(       self ,       __lowercase = 1 ,       __lowercase = 1_6_0_0_0 ,       __lowercase = 0.0 ,       __lowercase = False ,       __lowercase = 8_0 ,       __lowercase = 1_6 ,       __lowercase = 6_4 ,       __lowercase = "hann_window" ,       __lowercase = 1.0 ,       __lowercase = 8_0 ,       __lowercase = 7_6_0_0 ,       __lowercase = 1E-10 ,       __lowercase = 2 ,       __lowercase = True ,       **__lowercase ,       ) ->				List[Any]:
									"""simple docstring"""




									super().__init__(feature_size=_lowerCAmelCase ,       sampling_rate=_lowerCAmelCase ,       padding_value=_lowerCAmelCase ,       **_lowerCAmelCase  )
									a__       :						List[Any]							=  do_normalize
									a__       :						int							=  return_attention_mask

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

									a__       :						List[Any]							=  win_length * sampling_rate // 1_0_0_0
									a__       :						Any							=  hop_length * sampling_rate // 1_0_0_0
									a__       :						List[Any]							=  optimal_fft_length(self.sample_size  )
									a__       :						List[Any]							=  (self.n_fft // 2) + 1

									a__       :						int							=  window_function(window_length=self.sample_size ,       name=self.win_function ,       periodic=_lowerCAmelCase  )

									a__       :						str							=  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 							SCREAMING_SNAKE_CASE__(       __lowercase ,       __lowercase ,       __lowercase = 0.0  ) ->				Tuple:
									"""simple docstring"""




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

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

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

									return normed_input_values

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       ) ->				Union[str, Any]:
									"""simple docstring"""




									a__       :						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 ,       __lowercase = None ,       __lowercase = None ,       __lowercase = False ,       __lowercase = None ,       __lowercase = False ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       **__lowercase ,       ) ->				Optional[Any]:
									"""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:
												a__       :						Union[str, Any]							=  self._process_audio(
												    _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       **_lowerCAmelCase ,       )
									else:
												a__       :						List[Any]							=  None

									if audio_target is not None:
												a__       :						Any							=  self._process_audio(
												    _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       _lowerCAmelCase ,       **_lowerCAmelCase ,       )

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

									return inputs

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase = False ,       __lowercase = False ,       __lowercase = None ,       __lowercase = False ,       __lowercase = None ,       __lowercase = None ,       __lowercase = None ,       **__lowercase ,       ) ->				int:
									"""simple docstring"""




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

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

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

									# needed to make pad() work on spectrogram inputs
									a__       :						Tuple							=  self.feature_size

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

									a__       :						str							=  self.pad(
									    _lowerCAmelCase ,       padding=_lowerCAmelCase ,       max_length=_lowerCAmelCase ,       truncation=_lowerCAmelCase ,       pad_to_multiple_of=_lowerCAmelCase ,       return_attention_mask=_lowerCAmelCase ,       **_lowerCAmelCase ,       )

									a__       :						int							=  feature_size_hack

									# convert input values to correct format
									a__       :						Any							=  padded_inputs["""input_values"""]
									if not isinstance(input_values[0] ,       np.ndarray  ):
												a__       :						Any							=  [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  )
									):
												a__       :						List[Any]							=  [array.astype(np.floataa  ) for array in input_values]
									elif isinstance(_lowerCAmelCase ,       np.ndarray  ) and input_values.dtype is np.dtype(np.floataa  ):
												a__       :						Tuple							=  input_values.astype(np.floataa  )

									# convert attention_mask to correct format
									a__       :						Tuple							=  padded_inputs.get("""attention_mask"""  )
									if attention_mask is not None:
												a__       :						List[Any]							=  [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:
												a__       :						List[Any]							=  (
												    attention_mask
												    if self._get_padding_strategies(_lowerCAmelCase ,       max_length=_lowerCAmelCase  ) is not PaddingStrategy.DO_NOT_PAD
												    else None
												)
												a__       :						List[Any]							=  self.zero_mean_unit_var_norm(
												    padded_inputs["""input_values"""] ,       attention_mask=_lowerCAmelCase ,       padding_value=self.padding_value  )

									if return_tensors is not None:
												a__       :						Dict							=  padded_inputs.convert_to_tensors(_lowerCAmelCase  )

									return padded_inputs

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Any:
									"""simple docstring"""




									a__       :						Optional[int]							=  super().to_dict()

									# Don't serialize these as they are derived from the other properties.
									a__       :						List[Any]							=  ["""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 importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


_lowercase		:				int      		=(
    "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py"
)


_lowercase		:				Dict      		=logging.get_logger(__name__)  # pylint: disable=invalid-name

def      lowerCAmelCase_					(  )							->	Union[str, Any]:







			"""simple docstring"""
			a__       :						List[Any]							=  """https://pypi.org/pypi/diffusers/json"""
			a__       :						Tuple							=  json.loads(request.urlopen(_lowercase).read())["""releases"""].keys()
			return sorted(_lowercase						,       key=lambda _lowercase: version.Version(_lowercase))

def      lowerCAmelCase_					(  )							->	Optional[Any]:







			"""simple docstring"""
			# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
			if HF_MODULES_CACHE in sys.path:
						return

			sys.path.append(_lowercase)
			os.makedirs(_lowercase						,       exist_ok=_lowercase)
			a__       :						Tuple							=  Path(_lowercase) / """__init__.py"""
			if not init_path.exists():
						init_path.touch()

def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike])							->	Optional[Any]:







			"""simple docstring"""
			init_hf_modules()
			a__       :						Optional[int]							=  Path(_lowercase) / name
			# If the parent module does not exist yet, recursively create it.
			if not dynamic_module_path.parent.exists():
						create_dynamic_module(dynamic_module_path.parent)
			os.makedirs(_lowercase						,       exist_ok=_lowercase)
			a__       :						Any							=  dynamic_module_path / """__init__.py"""
			if not init_path.exists():
						init_path.touch()

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Optional[int]:







			"""simple docstring"""
			with open(_lowercase						,       """r"""						,       encoding="""utf-8""") as f:
						a__       :						Union[str, Any]							=  f.read()

			# Imports of the form `import .xxx`
			a__       :						Optional[Any]							=  re.findall("""^\s*import\s+\.(\S+)\s*$"""						,       _lowercase						,       flags=re.MULTILINE)
			# Imports of the form `from .xxx import yyy`
			relative_imports += re.findall("""^\s*from\s+\.(\S+)\s+import"""						,       _lowercase						,       flags=re.MULTILINE)
			# Unique-ify
			return list(set(_lowercase))

def      lowerCAmelCase_					(  _lowercase    :       List[Any])							->	Dict:







			"""simple docstring"""
			a__       :						Dict							=  False
			a__       :						str							=  [module_file]
			a__       :						List[Any]							=  []

			# Let's recurse through all relative imports
			while not no_change:
						a__       :						Optional[Any]							=  []
						for f in files_to_check:
									new_imports.extend(get_relative_imports(_lowercase))

						a__       :						Dict							=  Path(_lowercase).parent
						a__       :						Any							=  [str(module_path / m) for m in new_imports]
						a__       :						Any							=  [f for f in new_import_files if f not in all_relative_imports]
						a__       :						List[Any]							=  [F'''{f}.py''' for f in new_import_files]

						a__       :						List[Any]							=  len(_lowercase) == 0
						all_relative_imports.extend(_lowercase)

			return all_relative_imports

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	Any:







			"""simple docstring"""
			with open(_lowercase						,       """r"""						,       encoding="""utf-8""") as f:
						a__       :						Optional[Any]							=  f.read()

			# Imports of the form `import xxx`
			a__       :						Optional[int]							=  re.findall("""^\s*import\s+(\S+)\s*$"""						,       _lowercase						,       flags=re.MULTILINE)
			# Imports of the form `from xxx import yyy`
			imports += re.findall("""^\s*from\s+(\S+)\s+import"""						,       _lowercase						,       flags=re.MULTILINE)
			# Only keep the top-level module
			a__       :						Any							=  [imp.split(""".""")[0] for imp in imports if not imp.startswith(""".""")]

			# Unique-ify and test we got them all
			a__       :						Optional[Any]							=  list(set(_lowercase))
			a__       :						Union[str, Any]							=  []
			for imp in imports:
						try:
									importlib.import_module(_lowercase)
						except ImportError:
									missing_packages.append(_lowercase)

			if len(_lowercase) > 0:
						raise ImportError(
						    """This modeling file requires the following packages that were not found in your environment: """
						    F'''{', '.join(_lowercase)}. Run `pip install {' '.join(_lowercase)}`''')

			return get_relative_imports(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       int						,       _lowercase    :       Tuple)							->	Union[str, Any]:







			"""simple docstring"""
			a__       :						Dict							=  module_path.replace(os.path.sep						,       """.""")
			a__       :						List[Any]							=  importlib.import_module(_lowercase)

			if class_name is None:
						return find_pipeline_class(_lowercase)
			return getattr(_lowercase						,       _lowercase)

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Optional[int]:







			"""simple docstring"""
			from ..pipelines import DiffusionPipeline

			a__       :						Any							=  dict(inspect.getmembers(_lowercase						,       inspect.isclass))

			a__       :						str							=  None
			for cls_name, cls in cls_members.items():
						if (
						    cls_name != DiffusionPipeline.__name__
						    and issubclass(cls						,       _lowercase)
						    and cls.__module__.split(""".""")[0] != "diffusers"
						):
									if pipeline_class is not None:
												raise ValueError(
												    F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:'''
												    F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in'''
												    F''' {loaded_module}.''')
									a__       :						str							=  cls

			return pipeline_class

def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike]						,       _lowercase    :       str						,       _lowercase    :       Optional[Union[str, os.PathLike]] = None						,       _lowercase    :       bool = False						,       _lowercase    :       bool = False						,       _lowercase    :       Optional[Dict[str, str]] = None						,       _lowercase    :       Optional[Union[bool, str]] = None						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       bool = False						,       )							->	Optional[int]:







			"""simple docstring"""
			a__       :						Union[str, Any]							=  str(_lowercase)

			a__       :						Union[str, Any]							=  os.path.join(_lowercase						,       _lowercase)

			if os.path.isfile(_lowercase):
						a__       :						Dict							=  module_file_or_url
						a__       :						List[str]							=  """local"""
			elif pretrained_model_name_or_path.count("""/""") == 0:
						a__       :						Optional[Any]							=  get_diffusers_versions()
						# cut ".dev0"
						a__       :						Union[str, Any]							=  """v""" + """.""".join(__version__.split(""".""")[:3])

						# retrieve github version that matches
						if revision is None:
									a__       :						List[str]							=  latest_version if latest_version[1:] in available_versions else """main"""
									logger.info(F'''Defaulting to latest_version: {revision}.''')
						elif revision in available_versions:
									a__       :						str							=  F'''v{revision}'''
						elif revision == "main":
									a__       :						List[str]							=  revision
						else:
									raise ValueError(
									    F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of'''
									    F''' {', '.join(available_versions + ['main'])}.''')

						# community pipeline on GitHub
						a__       :						Any							=  COMMUNITY_PIPELINES_URL.format(revision=_lowercase						,       pipeline=_lowercase)
						try:
									a__       :						Optional[int]							=  cached_download(
									    _lowercase						,       cache_dir=_lowercase						,       force_download=_lowercase						,       proxies=_lowercase						,       resume_download=_lowercase						,       local_files_only=_lowercase						,       use_auth_token=_lowercase						,       )
									a__       :						Any							=  """git"""
									a__       :						int							=  pretrained_model_name_or_path + """.py"""
						except EnvironmentError:
									logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''')
									raise
			else:
						try:
									# Load from URL or cache if already cached
									a__       :						Any							=  hf_hub_download(
									    _lowercase						,       _lowercase						,       cache_dir=_lowercase						,       force_download=_lowercase						,       proxies=_lowercase						,       resume_download=_lowercase						,       local_files_only=_lowercase						,       use_auth_token=_lowercase						,       )
									a__       :						Optional[Any]							=  os.path.join("""local"""						,       """--""".join(pretrained_model_name_or_path.split("""/""")))
						except EnvironmentError:
									logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''')
									raise

    # Check we have all the requirements in our environment
			a__       :						List[str]							=  check_imports(_lowercase)

			# Now we move the module inside our cached dynamic modules.
			a__       :						int							=  DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
			create_dynamic_module(_lowercase)
			a__       :						Tuple							=  Path(_lowercase) / full_submodule
			if submodule == "local" or submodule == "git":
						# We always copy local files (we could hash the file to see if there was a change, and give them the name of
						# that hash, to only copy when there is a modification but it seems overkill for now).
						# The only reason we do the copy is to avoid putting too many folders in sys.path.
						shutil.copy(_lowercase						,       submodule_path / module_file)
						for module_needed in modules_needed:
									a__       :						Dict							=  F'''{module_needed}.py'''
									shutil.copy(os.path.join(_lowercase						,       _lowercase)						,       submodule_path / module_needed)
			else:
						# Get the commit hash
						# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
						if isinstance(_lowercase						,       _lowercase):
									a__       :						Optional[Any]							=  use_auth_token
						elif use_auth_token is True:
									a__       :						Dict							=  HfFolder.get_token()
						else:
									a__       :						str							=  None

						a__       :						Any							=  model_info(_lowercase						,       revision=_lowercase						,       token=_lowercase).sha

						# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
						# benefit of versioning.
						a__       :						Optional[int]							=  submodule_path / commit_hash
						a__       :						Tuple							=  full_submodule + os.path.sep + commit_hash
						create_dynamic_module(_lowercase)

						if not (submodule_path / module_file).exists():
									shutil.copy(_lowercase						,       submodule_path / module_file)
						# Make sure we also have every file with relative
						for module_needed in modules_needed:
									if not (submodule_path / module_needed).exists():
												get_cached_module_file(
												    _lowercase						,       F'''{module_needed}.py'''						,       cache_dir=_lowercase						,       force_download=_lowercase						,       resume_download=_lowercase						,       proxies=_lowercase						,       use_auth_token=_lowercase						,       revision=_lowercase						,       local_files_only=_lowercase						,       )
			return os.path.join(_lowercase						,       _lowercase)





def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike]						,       _lowercase    :       str						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       Optional[Union[str, os.PathLike]] = None						,       _lowercase    :       bool = False						,       _lowercase    :       bool = False						,       _lowercase    :       Optional[Dict[str, str]] = None						,       _lowercase    :       Optional[Union[bool, str]] = None						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       bool = False						,       **_lowercase    :       Union[str, Any]						,       )							->	List[str]:







			"""simple docstring"""
			a__       :						int							=  get_cached_module_file(
			    _lowercase						,       _lowercase						,       cache_dir=_lowercase						,       force_download=_lowercase						,       resume_download=_lowercase						,       proxies=_lowercase						,       use_auth_token=_lowercase						,       revision=_lowercase						,       local_files_only=_lowercase						,       )
			return get_class_in_module(_lowercase						,       final_module.replace(""".py"""						,       """"""))




