






"""simple docstring"""


import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
       from transformers import WhisperFeatureExtractor

if is_torch_available():
       import torch

lowercase_				     =     random.Random()



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=1.0		,       __UpperCamelCase=None		,       __UpperCamelCase=None ):




  """simple docstring"""







  if rng is None:
    __A									= global_rng

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

  return values


@require_torch
@require_torchaudio
class 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def __init__(	self :     Dict,       _lowerCamelCase :     Union[str, Any],       _lowerCamelCase :     str=7,       _lowerCamelCase :     Dict=4_00,       _lowerCamelCase :     Tuple=20_00,       _lowerCamelCase :     Any=10,       _lowerCamelCase :     Union[str, Any]=1_60,       _lowerCamelCase :     Tuple=8,       _lowerCamelCase :     Optional[int]=0.0,       _lowerCamelCase :     Optional[Any]=40_00,       _lowerCamelCase :     List[Any]=False,       _lowerCamelCase :     Any=True,       ):

     '''simple docstring'''
     __A									= parent
     __A									= batch_size
     __A									= min_seq_length
     __A									= max_seq_length
     __A									= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __A									= padding_value
     __A									= sampling_rate
     __A									= return_attention_mask
     __A									= do_normalize
     __A									= feature_size
     __A									= chunk_length
     __A									= hop_length


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     return {
         "feature_size": self.feature_size,
         "hop_length": self.hop_length,
         "chunk_length": self.chunk_length,
         "padding_value": self.padding_value,
         "sampling_rate": self.sampling_rate,
         "return_attention_mask": self.return_attention_mask,
         "do_normalize": self.do_normalize,
     }






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

     '''simple docstring'''
     def _flatten(_lowerCamelCase :     Any  ):
       return list(itertools.chain(*_lowerCamelCase  )  )

     if equal_length:
       __A									= [floats_list((self.max_seq_length, self.feature_size)  ) for _ in range(self.batch_size  )]
     else:
       # make sure that inputs increase in size
       __A									= [
           floats_list((x, self.feature_size)  )
           for x in range(self.min_seq_length,       self.max_seq_length,       self.seq_length_diff  )
       ]
     if numpify:
       __A									= [np.asarray(_lowerCamelCase  ) for x in speech_inputs]
     return speech_inputs





@require_torch
@require_torchaudio
class 					snake_case		(							_lowerCAmelCase   ,	unittest.TestCase						):


   '''simple docstring'''

   A_						:	List[Any]						 = WhisperFeatureExtractor if is_speech_available() else None


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= WhisperFeatureExtractionTester(self  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Any  ):

     '''simple docstring'''
     __A									= self.feature_extraction_class(**self.feat_extract_dict  )

     with tempfile.TemporaryDirectory() as tmpdirname:
       __A									= feat_extract_first.save_pretrained(_lowerCamelCase  )[0]
       check_json_file_has_correct_format(_lowerCamelCase  )
       __A									= self.feature_extraction_class.from_pretrained(_lowerCamelCase  )

     __A									= feat_extract_first.to_dict()
     __A									= feat_extract_second.to_dict()
     __A									= feat_extract_first.mel_filters
     __A									= feat_extract_second.mel_filters
     self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase  )  )
     self.assertEqual(_lowerCamelCase,       _lowerCamelCase  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Any  ):

     '''simple docstring'''
     __A									= self.feature_extraction_class(**self.feat_extract_dict  )

     with tempfile.TemporaryDirectory() as tmpdirname:
       __A									= os.path.join(_lowerCamelCase,       '''feat_extract.json'''  )
       feat_extract_first.to_json_file(_lowerCamelCase  )
       __A									= self.feature_extraction_class.from_json_file(_lowerCamelCase  )

     __A									= feat_extract_first.to_dict()
     __A									= feat_extract_second.to_dict()
     __A									= feat_extract_first.mel_filters
     __A									= feat_extract_second.mel_filters
     self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase  )  )
     self.assertEqual(_lowerCamelCase,       _lowerCamelCase  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     # Tests that all call wrap to encode_plus and batch_encode_plus
     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     # create three inputs of length 800, 1000, and 1200
     __A									= [floats_list((1, x)  )[0] for x in range(8_00,       14_00,       2_00  )]
     __A									= [np.asarray(_lowerCamelCase  ) for speech_input in speech_inputs]

     # Test feature size
     __A									= feature_extractor(_lowerCamelCase,       padding='''max_length''',       return_tensors='''np'''  ).input_features
     self.assertTrue(input_features.ndim == 3  )
     self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames  )
     self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size  )

     # Test not batched input
     __A									= feature_extractor(speech_inputs[0],       return_tensors='''np'''  ).input_features
     __A									= feature_extractor(np_speech_inputs[0],       return_tensors='''np'''  ).input_features
     self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test batched
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test 2-D numpy arrays are batched.
     __A									= [floats_list((1, x)  )[0] for x in (8_00, 8_00, 8_00)]
     __A									= np.asarray(_lowerCamelCase  )
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test truncation required
     __A									= [floats_list((1, x)  )[0] for x in range(2_00,       (feature_extractor.n_samples + 5_00),       2_00  )]
     __A									= [np.asarray(_lowerCamelCase  ) for speech_input in speech_inputs]

     __A									= [x[: feature_extractor.n_samples] for x in speech_inputs]
     __A									= [np.asarray(_lowerCamelCase  ) for speech_input in speech_inputs_truncated]

     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''np'''  ).input_features
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     import torch

     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A									= np.random.rand(1_00,       32  ).astype(np.floataa  )
     __A									= np_speech_inputs.tolist()

     for inputs in [py_speech_inputs, np_speech_inputs]:
       __A									= feature_extractor.pad([{'''input_features''': inputs}],       return_tensors='''np'''  )
       self.assertTrue(np_processed.input_features.dtype == np.floataa  )
       __A									= feature_extractor.pad([{'''input_features''': inputs}],       return_tensors='''pt'''  )
       self.assertTrue(pt_processed.input_features.dtype == torch.floataa  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any],       _lowerCamelCase :     Dict  ):

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

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


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     # fmt: off
     __A									= torch.tensor(
         [
             0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51,
             0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78,
             0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54,
             -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54
         ]  )
     # fmt: on

     __A									= self._load_datasamples(1  )
     __A									= WhisperFeatureExtractor()
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''pt'''  ).input_features
     self.assertEqual(input_features.shape,       (1, 80, 30_00)  )
     self.assertTrue(torch.allclose(input_features[0, 0, :30],       _lowerCamelCase,       atol=1e-4  )  )






   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A									= self._load_datasamples(1  )[0]
     __A									= ((audio - audio.min()) / (audio.max() - audio.min())) * 6_55_35  # Rescale to [0, 65535] to show issue
     __A									= feat_extract.zero_mean_unit_var_norm([audio],       attention_mask=_lowerCamelCase  )[0]

     self.assertTrue(np.all(np.mean(_lowerCamelCase  ) < 1e-3  )  )
     self.assertTrue(np.all(np.abs(np.var(_lowerCamelCase  ) - 1  ) < 1e-3  )  )












"""simple docstring"""


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_				     =     (
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


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



def 					lowerCAmelCase				(    ):




  """simple docstring"""







  __A									= '''https://pypi.org/pypi/diffusers/json'''
  __A									= json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys()
  return sorted(__UpperCamelCase		,       key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) )



def 					lowerCAmelCase				(    ):




  """simple docstring"""







  if HF_MODULES_CACHE in sys.path:
    return

  sys.path.append(__UpperCamelCase )
  os.makedirs(__UpperCamelCase		,       exist_ok=__UpperCamelCase )
  __A									= Path(__UpperCamelCase ) / '''__init__.py'''
  if not init_path.exists():
    init_path.touch()



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  init_hf_modules()
  __A									= Path(__UpperCamelCase ) / 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(__UpperCamelCase		,       exist_ok=__UpperCamelCase )
  __A									= dynamic_module_path / '''__init__.py'''
  if not init_path.exists():
    init_path.touch()



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

  # Imports of the form `import .xxx`
  __A									= re.findall('''^\s*import\s+\.(\S+)\s*$'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Imports of the form `from .xxx import yyy`
  relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''		,       __UpperCamelCase		,       flags=re.MULTILINE )
  # Unique-ify
  return list(set(__UpperCamelCase ) )



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  __A									= False
  __A									= [module_file]
  __A									= []

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

    __A									= Path(__UpperCamelCase ).parent
    __A									= [str(module_path / m ) for m in new_imports]
    __A									= [f for f in new_import_files if f not in all_relative_imports]
    __A									= [f'{f}.py' for f in new_import_files]

    __A									= len(__UpperCamelCase ) == 0
    all_relative_imports.extend(__UpperCamelCase )

  return all_relative_imports



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

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

  # Unique-ify and test we got them all
  __A									= list(set(__UpperCamelCase ) )
  __A									= []
  for imp in imports:
    try:
      importlib.import_module(__UpperCamelCase )
    except ImportError:
      missing_packages.append(__UpperCamelCase )

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

  return get_relative_imports(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







  __A									= module_path.replace(os.path.sep		,       '''.''' )
  __A									= importlib.import_module(__UpperCamelCase )

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



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  from ..pipelines import DiffusionPipeline

  __A									= dict(inspect.getmembers(__UpperCamelCase		,       inspect.isclass ) )

  __A									= None
  for cls_name, cls in cls_members.items():
    if (
        cls_name != DiffusionPipeline.__name__
        and issubclass(cls		,       __UpperCamelCase )
        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									= cls

  return pipeline_class



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       ):




  """simple docstring"""







  __A									= str(__UpperCamelCase )

  __A									= os.path.join(__UpperCamelCase		,       __UpperCamelCase )

  if os.path.isfile(__UpperCamelCase ):
    __A									= module_file_or_url
    __A									= '''local'''
  elif pretrained_model_name_or_path.count('''/''' ) == 0:
    __A									= get_diffusers_versions()
    # cut ".dev0"
    __A									= '''v''' + '''.'''.join(__version__.split('''.''' )[:3] )

    # retrieve github version that matches
    if revision is None:
      __A									= 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									= f'v{revision}'
    elif revision == "main":
      __A									= 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									= COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase		,       pipeline=__UpperCamelCase )
    try:
      __A									= cached_download(
          __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= '''git'''
      __A									= 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									= hf_hub_download(
          __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= 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									= check_imports(__UpperCamelCase )

  # Now we move the module inside our cached dynamic modules.
  __A									= DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
  create_dynamic_module(__UpperCamelCase )
  __A									= Path(__UpperCamelCase ) / 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(__UpperCamelCase		,       submodule_path / module_file )
    for module_needed in modules_needed:
      __A									= f'{module_needed}.py'
      shutil.copy(os.path.join(__UpperCamelCase		,       __UpperCamelCase )		,       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(__UpperCamelCase		,       __UpperCamelCase ):
      __A									= use_auth_token
    elif use_auth_token is True:
      __A									= HfFolder.get_token()
    else:
      __A									= None

    __A									= model_info(__UpperCamelCase		,       revision=__UpperCamelCase		,       token=__UpperCamelCase ).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									= submodule_path / commit_hash
    __A									= full_submodule + os.path.sep + commit_hash
    create_dynamic_module(__UpperCamelCase )

    if not (submodule_path / module_file).exists():
      shutil.copy(__UpperCamelCase		,       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(
            __UpperCamelCase		,       f'{module_needed}.py'		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return os.path.join(__UpperCamelCase		,       __UpperCamelCase )





def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       **__UpperCamelCase		,       ):




  """simple docstring"""







  __A									= get_cached_module_file(
      __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return get_class_in_module(__UpperCamelCase		,       final_module.replace('''.py'''		,       '''''' ) )




