

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


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


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

def 						UpperCamelCase					()     ->      Optional[int]:
	A__							:    List[str]        =		"""https://pypi.org/pypi/diffusers/json"""
	A__							:    Union[str, Any]        =		json.loads(request.urlopen(_A					).read()					)["""releases"""].keys()
	return sorted(_A    ,      key=lambda lowercase_					: version.Version(_A					)					)

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





	if HF_MODULES_CACHE in sys.path:
		return

	sys.path.append(_A					)
	os.makedirs(_A    ,      exist_ok=_A					)
	A__							:    str        =		Path(_A					) / """__init__.py"""
	if not init_path.exists():
		init_path.touch()

def 						UpperCamelCase					(lowercase_: List[str]					)     ->      Tuple:
	init_hf_modules()
	A__							:    Union[str, Any]        =		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					)
	A__							:    Optional[Any]        =		dynamic_module_path / """__init__.py"""
	if not init_path.exists():
		init_path.touch()

def 						UpperCamelCase					(lowercase_: int					)     ->      Any:





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

	# Imports of the form `import .xxx`
	A__							:    Dict        =		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					(lowercase_: Union[str, Any]					)     ->      Optional[Any]:
	A__							:    Tuple        =		False
	A__							:    List[str]        =		[module_file]
	A__							:    Union[str, 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(_A					)					)

		A__							:    Optional[Any]        =		Path(_A					).parent
		A__							:    Optional[int]        =		[str(module_path / m					) for m in new_imports]
		A__							:    List[str]        =		[f for f in new_import_files if f not in all_relative_imports]
		A__							:    Tuple        =		[f"""{f}.py""" for f in new_import_files]

		A__							:    Optional[int]        =		len(_A					) == 0
		all_relative_imports.extend(_A					)

	return all_relative_imports

def 						UpperCamelCase					(lowercase_: List[str]					)     ->      Optional[Any]:





	with open(_A    ,      """r"""    ,      encoding="""utf-8"""					) as f:
		A__							:    int        =		f.read()

	# Imports of the form `import xxx`
	A__							:    Optional[Any]        =		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
	A__							:    List[Any]        =		[imp.split("""."""					)[0] for imp in imports if not imp.startswith("""."""					)]

	# Unique-ify and test we got them all
	A__							:    Optional[int]        =		list(set(_A					)					)
	A__							:    Optional[Any]        =		[]
	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					(lowercase_: int    ,      lowercase_: int					)     ->      Optional[int]:
	A__							:    int        =		module_path.replace(os.path.sep    ,      """."""					)
	A__							:    Any        =		importlib.import_module(_A					)

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

def 						UpperCamelCase					(lowercase_: List[Any]					)     ->      List[Any]:
	from ..pipelines import DiffusionPipeline

	A__							:    Any        =		dict(inspect.getmembers(_A    ,      inspect.isclass					)					)

	A__							:    Optional[int]        =		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}."""					)
			A__							:    List[str]        =		cls

	return pipeline_class

def 						UpperCamelCase					(lowercase_: str    ,      lowercase_: str    ,      lowercase_: List[str] = None    ,      lowercase_: Union[str, Any] = False    ,      lowercase_: Tuple = False    ,      lowercase_: List[Any] = None    ,      lowercase_: Optional[int] = None    ,      lowercase_: Tuple = None    ,      lowercase_: str = False    ,      )     ->      List[Any]:
	A__							:    Dict        =		str(_A					)

	A__							:    Dict        =		os.path.join(_A    ,      _A					)

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

		# retrieve github version that matches
		if revision is None:
			A__							:    Dict        =		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__							:    List[str]        =		f"""v{revision}"""
		elif revision == "main":
			A__							:    Union[str, Any]        =		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__							:    List[Any]        =		COMMUNITY_PIPELINES_URL.format(revision=_A    ,      pipeline=_A					)
		try:
			A__							:    Tuple        =		cached_download(
			    _A    ,      cache_dir=_A    ,      force_download=_A    ,      proxies=_A    ,      resume_download=_A    ,      local_files_only=_A    ,      use_auth_token=_A    ,      )
			A__							:    int        =		"""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__							:    int        =		hf_hub_download(
			    _A    ,      _A    ,      cache_dir=_A    ,      force_download=_A    ,      proxies=_A    ,      resume_download=_A    ,      local_files_only=_A    ,      use_auth_token=_A    ,      )
			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[Any]        =		check_imports(_A					)

	# Now we move the module inside our cached dynamic modules.
	A__							:    str        =		DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
	create_dynamic_module(_A					)
	A__							:    Dict        =		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:
			A__							:    Tuple        =		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					):
			A__							:    str        =		use_auth_token
		elif use_auth_token is True:
			A__							:    Optional[Any]        =		HfFolder.get_token()
		else:
			A__							:    Optional[Any]        =		None

		A__							:    List[Any]        =		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.
		A__							:    int        =		submodule_path / commit_hash
		A__							:    Any        =		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					(lowercase_: Optional[Any]    ,      lowercase_: List[str]    ,      lowercase_: Union[str, Any] = None    ,      lowercase_: Optional[Any] = None    ,      lowercase_: Dict = False    ,      lowercase_: Any = False    ,      lowercase_: Optional[int] = None    ,      lowercase_: Dict = None    ,      lowercase_: Union[str, Any] = None    ,      lowercase_: Any = False    ,      **lowercase_: Union[str, Any]    ,      )     ->      Optional[int]:
	A__							:    Optional[int]        =		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"""    ,      """"""					)					)









import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


lowercase__				:     str 		=						NewType("DataClass", Any)
lowercase__				:     Union[str, Any] 		=						NewType("DataClassType", Any)


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	if isinstance(_A     ,	_A							):
		return v
	if v.lower() in ("yes", "true", "t", "y", "1"):
		return True
	elif v.lower() in ("no", "false", "f", "n", "0"):
		return False
	else:
		raise ArgumentTypeError(
		    f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."							)


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     {str(_A							): choice for choice in choices}
	return lambda _A							: str_to_choice.get(_A     ,	_A							)


def 						lowerCamelCase__    (		*,
    _A = None     ,	_A = None     ,	_A = dataclasses.MISSING     ,	_A = dataclasses.MISSING     ,	_A = None     ,	**_A     ,	):







	'''simple docstring'''





	if metadata is None:
		# Important, don't use as default param in function signature because dict is mutable and shared across function calls
		snake_case_		    =     {}
	if aliases is not None:
		snake_case_		    =     aliases
	if help is not None:
		snake_case_		    =     help

	return dataclasses.field(metadata=_A     ,	default=_A     ,	default_factory=_A     ,	**_A							)






class 		UpperCAmelCase   (				UpperCAmelCase__			):







						'''simple docstring'''





						lowerCAmelCase_     		=   42






						def __init__(						self							:     Optional[Any]       ,	__lowercase							:     Union[DataClassType, Iterable[DataClassType]]       ,	**__lowercase							:     Optional[int]						):






							"""simple docstring"""






							if "formatter_class" not in kwargs:
								snake_case_		    =     ArgumentDefaultsHelpFormatter
							super().__init__(**__lowercase						)
							if dataclasses.is_dataclass(__lowercase						):
								snake_case_		    =     [dataclass_types]
							snake_case_		    =     list(__lowercase						)
							for dtype in self.dataclass_types:
								self._add_dataclass_arguments(__lowercase						)






						@staticmethod
						def        snake_case__						(						__lowercase							:     ArgumentParser       ,	__lowercase							:     dataclasses.Field						):






							"""simple docstring"""






							snake_case_		    =     f"--{field.name}"
							snake_case_		    =     field.metadata.copy()
							# field.metadata is not used at all by Data Classes,
							# it is provided as a third-party extension mechanism.
							if isinstance(field.type       ,	__lowercase						):
								raise RuntimeError(
								    "Unresolved type detected, which should have been done with the help of "
								    "`typing.get_type_hints` method by default"						)

							snake_case_		    =     kwargs.pop("aliases"       ,	[]						)
							if isinstance(__lowercase       ,	__lowercase						):
								snake_case_		    =     [aliases]

							snake_case_		    =     getattr(field.type       ,	"__origin__"       ,	field.type						)
							if origin_type is Union or (hasattr(__lowercase       ,	"UnionType"						) and isinstance(__lowercase       ,	types.UnionType						)):
								if str not in field.type.__args__ and (
								    len(field.type.__args__						) != 2 or type(__lowercase						) not in field.type.__args__
								):
									raise ValueError(
									    "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
									    " the argument parser only supports one type per argument."
									    f" Problem encountered in field '{field.name}'."						)
								if type(__lowercase						) not in field.type.__args__:
									# filter `str` in Union
									snake_case_		    =     field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
									snake_case_		    =     getattr(field.type       ,	"__origin__"       ,	field.type						)
								elif bool not in field.type.__args__:
									# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
									snake_case_		    =     (
									    field.type.__args__[0] if isinstance(__lowercase       ,	field.type.__args__[1]						) else field.type.__args__[1]
									)
									snake_case_		    =     getattr(field.type       ,	"__origin__"       ,	field.type						)

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
							snake_case_		    =     {}
							if origin_type is Literal or (isinstance(field.type       ,	__lowercase						) and issubclass(field.type       ,	__lowercase						)):
								if origin_type is Literal:
									snake_case_		    =     field.type.__args__
								else:
									snake_case_		    =     [x.value for x in field.type]

								snake_case_		    =     make_choice_type_function(kwargs["choices"]						)

								if field.default is not dataclasses.MISSING:
									snake_case_		    =     field.default
								else:
									snake_case_		    =     True
							elif field.type is bool or field.type == Optional[bool]:
								# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
								# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
								snake_case_		    =     copy(__lowercase						)

								# Hack because type=bool in argparse does not behave as we want.
								snake_case_		    =     string_to_bool
								if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
									# Default value is False if we have no default when of type bool.
									snake_case_		    =     False if field.default is dataclasses.MISSING else field.default
									# This is the value that will get picked if we don't include --field_name in any way
									snake_case_		    =     default
									# This tells argparse we accept 0 or 1 value after --field_name
									snake_case_		    =     "?"
									# This is the value that will get picked if we do --field_name (without value)
									snake_case_		    =     True
							elif isclass(__lowercase						) and issubclass(__lowercase       ,	__lowercase						):
								snake_case_		    =     field.type.__args__[0]
								snake_case_		    =     "+"
								if field.default_factory is not dataclasses.MISSING:
									snake_case_		    =     field.default_factory()
								elif field.default is dataclasses.MISSING:
									snake_case_		    =     True
							else:
								snake_case_		    =     field.type
								if field.default is not dataclasses.MISSING:
									snake_case_		    =     field.default
								elif field.default_factory is not dataclasses.MISSING:
									snake_case_		    =     field.default_factory()
								else:
									snake_case_		    =     True
							parser.add_argument(__lowercase       ,	*__lowercase       ,	**__lowercase						)

							# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
							# Order is important for arguments with the same destination!
							# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
							# here and we do not need those changes/additional keys.
							if field.default is True and (field.type is bool or field.type == Optional[bool]):
								snake_case_		    =     False
								parser.add_argument(f"--no_{field.name}"       ,	action="store_false"       ,	dest=field.name       ,	**__lowercase						)






						def        snake_case__						(						self							:     List[str]       ,	__lowercase							:     DataClassType						):






							"""simple docstring"""






							if hasattr(__lowercase       ,	"_argument_group_name"						):
								snake_case_		    =     self.add_argument_group(dtype._argument_group_name						)
							else:
								snake_case_		    =     self

							try:
								snake_case_		    =     get_type_hints(__lowercase						)
							except NameError:
								raise RuntimeError(
								    f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
								    "removing line of `from __future__ import annotations` which opts in Postponed "
								    "Evaluation of Annotations (PEP 563)"						)
							except TypeError as ex:
								# Remove this block when we drop Python 3.9 support
								if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__lowercase						):
									snake_case_		    =     ".".join(map(__lowercase       ,	sys.version_info[:3]						)						)
									raise RuntimeError(
									    f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
									    "line of `from __future__ import annotations` which opts in union types as "
									    "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
									    "support Python versions that lower than 3.10, you need to use "
									    "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
									    "`X | None`."						) from ex
								raise

							for field in dataclasses.fields(__lowercase						):
								if not field.init:
									continue
								snake_case_		    =     type_hints[field.name]
								self._parse_dataclass_field(__lowercase       ,	__lowercase						)






						def        snake_case__						(						self							:     Union[str, Any]       ,	__lowercase							:     Union[str, Any]=None       ,	__lowercase							:     Union[str, Any]=False       ,	__lowercase							:     List[str]=True       ,	__lowercase							:     int=None       ,	__lowercase							:     Optional[int]=None       ,	):






							"""simple docstring"""






							if args_file_flag or args_filename or (look_for_args_file and len(sys.argv						)):
								snake_case_		    =     []

								if args_filename:
									args_files.append(Path(__lowercase						)						)
								elif look_for_args_file and len(sys.argv						):
									args_files.append(Path(sys.argv[0]						).with_suffix(".args"						)						)

								# args files specified via command line flag should overwrite default args files so we add them last
								if args_file_flag:
									# Create special parser just to extract the args_file_flag values
									snake_case_		    =     ArgumentParser()
									args_file_parser.add_argument(__lowercase       ,	type=__lowercase       ,	action="append"						)

									# Use only remaining args for further parsing (remove the args_file_flag)
									snake_case_    ,      snake_case_		    =     args_file_parser.parse_known_args(args=__lowercase						)
									snake_case_		    =     vars(__lowercase						).get(args_file_flag.lstrip("-"						)       ,	__lowercase						)

									if cmd_args_file_paths:
										args_files.extend([Path(__lowercase						) for p in cmd_args_file_paths]						)

								snake_case_		    =     []
								for args_file in args_files:
									if args_file.exists():
										file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
								snake_case_		    =     file_args + args if args is not None else file_args + sys.argv[1:]
							snake_case_    ,      snake_case_		    =     self.parse_known_args(args=__lowercase						)
							snake_case_		    =     []
							for dtype in self.dataclass_types:
								snake_case_		    =     {f.name for f in dataclasses.fields(__lowercase						) if f.init}
								snake_case_		    =     {k: v for k, v in vars(__lowercase						).items() if k in keys}
								for k in keys:
									delattr(__lowercase       ,	__lowercase						)
								snake_case_		    =     dtype(**__lowercase						)
								outputs.append(__lowercase						)
							if len(namespace.__dict__						) > 0:
								# additional namespace.
								outputs.append(__lowercase						)
							if return_remaining_strings:
								return (*outputs, remaining_args)
							else:
								if remaining_args:
									raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}"						)

								return (*outputs,)






						def        snake_case__						(						self							:     int       ,	__lowercase							:     Dict[str, Any]       ,	__lowercase							:     bool = False						):






							"""simple docstring"""






							snake_case_		    =     set(args.keys()						)
							snake_case_		    =     []
							for dtype in self.dataclass_types:
								snake_case_		    =     {f.name for f in dataclasses.fields(__lowercase						) if f.init}
								snake_case_		    =     {k: v for k, v in args.items() if k in keys}
								unused_keys.difference_update(inputs.keys()						)
								snake_case_		    =     dtype(**__lowercase						)
								outputs.append(__lowercase						)
							if not allow_extra_keys and unused_keys:
								raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(__lowercase						)}"						)
							return tuple(__lowercase						)






						def        snake_case__						(						self							:     List[Any]       ,	__lowercase							:     str       ,	__lowercase							:     bool = False						):






							"""simple docstring"""






							with open(Path(__lowercase						)       ,	encoding="utf-8"						) as open_json_file:
								snake_case_		    =     json.loads(open_json_file.read()						)
							snake_case_		    =     self.parse_dict(__lowercase       ,	allow_extra_keys=__lowercase						)
							return tuple(__lowercase						)






						def        snake_case__						(						self							:     int       ,	__lowercase							:     str       ,	__lowercase							:     bool = False						):






							"""simple docstring"""






							snake_case_		    =     self.parse_dict(yaml.safe_load(Path(__lowercase						).read_text()						)       ,	allow_extra_keys=__lowercase						)
							return tuple(__lowercase						)
