






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


__UpperCamelCase   :						str							=  logging.get_logger(__name__)  # pylint: disable=invalid-name


class 					__SCREAMING_SNAKE_CASE(		a_		):
							_UpperCAmelCase	      =    ["safety_checker", "feature_extractor"]
							def __init__(       self: List[Any]    ,		UpperCamelCase: AutoencoderKL    ,		UpperCamelCase: CLIPTextModel    ,		UpperCamelCase: CLIPTokenizer    ,		UpperCamelCase: UNetaDConditionModel    ,		UpperCamelCase: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]    ,		UpperCamelCase: StableDiffusionSafetyChecker    ,		UpperCamelCase: CLIPImageProcessor    ,		UpperCamelCase: bool = True    ,		)						->						Optional[Any]:
											super().__init__()
											if hasattr(scheduler.config    ,		'steps_offset'  ) and scheduler.config.steps_offset != 1:
															snake_case__													=       (
															    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  )
															snake_case__													=       dict(scheduler.config  )
															snake_case__													=       1
															snake_case__													=       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 lowerCAmelCase_	(       self: Any  )						->						Dict[str, Any]:
											return {k: getattr(self    ,		UpperCamelCase  ) for k in self.config.keys() if not k.startswith('_'  )}
							def lowerCAmelCase_	(       self: Dict    ,		UpperCamelCase: Optional[Union[str, int]] = "auto"  )						->						List[str]:
											if slice_size == "auto":
															# half the attention head size is usually a good trade-off between
															# speed and memory
															snake_case__													=       self.unet.config.attention_head_dim // 2
											self.unet.set_attention_slice(UpperCamelCase  )
							def lowerCAmelCase_	(       self: Tuple  )						->						Optional[int]:
											self.enable_attention_slicing(UpperCamelCase  )
							@torch.no_grad()
							def lowerCAmelCase_	(       self: int    ,		UpperCamelCase: Union[str, List[str]]    ,		UpperCamelCase: Union[torch.FloatTensor, PIL.Image.Image]    ,		UpperCamelCase: Union[torch.FloatTensor, PIL.Image.Image]    ,		UpperCamelCase: float = 0.8    ,		UpperCamelCase: Optional[int] = 50    ,		UpperCamelCase: Optional[float] = 7.5    ,		UpperCamelCase: Optional[Union[str, List[str]]] = None    ,		UpperCamelCase: Optional[int] = 1    ,		UpperCamelCase: Optional[float] = 0.0    ,		UpperCamelCase: Optional[torch.Generator] = None    ,		UpperCamelCase: Optional[str] = "pil"    ,		UpperCamelCase: bool = True    ,		UpperCamelCase: Optional[Callable[[int, int, torch.FloatTensor], None]] = None    ,		UpperCamelCase: int = 1    ,		)						->						List[Any]:
											# 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 lowerCAmelCase_	(       self: Optional[int]    ,		UpperCamelCase: Union[str, List[str]]    ,		UpperCamelCase: Union[torch.FloatTensor, PIL.Image.Image]    ,		UpperCamelCase: float = 0.8    ,		UpperCamelCase: Optional[int] = 50    ,		UpperCamelCase: Optional[float] = 7.5    ,		UpperCamelCase: Optional[Union[str, List[str]]] = None    ,		UpperCamelCase: Optional[int] = 1    ,		UpperCamelCase: Optional[float] = 0.0    ,		UpperCamelCase: Optional[torch.Generator] = None    ,		UpperCamelCase: Optional[str] = "pil"    ,		UpperCamelCase: bool = True    ,		UpperCamelCase: Optional[Callable[[int, int, torch.FloatTensor], None]] = None    ,		UpperCamelCase: int = 1    ,		**UpperCamelCase: Tuple    ,		)						->						Optional[Any]:
											# 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 lowerCAmelCase_	(       self: List[Any]    ,		UpperCamelCase: Union[str, List[str]]    ,		UpperCamelCase: int = 5_12    ,		UpperCamelCase: int = 5_12    ,		UpperCamelCase: int = 50    ,		UpperCamelCase: float = 7.5    ,		UpperCamelCase: Optional[Union[str, List[str]]] = None    ,		UpperCamelCase: Optional[int] = 1    ,		UpperCamelCase: float = 0.0    ,		UpperCamelCase: Optional[torch.Generator] = None    ,		UpperCamelCase: Optional[torch.FloatTensor] = None    ,		UpperCamelCase: Optional[str] = "pil"    ,		UpperCamelCase: bool = True    ,		UpperCamelCase: Optional[Callable[[int, int, torch.FloatTensor], None]] = None    ,		UpperCamelCase: int = 1    ,		)						->						Optional[Any]:
											# 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    ,		)












import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
							from transformers.models.electra.modeling_flax_electra import (
							    FlaxElectraForCausalLM,
							    FlaxElectraForMaskedLM,
							    FlaxElectraForMultipleChoice,
							    FlaxElectraForPreTraining,
							    FlaxElectraForQuestionAnswering,
							    FlaxElectraForSequenceClassification,
							    FlaxElectraForTokenClassification,
							    FlaxElectraModel,
							)


class 					__SCREAMING_SNAKE_CASE(		unittest.TestCase		):
							def __init__(       self: int    ,		UpperCamelCase: List[str]    ,		UpperCamelCase: Dict=13    ,		UpperCamelCase: Dict=7    ,		UpperCamelCase: Union[str, Any]=True    ,		UpperCamelCase: List[Any]=True    ,		UpperCamelCase: Optional[int]=True    ,		UpperCamelCase: Union[str, Any]=True    ,		UpperCamelCase: Optional[int]=99    ,		UpperCamelCase: Optional[int]=24    ,		UpperCamelCase: Any=32    ,		UpperCamelCase: Any=5    ,		UpperCamelCase: Any=4    ,		UpperCamelCase: int=37    ,		UpperCamelCase: Union[str, Any]="gelu"    ,		UpperCamelCase: str=0.1    ,		UpperCamelCase: str=0.1    ,		UpperCamelCase: int=5_12    ,		UpperCamelCase: Tuple=16    ,		UpperCamelCase: Dict=2    ,		UpperCamelCase: Any=0.02    ,		UpperCamelCase: List[Any]=4    ,		)						->						int:
											snake_case__													=       parent
											snake_case__													=       batch_size
											snake_case__													=       seq_length
											snake_case__													=       is_training
											snake_case__													=       use_attention_mask
											snake_case__													=       use_token_type_ids
											snake_case__													=       use_labels
											snake_case__													=       vocab_size
											snake_case__													=       hidden_size
											snake_case__													=       embedding_size
											snake_case__													=       num_hidden_layers
											snake_case__													=       num_attention_heads
											snake_case__													=       intermediate_size
											snake_case__													=       hidden_act
											snake_case__													=       hidden_dropout_prob
											snake_case__													=       attention_probs_dropout_prob
											snake_case__													=       max_position_embeddings
											snake_case__													=       type_vocab_size
											snake_case__													=       type_sequence_label_size
											snake_case__													=       initializer_range
											snake_case__													=       num_choices
							def lowerCAmelCase_	(       self: List[str]  )						->						List[str]:
											snake_case__													=       ids_tensor([self.batch_size, self.seq_length]    ,		self.vocab_size  )

											snake_case__													=       None
											if self.use_attention_mask:
															snake_case__													=       random_attention_mask([self.batch_size, self.seq_length]  )

											snake_case__													=       None
											if self.use_token_type_ids:
															snake_case__													=       ids_tensor([self.batch_size, self.seq_length]    ,		self.type_vocab_size  )

											snake_case__													=       ElectraConfig(
											    vocab_size=self.vocab_size    ,		hidden_size=self.hidden_size    ,		embedding_size=self.embedding_size    ,		num_hidden_layers=self.num_hidden_layers    ,		num_attention_heads=self.num_attention_heads    ,		intermediate_size=self.intermediate_size    ,		hidden_act=self.hidden_act    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		max_position_embeddings=self.max_position_embeddings    ,		type_vocab_size=self.type_vocab_size    ,		initializer_range=self.initializer_range    ,		)

											return config, input_ids, token_type_ids, attention_mask


							def lowerCAmelCase_	(       self: Tuple  )						->						Any:
											snake_case__													=       self.prepare_config_and_inputs()
											snake_case__							,  snake_case__							,  snake_case__							,  snake_case__													=       config_and_inputs
											snake_case__													=       {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
											return config, inputs_dict


@require_flax
class 					__SCREAMING_SNAKE_CASE(		a_      ,					unittest.TestCase		):
							_UpperCAmelCase	      =    True

							_UpperCAmelCase	      =    (
							    (
							        FlaxElectraModel,
							        FlaxElectraForCausalLM,
							        FlaxElectraForMaskedLM,
							        FlaxElectraForPreTraining,
							        FlaxElectraForTokenClassification,
							        FlaxElectraForQuestionAnswering,
							        FlaxElectraForMultipleChoice,
							        FlaxElectraForSequenceClassification,
							    )
							    if is_flax_available()
							    else ()
							)
							def lowerCAmelCase_	(       self: List[Any]  )						->						Dict:
											snake_case__													=       FlaxElectraModelTester(self  )


							@slow
							def lowerCAmelCase_	(       self: int  )						->						Optional[int]:
											for model_class_name in self.all_model_classes:
															if model_class_name == FlaxElectraForMaskedLM:
																			snake_case__													=       model_class_name.from_pretrained('google/electra-small-generator'  )
															else:
																			snake_case__													=       model_class_name.from_pretrained('google/electra-small-discriminator'  )
															snake_case__													=       model(np.ones((1, 1)  )  )
															self.assertIsNotNone(UpperCamelCase  )




