


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       _a			(				):


		"""simple docstring"""




		lowercase__						=				'''https://pypi.org/pypi/diffusers/json'''
		lowercase__						=				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			(				):


		"""simple docstring"""




		if HF_MODULES_CACHE in sys.path:
				return

		sys.path.append(SCREAMING_SNAKE_CASE					)
		os.makedirs(SCREAMING_SNAKE_CASE						,    exist_ok=SCREAMING_SNAKE_CASE					)
		lowercase__						=				Path(SCREAMING_SNAKE_CASE					) / '''__init__.py'''
		if not init_path.exists():
				init_path.touch()
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		init_hf_modules()
		lowercase__						=				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					)
		lowercase__						=				dynamic_module_path / '''__init__.py'''
		if not init_path.exists():
				init_path.touch()
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




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

		# Imports of the form `import .xxx`
		lowercase__						=				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					):


		"""simple docstring"""




		lowercase__						=				False
		lowercase__						=				[module_file]
		lowercase__						=				[]

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

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

				lowercase__						=				len(SCREAMING_SNAKE_CASE					) == 0
				all_relative_imports.extend(SCREAMING_SNAKE_CASE					)

		return all_relative_imports
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




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

		# Imports of the form `import xxx`
		lowercase__						=				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
		lowercase__						=				[imp.split('''.'''					)[0] for imp in imports if not imp.startswith('''.'''					)]

		# Unique-ify and test we got them all
		lowercase__						=				list(set(SCREAMING_SNAKE_CASE					)					)
		lowercase__						=				[]
		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						,    SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		lowercase__						=				module_path.replace(os.path.sep						,    '''.'''					)
		lowercase__						=				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					):


		"""simple docstring"""




		from ..pipelines import DiffusionPipeline

		lowercase__						=				dict(inspect.getmembers(SCREAMING_SNAKE_CASE						,    inspect.isclass					)					)

		lowercase__						=				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}.'					)
						lowercase__						=				cls

		return pipeline_class
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    ):


		"""simple docstring"""




		lowercase__						=				str(SCREAMING_SNAKE_CASE					)

		lowercase__						=				os.path.join(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)

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

				# retrieve github version that matches
				if revision is None:
						lowercase__						=				latest_version if latest_version[1:] in available_versions else '''main'''
						logger.info(f'Defaulting to latest_version: {revision}.'					)
				elif revision in available_versions:
						lowercase__						=				f'v{revision}'
				elif revision == "main":
						lowercase__						=				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
				lowercase__						=				COMMUNITY_PIPELINES_URL.format(revision=SCREAMING_SNAKE_CASE						,    pipeline=SCREAMING_SNAKE_CASE					)
				try:
						lowercase__						=				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						,    )
						lowercase__						=				'''git'''
						lowercase__						=				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
						lowercase__						=				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						,    )
						lowercase__						=				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
		lowercase__						=				check_imports(SCREAMING_SNAKE_CASE					)

		# Now we move the module inside our cached dynamic modules.
		lowercase__						=				DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
		create_dynamic_module(SCREAMING_SNAKE_CASE					)
		lowercase__						=				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:
						lowercase__						=				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					):
						lowercase__						=				use_auth_token
				elif use_auth_token is True:
						lowercase__						=				HfFolder.get_token()
				else:
						lowercase__						=				None

				lowercase__						=				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.
				lowercase__						=				submodule_path / commit_hash
				lowercase__						=				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						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = False						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = None						,    SCREAMING_SNAKE_CASE = False						,    **SCREAMING_SNAKE_CASE						,    ):


		"""simple docstring"""




		lowercase__						=				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'''						,    ''''''					)					)






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


lowerCAmelCase	=							'Create a default config file for Accelerate with only a few flags set.'
def       _a			(				SCREAMING_SNAKE_CASE="no"						,    SCREAMING_SNAKE_CASE = default_json_config_file						,    SCREAMING_SNAKE_CASE = False					):


		"""simple docstring"""




		lowercase__						=				Path(SCREAMING_SNAKE_CASE					)
		path.parent.mkdir(parents=SCREAMING_SNAKE_CASE						,    exist_ok=SCREAMING_SNAKE_CASE					)
		if path.exists():
				print(
				    f'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'					)
				return False
		lowercase__						=				mixed_precision.lower()
		if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
				raise ValueError(
				    f'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'					)
		lowercase__						=				{
		    '''compute_environment''': '''LOCAL_MACHINE''',
		    '''mixed_precision''': mixed_precision,
		}
		if torch.cuda.is_available():
				lowercase__						=				torch.cuda.device_count()
				lowercase__						=				num_gpus
				lowercase__						=				False
				if num_gpus > 1:
						lowercase__						=				'''MULTI_GPU'''
				else:
						lowercase__						=				'''NO'''
		elif is_xpu_available() and use_xpu:
				lowercase__						=				torch.xpu.device_count()
				lowercase__						=				num_xpus
				lowercase__						=				False
				if num_xpus > 1:
						lowercase__						=				'''MULTI_XPU'''
				else:
						lowercase__						=				'''NO'''
		elif is_npu_available():
				lowercase__						=				torch.npu.device_count()
				lowercase__						=				num_npus
				lowercase__						=				False
				if num_npus > 1:
						lowercase__						=				'''MULTI_NPU'''
				else:
						lowercase__						=				'''NO'''
		else:
				lowercase__						=				0
				lowercase__						=				True
				lowercase__						=				1
				lowercase__						=				'''NO'''
		lowercase__						=				ClusterConfig(**SCREAMING_SNAKE_CASE					)
		config.to_json_file(SCREAMING_SNAKE_CASE					)
		return path
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		lowercase__						=				parser.add_parser('''default'''						,    parents=SCREAMING_SNAKE_CASE						,    help=SCREAMING_SNAKE_CASE						,    formatter_class=SCREAMING_SNAKE_CASE					)
		parser.add_argument(
		    '''--config_file'''						,    default=SCREAMING_SNAKE_CASE						,    help=(
		        '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
		        '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
		        '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
		        '''with \'huggingface\'.'''
		    )						,    dest='''save_location'''						,    )

		parser.add_argument(
		    '''--mixed_precision'''						,    choices=['''no''', '''fp16''', '''bf16''']						,    type=SCREAMING_SNAKE_CASE						,    help='''Whether or not to use mixed precision training. '''
		    '''Choose between FP16 and BF16 (bfloat16) training. '''
		    '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''						,    default='''no'''						,    )
		parser.set_defaults(func=SCREAMING_SNAKE_CASE					)
		return parser
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		lowercase__						=				write_basic_config(args.mixed_precision						,    args.save_location					)
		if config_file:
				print(f'accelerate configuration saved at {config_file}'					)


