
# Copyright 2022 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.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available






def 				UpperCAmelCase_						(				__SCREAMING_SNAKE_CASE=None				):
	if subparsers is not None:
		lowercase	    =       subparsers.add_parser('env'				)
	else:
		lowercase	    =       argparse.ArgumentParser('Accelerate env command'				)

	parser.add_argument(
	    '--config_file'					,				default=__SCREAMING_SNAKE_CASE					,				help='The config file to use for the default values in the launching script.'				)

	if subparsers is not None:
		parser.set_defaults(func=__SCREAMING_SNAKE_CASE				)
	return parser






def 				UpperCAmelCase_						(				__SCREAMING_SNAKE_CASE				):
	lowercase	    =       torch.__version__
	lowercase	    =       torch.cuda.is_available()
	lowercase	    =       is_xpu_available()
	lowercase	    =       is_npu_available()

	lowercase	    =       'Not found'
	# Get the default from the config file.
	if args.config_file is not None or os.path.isfile(__SCREAMING_SNAKE_CASE				):
		lowercase	    =       load_config_from_file(args.config_file				).to_dict()

	lowercase	    =       {
	    '`Accelerate` version': version,
	    'Platform': platform.platform(),
	    'Python version': platform.python_version(),
	    'Numpy version': np.__version__,
	    'PyTorch version (GPU?)': F'''{pt_version} ({pt_cuda_available})''',
	    'PyTorch XPU available': str(__SCREAMING_SNAKE_CASE				),
	    'PyTorch NPU available': str(__SCREAMING_SNAKE_CASE				),
	    'System RAM': F'''{psutil.virtual_memory().total / 1024 ** 3:.2f} GB''',
	}
	if pt_cuda_available:
		lowercase	    =       torch.cuda.get_device_name()

	print('\nCopy-and-paste the text below in your GitHub issue\n'				)
	print('\n'.join([F'''- {prop}: {val}''' for prop, val in info.items()]				)				)

	print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:'				)
	lowercase	    =       (
	    '\n'.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]				)
	    if isinstance(__SCREAMING_SNAKE_CASE					,				__SCREAMING_SNAKE_CASE				)
	    else F'''\t{accelerate_config}'''
	)
	print(__SCREAMING_SNAKE_CASE				)

	lowercase	    =       accelerate_config

	return info






def 				UpperCAmelCase_						(				):
	lowercase	    =       env_command_parser()
	lowercase	    =       parser.parse_args()
	env_command(__SCREAMING_SNAKE_CASE				)
	return 0


if __name__ == "__main__":
	raise SystemExit(main())








'''simple docstring'''




from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-1"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-2"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-3"""
__UpperCAmelCase            =       """CompVis/stable-diffusion-v1-4"""




class      UpperCamelCase__					(					lowercase_			):




					"""simple docstring"""


					def __init__(						self				:			List[str]      ,						lowerCamelCase_				:			AutoencoderKL      ,						lowerCamelCase_				:			CLIPTextModel      ,						lowerCamelCase_				:			CLIPTokenizer      ,						lowerCamelCase_				:			UNetaDConditionModel      ,						lowerCamelCase_				:			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,						lowerCamelCase_				:			StableDiffusionSafetyChecker      ,						lowerCamelCase_				:			CLIPImageProcessor      ,						lowerCamelCase_				:			bool = True      ,						):

							'''simple docstring'''



							super()._init_()

							SCREAMING_SNAKE_CASE :				Tuple		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			StableDiffusionPipeline.from_pretrained(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Optional[int]		=			StableDiffusionPipeline(
							    vae=lowerCamelCase_      ,						text_encoder=lowerCamelCase_      ,						tokenizer=lowerCamelCase_      ,						unet=lowerCamelCase_      ,						scheduler=lowerCamelCase_      ,						safety_checker=lowerCamelCase_      ,						feature_extractor=lowerCamelCase_      ,						requires_safety_checker=lowerCamelCase_      ,						)

							self.register_modules(pipelinea=self.pipea      ,						pipelinea=self.pipea      ,						pipelinea=self.pipea      ,						pipelinea=self.pipea						)


					@property
					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							return {k: getattr(self      ,						lowerCamelCase_						) for k in self.config.keys() if not k.startswith("""_"""						)}


					def lowerCamelCase_			(						self				:			Any      ,						lowerCamelCase_				:			Optional[Union[str, int]] = "auto"						):

							'''simple docstring'''



							if slice_size == "auto":
									# half the attention head size is usually a good trade-off between
									# speed and memory
									SCREAMING_SNAKE_CASE :				Optional[int]		=			self.unet.config.attention_head_dim // 2
							self.unet.set_attention_slice(lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Dict						):

							'''simple docstring'''



							self.enable_attention_slicing(lowerCamelCase_						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Union[str, Any]      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[int]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Union[str, Any]      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Optional[Any]      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			str      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)


					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Tuple      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Dict      ,						):

							'''simple docstring'''



							return self.pipea(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)



					@torch.no_grad()
					def lowerCamelCase_			(						self				:			Dict      ,						lowerCamelCase_				:			Union[str, List[str]]      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 5_12      ,						lowerCamelCase_				:			int = 50      ,						lowerCamelCase_				:			float = 7.5      ,						lowerCamelCase_				:			Optional[Union[str, List[str]]] = None      ,						lowerCamelCase_				:			Optional[int] = 1      ,						lowerCamelCase_				:			float = 0.0      ,						lowerCamelCase_				:			Optional[torch.Generator] = None      ,						lowerCamelCase_				:			Optional[torch.FloatTensor] = None      ,						lowerCamelCase_				:			Optional[str] = "pil"      ,						lowerCamelCase_				:			bool = True      ,						lowerCamelCase_				:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,						lowerCamelCase_				:			int = 1      ,						**lowerCamelCase_				:			Any      ,						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			"""cuda""" if torch.cuda.is_available() else """cpu"""
							self.to(lowerCamelCase_						)

							# Checks if the height and width are divisible by 8 or not
							if height % 8 != 0 or width % 8 != 0:
									raise ValueError(f'''`height` and `width` must be divisible by 8 but are {height} and {width}.'''						)

							# Get first result from Stable Diffusion Checkpoint v1.1
							SCREAMING_SNAKE_CASE :				List[str]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.2
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.3
							SCREAMING_SNAKE_CASE :				int		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get first result from Stable Diffusion Checkpoint v1.4
							SCREAMING_SNAKE_CASE :				Optional[int]		=			self.textaimg_sda_a(
							    prompt=lowerCamelCase_      ,						height=lowerCamelCase_      ,						width=lowerCamelCase_      ,						num_inference_steps=lowerCamelCase_      ,						guidance_scale=lowerCamelCase_      ,						negative_prompt=lowerCamelCase_      ,						num_images_per_prompt=lowerCamelCase_      ,						eta=lowerCamelCase_      ,						generator=lowerCamelCase_      ,						latents=lowerCamelCase_      ,						output_type=lowerCamelCase_      ,						return_dict=lowerCamelCase_      ,						callback=lowerCamelCase_      ,						callback_steps=lowerCamelCase_      ,						**lowerCamelCase_      ,						)

							# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
							return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]						)



