
'''simple docstring'''







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


_snake_case				:   List[Any]     =				logging.get_logger(__name__)

_snake_case				:   Dict     =				{
    """microsoft/cvt-13""": """https://huggingface.co/microsoft/cvt-13/resolve/main/config.json""",
    # See all Cvt models at https://huggingface.co/models?filter=cvt
}


class 			lowerCAmelCase (				__UpperCAmelCase			):
		a							:					List[str]       =					"""cvt"""




		def __init__(				self					,						UpperCamelCase=3					,						UpperCamelCase=[7, 3, 3]					,						UpperCamelCase=[4, 2, 2]					,						UpperCamelCase=[2, 1, 1]					,						UpperCamelCase=[64, 192, 384]					,						UpperCamelCase=[1, 3, 6]					,						UpperCamelCase=[1, 2, 10]					,						UpperCamelCase=[4.0, 4.0, 4.0]					,						UpperCamelCase=[0.0, 0.0, 0.0]					,						UpperCamelCase=[0.0, 0.0, 0.0]					,						UpperCamelCase=[0.0, 0.0, 0.1]					,						UpperCamelCase=[True, True, True]					,						UpperCamelCase=[False, False, True]					,						UpperCamelCase=["dw_bn", "dw_bn", "dw_bn"]					,						UpperCamelCase=[3, 3, 3]					,						UpperCamelCase=[1, 1, 1]					,						UpperCamelCase=[2, 2, 2]					,						UpperCamelCase=[1, 1, 1]					,						UpperCamelCase=[1, 1, 1]					,						UpperCamelCase=0.02					,						UpperCamelCase=1e-12					,						**UpperCamelCase					,						):
								super().__init__(**UpperCamelCase      )
								_SCREAMING_SNAKE_CASE				= num_channels
								_SCREAMING_SNAKE_CASE				= patch_sizes
								_SCREAMING_SNAKE_CASE				= patch_stride
								_SCREAMING_SNAKE_CASE				= patch_padding
								_SCREAMING_SNAKE_CASE				= embed_dim
								_SCREAMING_SNAKE_CASE				= num_heads
								_SCREAMING_SNAKE_CASE				= depth
								_SCREAMING_SNAKE_CASE				= mlp_ratio
								_SCREAMING_SNAKE_CASE				= attention_drop_rate
								_SCREAMING_SNAKE_CASE				= drop_rate
								_SCREAMING_SNAKE_CASE				= drop_path_rate
								_SCREAMING_SNAKE_CASE				= qkv_bias
								_SCREAMING_SNAKE_CASE				= cls_token
								_SCREAMING_SNAKE_CASE				= qkv_projection_method
								_SCREAMING_SNAKE_CASE				= kernel_qkv
								_SCREAMING_SNAKE_CASE				= padding_kv
								_SCREAMING_SNAKE_CASE				= stride_kv
								_SCREAMING_SNAKE_CASE				= padding_q
								_SCREAMING_SNAKE_CASE				= stride_q
								_SCREAMING_SNAKE_CASE				= initializer_range
								_SCREAMING_SNAKE_CASE				= layer_norm_eps

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


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


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



def 			_a		(	):
						_SCREAMING_SNAKE_CASE				= "https://pypi.org/pypi/diffusers/json"
						_SCREAMING_SNAKE_CASE				= json.loads(request.urlopen(_SCREAMING_SNAKE_CASE  ).read()  )["releases"].keys()
						return sorted(_SCREAMING_SNAKE_CASE	,			key=lambda _SCREAMING_SNAKE_CASE  : version.Version(_SCREAMING_SNAKE_CASE  )  )



def 			_a		(	):
						# 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(_SCREAMING_SNAKE_CASE  )
						os.makedirs(_SCREAMING_SNAKE_CASE	,			exist_ok=_SCREAMING_SNAKE_CASE  )
						_SCREAMING_SNAKE_CASE				= Path(_SCREAMING_SNAKE_CASE  ) / "__init__.py"
						if not init_path.exists():
												init_path.touch()



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Union[str, os.PathLike]  ):
						init_hf_modules()
						_SCREAMING_SNAKE_CASE				= Path(_SCREAMING_SNAKE_CASE  ) / 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(_SCREAMING_SNAKE_CASE	,			exist_ok=_SCREAMING_SNAKE_CASE  )
						_SCREAMING_SNAKE_CASE				= dynamic_module_path / "__init__.py"
						if not init_path.exists():
												init_path.touch()



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Optional[Any]  ):
						with open(_SCREAMING_SNAKE_CASE	,			"r"	,			encoding="utf-8"  ) as f:
												_SCREAMING_SNAKE_CASE				= f.read()

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



def 			_a		(	_SCREAMING_SNAKE_CASE		:   List[str]  ):
						_SCREAMING_SNAKE_CASE				= False
						_SCREAMING_SNAKE_CASE				= [module_file]
						_SCREAMING_SNAKE_CASE				= []

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

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

												_SCREAMING_SNAKE_CASE				= len(_SCREAMING_SNAKE_CASE  ) == 0
												all_relative_imports.extend(_SCREAMING_SNAKE_CASE  )

						return all_relative_imports



def 			_a		(	_SCREAMING_SNAKE_CASE		:   str  ):
						with open(_SCREAMING_SNAKE_CASE	,			"r"	,			encoding="utf-8"  ) as f:
												_SCREAMING_SNAKE_CASE				= f.read()

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

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

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

						return get_relative_imports(_SCREAMING_SNAKE_CASE  )



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Union[str, Any]	,			_SCREAMING_SNAKE_CASE		:   int  ):
						_SCREAMING_SNAKE_CASE				= module_path.replace(os.path.sep	,			"."  )
						_SCREAMING_SNAKE_CASE				= importlib.import_module(_SCREAMING_SNAKE_CASE  )

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



def 			_a		(	_SCREAMING_SNAKE_CASE		:   List[Any]  ):
						from ..pipelines import DiffusionPipeline

						_SCREAMING_SNAKE_CASE				= dict(inspect.getmembers(_SCREAMING_SNAKE_CASE	,			inspect.isclass  )  )

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

						return pipeline_class



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Union[str, os.PathLike]	,			_SCREAMING_SNAKE_CASE		:   str	,			_SCREAMING_SNAKE_CASE		:   Optional[Union[str, os.PathLike]] = None	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			_SCREAMING_SNAKE_CASE		:   Optional[Dict[str, str]] = None	,			_SCREAMING_SNAKE_CASE		:   Optional[Union[bool, str]] = None	,			_SCREAMING_SNAKE_CASE		:   Optional[str] = None	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			):
						_SCREAMING_SNAKE_CASE				= str(_SCREAMING_SNAKE_CASE  )

						_SCREAMING_SNAKE_CASE				= os.path.join(_SCREAMING_SNAKE_CASE	,			_SCREAMING_SNAKE_CASE  )

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

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

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

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

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




def 			_a		(	_SCREAMING_SNAKE_CASE		:   Union[str, os.PathLike]	,			_SCREAMING_SNAKE_CASE		:   str	,			_SCREAMING_SNAKE_CASE		:   Optional[str] = None	,			_SCREAMING_SNAKE_CASE		:   Optional[Union[str, os.PathLike]] = None	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			_SCREAMING_SNAKE_CASE		:   Optional[Dict[str, str]] = None	,			_SCREAMING_SNAKE_CASE		:   Optional[Union[bool, str]] = None	,			_SCREAMING_SNAKE_CASE		:   Optional[str] = None	,			_SCREAMING_SNAKE_CASE		:   bool = False	,			**_SCREAMING_SNAKE_CASE		:   Tuple	,			):
						_SCREAMING_SNAKE_CASE				= get_cached_module_file(
						    _SCREAMING_SNAKE_CASE	,			_SCREAMING_SNAKE_CASE	,			cache_dir=_SCREAMING_SNAKE_CASE	,			force_download=_SCREAMING_SNAKE_CASE	,			resume_download=_SCREAMING_SNAKE_CASE	,			proxies=_SCREAMING_SNAKE_CASE	,			use_auth_token=_SCREAMING_SNAKE_CASE	,			revision=_SCREAMING_SNAKE_CASE	,			local_files_only=_SCREAMING_SNAKE_CASE	,			)
						return get_class_in_module(_SCREAMING_SNAKE_CASE	,			final_module.replace(".py"	,			""  )  )