

"""simple docstring"""

import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


a__ :	int						= logging.get_logger(__name__)

if is_tf_available():
							import tensorflow as tf


@dataclass
class 			_snake_case     (						lowerCAmelCase_       ):
						__snake_case 			=     'tf'
						__snake_case 			=     field(
						    default=lowerCAmelCase_						,			metadata={'help': 'Name of TPU'}						,			)

						__snake_case 			=     field(
						    default=lowerCAmelCase_						,			metadata={'help': 'Zone of TPU'}						,			)

						__snake_case 			=     field(
						    default=lowerCAmelCase_						,			metadata={'help': 'Name of Cloud TPU-enabled project'}						,			)

						__snake_case 			=     field(
						    default=1.0						,			metadata={'help': 'Power for the Polynomial decay LR scheduler.'}						,			)

						__snake_case 			=     field(default=lowerCAmelCase_						,			metadata={'help': 'Whether to activate the XLA compilation or not'}       )







						@cached_property
						def        _UpperCamelCase    (self							)			->						int:
											requires_backends(self     ,							['''tf''']							)
											logger.info('''Tensorflow: setting up strategy'''							)

											__lowercase												=			tf.config.list_physical_devices('''GPU'''							)

											# Set to float16 at first
											if self.fpaa:
																tf.keras.mixed_precision.set_global_policy('''mixed_float16'''							)

											if self.no_cuda:
																__lowercase												=			tf.distribute.OneDeviceStrategy(device='''/cpu:0'''							)
											else:
																try:
																					if self.tpu_name:
																										__lowercase												=			tf.distribute.cluster_resolver.TPUClusterResolver(
																										    self.tpu_name     ,							zone=self.tpu_zone     ,							project=self.gcp_project							)
																					else:
																										__lowercase												=			tf.distribute.cluster_resolver.TPUClusterResolver()
																except ValueError:
																					if self.tpu_name:
																										raise RuntimeError(f'''Couldn\'t connect to TPU {self.tpu_name}!'''							)
																					else:
																										__lowercase												=			None

																if tpu:
																					# Set to bfloat16 in case of TPU
																					if self.fpaa:
																										tf.keras.mixed_precision.set_global_policy('''mixed_bfloat16'''							)

																					tf.config.experimental_connect_to_cluster(lowerCamelCase_							)
																					tf.tpu.experimental.initialize_tpu_system(lowerCamelCase_							)

																					__lowercase												=			tf.distribute.TPUStrategy(lowerCamelCase_							)

																elif len(lowerCamelCase_							) == 0:
																					__lowercase												=			tf.distribute.OneDeviceStrategy(device='''/cpu:0'''							)
																elif len(lowerCamelCase_							) == 1:
																					__lowercase												=			tf.distribute.OneDeviceStrategy(device='''/gpu:0'''							)
																elif len(lowerCamelCase_							) > 1:
																					# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
																					__lowercase												=			tf.distribute.MirroredStrategy()
																else:
																					raise ValueError('''Cannot find the proper strategy, please check your environment properties.'''							)

											return strategy







						@property
						def        _UpperCamelCase    (self							)			->						str:
											requires_backends(self     ,							['''tf''']							)
											return self._setup_strategy







						@property
						def        _UpperCamelCase    (self							)			->						Optional[int]:
											requires_backends(self     ,							['''tf''']							)
											return self._setup_strategy.num_replicas_in_sync







						@property
						def        _UpperCamelCase    (self							)			->						Union[str, Any]:
											return False  # TF Logging is handled by Keras not the Trainer







						@property
						def        _UpperCamelCase    (self							)			->						Optional[int]:

											if self.per_gpu_train_batch_size:
																logger.warning(
																    '''Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future '''
																    '''version. Using `--per_device_train_batch_size` is preferred.'''							)
											__lowercase												=			self.per_gpu_train_batch_size or self.per_device_train_batch_size
											return per_device_batch_size * self.n_replicas







						@property
						def        _UpperCamelCase    (self							)			->						Union[str, Any]:

											if self.per_gpu_eval_batch_size:
																logger.warning(
																    '''Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future '''
																    '''version. Using `--per_device_eval_batch_size` is preferred.'''							)
											__lowercase												=			self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
											return per_device_batch_size * self.n_replicas







						@property
						def        _UpperCamelCase    (self							)			->						Any:
											requires_backends(self     ,							['''tf''']							)
											warnings.warn(
											    '''The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.'''     ,							lowerCamelCase_     ,							)
											return self._setup_strategy.num_replicas_in_sync





"""simple docstring"""

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

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


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


class 			_snake_case     (						UpperCamelCase       ):
						__snake_case 			=     ['safety_checker', 'feature_extractor']







						def __init__(self     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = True     ,							)			->						Optional[int]:
											super().__init__()
											if hasattr(scheduler.config     ,							'''steps_offset'''							) and scheduler.config.steps_offset != 1:
																__lowercase												=			(
																    f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'''
																    f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '''
																    '''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
																    ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
																    ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
																    ''' file'''
																)
																deprecate('''steps_offset!=1'''     ,							'''1.0.0'''     ,							UpperCAmelCase_     ,							standard_warn=UpperCAmelCase_							)
																__lowercase												=			dict(scheduler.config							)
																__lowercase												=			1
																__lowercase												=			FrozenDict(UpperCAmelCase_							)

											self.register_modules(
											    vae=UpperCAmelCase_     ,							text_encoder=UpperCAmelCase_     ,							tokenizer=UpperCAmelCase_     ,							unet=UpperCAmelCase_     ,							scheduler=UpperCAmelCase_     ,							safety_checker=UpperCAmelCase_     ,							feature_extractor=UpperCAmelCase_     ,							)
											self.register_to_config(requires_safety_checker=UpperCAmelCase_							)







						@property
						def        _UpperCamelCase    (self							)			->						Dict[str, Any]:
											return {k: getattr(self     ,							UpperCAmelCase_							) for k in self.config.keys() if not k.startswith('''_'''							)}







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_ = "auto"							)			->						str:
											if slice_size == "auto":
																# half the attention head size is usually a good trade-off between
																# speed and memory
																__lowercase												=			self.unet.config.attention_head_dim // 2
											self.unet.set_attention_slice(UpperCAmelCase_							)







						def        _UpperCamelCase    (self							)			->						int:
											self.enable_attention_slicing(UpperCAmelCase_							)







						@torch.no_grad()
						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = 0.8     ,							UpperCAmelCase_ = 5_0     ,							UpperCAmelCase_ = 7.5     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							UpperCAmelCase_ = 0.0     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = "pil"     ,							UpperCAmelCase_ = True     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							)			->						str:
											# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
											return StableDiffusionInpaintPipelineLegacy(**self.components							)(
											    prompt=UpperCAmelCase_     ,							image=UpperCAmelCase_     ,							mask_image=UpperCAmelCase_     ,							strength=UpperCAmelCase_     ,							num_inference_steps=UpperCAmelCase_     ,							guidance_scale=UpperCAmelCase_     ,							negative_prompt=UpperCAmelCase_     ,							num_images_per_prompt=UpperCAmelCase_     ,							eta=UpperCAmelCase_     ,							generator=UpperCAmelCase_     ,							output_type=UpperCAmelCase_     ,							return_dict=UpperCAmelCase_     ,							callback=UpperCAmelCase_     ,							)







						@torch.no_grad()
						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = 0.8     ,							UpperCAmelCase_ = 5_0     ,							UpperCAmelCase_ = 7.5     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							UpperCAmelCase_ = 0.0     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = "pil"     ,							UpperCAmelCase_ = True     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							**UpperCAmelCase_     ,							)			->						List[str]:
											# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
											return StableDiffusionImgaImgPipeline(**self.components							)(
											    prompt=UpperCAmelCase_     ,							image=UpperCAmelCase_     ,							strength=UpperCAmelCase_     ,							num_inference_steps=UpperCAmelCase_     ,							guidance_scale=UpperCAmelCase_     ,							negative_prompt=UpperCAmelCase_     ,							num_images_per_prompt=UpperCAmelCase_     ,							eta=UpperCAmelCase_     ,							generator=UpperCAmelCase_     ,							output_type=UpperCAmelCase_     ,							return_dict=UpperCAmelCase_     ,							callback=UpperCAmelCase_     ,							callback_steps=UpperCAmelCase_     ,							)







						@torch.no_grad()
						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = 5_1_2     ,							UpperCAmelCase_ = 5_1_2     ,							UpperCAmelCase_ = 5_0     ,							UpperCAmelCase_ = 7.5     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							UpperCAmelCase_ = 0.0     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = "pil"     ,							UpperCAmelCase_ = True     ,							UpperCAmelCase_ = None     ,							UpperCAmelCase_ = 1     ,							)			->						Optional[int]:
											# For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
											return StableDiffusionPipeline(**self.components							)(
											    prompt=UpperCAmelCase_     ,							height=UpperCAmelCase_     ,							width=UpperCAmelCase_     ,							num_inference_steps=UpperCAmelCase_     ,							guidance_scale=UpperCAmelCase_     ,							negative_prompt=UpperCAmelCase_     ,							num_images_per_prompt=UpperCAmelCase_     ,							eta=UpperCAmelCase_     ,							generator=UpperCAmelCase_     ,							latents=UpperCAmelCase_     ,							output_type=UpperCAmelCase_     ,							return_dict=UpperCAmelCase_     ,							callback=UpperCAmelCase_     ,							callback_steps=UpperCAmelCase_     ,							)


