

'''simple docstring'''




import math

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase         =						logging.get_logger(__name__)

_lowerCAmelCase         =						{
    "facebook/data2vec-base-960h": "https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json",
    # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio
}






class   _SCREAMING_SNAKE_CASE   (   __a     ):
 __SCREAMING_SNAKE_CASE					:Optional[Any]      	=					"""data2vec-audio"""



 def __init__(   self		:   Optional[int]			,				a__		:   int=32			,				a__		:   str=768			,				a__		:   Any=12			,				a__		:   List[Any]=12			,				a__		:   Optional[Any]=3072			,				a__		:   Optional[Any]="gelu"			,				a__		:   int=0.1			,				a__		:   Optional[Any]=0.1			,				a__		:   Any=0.1			,				a__		:   Any=0.0			,				a__		:   Union[str, Any]=0.1			,				a__		:   Dict=0.1			,				a__		:   List[Any]=0.02			,				a__		:   Dict=1E-5			,				a__		:   Tuple="gelu"			,				a__		:   str=(512, 512, 512, 512, 512, 512, 512)			,				a__		:   List[str]=(5, 2, 2, 2, 2, 2, 2)			,				a__		:   Any=(10, 3, 3, 3, 3, 2, 2)			,				a__		:   Optional[int]=False			,				a__		:   Union[str, Any]=16			,				a__		:   List[str]=19			,				a__		:   Optional[Any]=5			,				a__		:   int=0.05			,				a__		:   List[Any]=10			,				a__		:   Optional[int]=2			,				a__		:   Optional[Any]=0.0			,				a__		:   List[Any]=10			,				a__		:   str=0			,				a__		:   Any="sum"			,				a__		:   List[str]=False			,				a__		:   int=False			,				a__		:   Any=256			,				a__		:   List[str]=(512, 512, 512, 512, 1500)			,				a__		:   Union[str, Any]=(5, 3, 3, 1, 1)			,				a__		:   Union[str, Any]=(1, 2, 3, 1, 1)			,				a__		:   Tuple=512			,				a__		:   Optional[Any]=0			,				a__		:   Optional[int]=1			,				a__		:   Dict=2			,				a__		:   Any=False			,				a__		:   List[Any]=3			,				a__		:   Optional[int]=2			,				a__		:   List[Any]=3			,				a__		:   int=None			,				**a__		:   List[str]			,				):
      super().__init__(**a__			,				pad_token_id=a__			,				bos_token_id=a__			,				eos_token_id=a__      )
      __magic_name__						       =    hidden_size
      __magic_name__						       =    feat_extract_activation
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    conv_bias
      __magic_name__						       =    num_conv_pos_embeddings
      __magic_name__						       =    num_conv_pos_embedding_groups
      __magic_name__						       =    conv_pos_kernel_size
      __magic_name__						       =    len(self.conv_dim      )
      __magic_name__						       =    num_hidden_layers
      __magic_name__						       =    intermediate_size
      __magic_name__						       =    hidden_act
      __magic_name__						       =    num_attention_heads
      __magic_name__						       =    hidden_dropout
      __magic_name__						       =    attention_dropout
      __magic_name__						       =    activation_dropout
      __magic_name__						       =    feat_proj_dropout
      __magic_name__						       =    final_dropout
      __magic_name__						       =    layerdrop
      __magic_name__						       =    layer_norm_eps
      __magic_name__						       =    initializer_range
      __magic_name__						       =    vocab_size
      __magic_name__						       =    use_weighted_layer_sum

      if (
          (len(self.conv_stride      ) != self.num_feat_extract_layers)
          or (len(self.conv_kernel      ) != self.num_feat_extract_layers)
          or (len(self.conv_dim      ) != self.num_feat_extract_layers)
      ):
           raise ValueError(
               '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='''
               ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='''
               F''' {len(self.conv_dim      )}`, `len(config.conv_stride) = {len(self.conv_stride      )}`,'''
               F''' `len(config.conv_kernel) = {len(self.conv_kernel      )}`.'''      )

      # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
      __magic_name__						       =    mask_time_prob
      __magic_name__						       =    mask_time_length
      __magic_name__						       =    mask_time_min_masks
      __magic_name__						       =    mask_feature_prob
      __magic_name__						       =    mask_feature_length
      __magic_name__						       =    mask_feature_min_masks

      # ctc loss
      __magic_name__						       =    ctc_loss_reduction
      __magic_name__						       =    ctc_zero_infinity

      # adapter
      __magic_name__						       =    add_adapter
      __magic_name__						       =    adapter_kernel_size
      __magic_name__						       =    adapter_stride
      __magic_name__						       =    num_adapter_layers
      __magic_name__						       =    output_hidden_size or hidden_size

      # SequenceClassification-specific parameter. Feel free to ignore for other classes.
      __magic_name__						       =    classifier_proj_size

      # XVector-specific parameters. Feel free to ignore for other classes.
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    list(a__      )
      __magic_name__						       =    xvector_output_dim



 @property
 def 			snake_case__  (   self		:   Optional[int]      ):
      return math.prod(self.conv_stride      )









'''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


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


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




def 						UpperCamelCase	(			)				->     Optional[Any]:






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




def 						UpperCamelCase	(			)				->     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(a			)
     os.makedirs(a		,						exist_ok=a			)
     __magic_name__						       =    Path(a			) / '''__init__.py'''
     if not init_path.exists():
          init_path.touch()




def 						UpperCamelCase	(			a			)				->     Tuple:






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




def 						UpperCamelCase	(			a			)				->     List[str]:






     '''simple docstring'''
     with open(a		,						'''r'''		,						encoding='''utf-8'''			) as f:
          __magic_name__						       =    f.read()

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




def 						UpperCamelCase	(			a			)				->     str:






     '''simple docstring'''
     __magic_name__						       =    False
     __magic_name__						       =    [module_file]
     __magic_name__						       =    []

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

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

          __magic_name__						       =    len(a			) == 0
          all_relative_imports.extend(a			)

     return all_relative_imports




def 						UpperCamelCase	(			a			)				->     List[str]:






     '''simple docstring'''
     with open(a		,						'''r'''		,						encoding='''utf-8'''			) as f:
          __magic_name__						       =    f.read()

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

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

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

     return get_relative_imports(a			)




def 						UpperCamelCase	(			a		,						a			)				->     Optional[int]:






     '''simple docstring'''
     __magic_name__						       =    module_path.replace(os.path.sep		,						'''.'''			)
     __magic_name__						       =    importlib.import_module(a			)

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




def 						UpperCamelCase	(			a			)				->     Tuple:






     '''simple docstring'''
     from ..pipelines import DiffusionPipeline

     __magic_name__						       =    dict(inspect.getmembers(a		,						inspect.isclass			)			)

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

     return pipeline_class




def 						UpperCamelCase	(			a		,						a		,						a = None		,						a = False		,						a = False		,						a = None		,						a = None		,						a = None		,						a = False		,						)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    str(a			)

     __magic_name__						       =    os.path.join(a		,						a			)

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

          # retrieve github version that matches
          if revision is None:
               __magic_name__						       =    latest_version if latest_version[1:] in available_versions else '''main'''
               logger.info(F'''Defaulting to latest_version: {revision}.'''			)
          elif revision in available_versions:
               __magic_name__						       =    F'''v{revision}'''
          elif revision == "main":
               __magic_name__						       =    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
          __magic_name__						       =    COMMUNITY_PIPELINES_URL.format(revision=a		,						pipeline=a			)
          try:
               __magic_name__						       =    cached_download(
                   a		,						cache_dir=a		,						force_download=a		,						proxies=a		,						resume_download=a		,						local_files_only=a		,						use_auth_token=a		,						)
               __magic_name__						       =    '''git'''
               __magic_name__						       =    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
               __magic_name__						       =    hf_hub_download(
                   a		,						a		,						cache_dir=a		,						force_download=a		,						proxies=a		,						resume_download=a		,						local_files_only=a		,						use_auth_token=a		,						)
               __magic_name__						       =    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
     __magic_name__						       =    check_imports(a			)

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

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

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




def 						UpperCamelCase	(			a		,						a		,						a = None		,						a = None		,						a = False		,						a = False		,						a = None		,						a = None		,						a = None		,						a = False		,						**a		,						)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    get_cached_module_file(
         a		,						a		,						cache_dir=a		,						force_download=a		,						resume_download=a		,						proxies=a		,						use_auth_token=a		,						revision=a		,						local_files_only=a		,						)
     return get_class_in_module(a		,						final_module.replace('''.py'''		,						''''''			)			)






