
import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





class   UpperCamelCase_      (      __a		,    __a		,    unittest.TestCase		):







						'''simple docstring'''



						UpperCamelCase      :  Union[str, Any]				   =					StableDiffusionXLImgaImgPipeline
						UpperCamelCase      :  List[Any]				   =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
						UpperCamelCase      :  int				   =					PipelineTesterMixin.required_optional_params - {'''latents'''}
						UpperCamelCase      :  Optional[Any]				   =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
						UpperCamelCase      :  str				   =					IMAGE_TO_IMAGE_IMAGE_PARAMS
						UpperCamelCase      :  str				   =					IMAGE_TO_IMAGE_IMAGE_PARAMS





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Dict:
										torch.manual_seed(0     )
										lowercase         =      UNetaDConditionModel(
										    block_out_channels=(32, 64)		,    layers_per_block=2		,    sample_size=32		,    in_channels=4		,    out_channels=4		,    down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")		,    up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")		,    attention_head_dim=(2, 4)		,    use_linear_projection=lowerCAmelCase__		,    addition_embed_type="text_time"		,    addition_time_embed_dim=8		,    transformer_layers_per_block=(1, 2)		,    projection_class_embeddings_input_dim=80		,    cross_attention_dim=64		,    )
										lowercase         =      EulerDiscreteScheduler(
										    beta_start=0.0_00_85		,    beta_end=0.0_12		,    steps_offset=1		,    beta_schedule="scaled_linear"		,    timestep_spacing="leading"		,    )
										torch.manual_seed(0     )
										lowercase         =      AutoencoderKL(
										    block_out_channels=[32, 64]		,    in_channels=3		,    out_channels=3		,    down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]		,    up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]		,    latent_channels=4		,    sample_size=128		,    )
										torch.manual_seed(0     )
										lowercase         =      CLIPTextConfig(
										    bos_token_id=0		,    eos_token_id=2		,    hidden_size=32		,    intermediate_size=37		,    layer_norm_eps=1E-0_5		,    num_attention_heads=4		,    num_hidden_layers=5		,    pad_token_id=1		,    vocab_size=1000		,    hidden_act="gelu"		,    projection_dim=32		,    )
										lowercase         =      CLIPTextModel(lowerCAmelCase__     )
										lowercase         =      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,    local_files_only=lowerCAmelCase__     )

										lowercase         =      CLIPTextModelWithProjection(lowerCAmelCase__     )
										lowercase         =      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,    local_files_only=lowerCAmelCase__     )

										lowercase         =      {
										    "unet": unet,
										    "scheduler": scheduler,
										    "vae": vae,
										    "text_encoder": text_encoder,
										    "tokenizer": tokenizer,
										    "text_encoder_2": text_encoder_a,
										    "tokenizer_2": tokenizer_a,
										    # "safety_checker": None,
										    # "feature_extractor": None,
										}
										return components





						def        SCREAMING_SNAKE_CASE(			self							:Any		,    lowerCAmelCase__							:int		,    lowerCAmelCase__							:str=0     )  ->Optional[Any]:
										lowercase         =      floats_tensor((1, 3, 32, 32)		,    rng=random.Random(lowerCAmelCase__     )     ).to(lowerCAmelCase__     )
										lowercase         =      image / 2 + 0.5
										if str(lowerCAmelCase__     ).startswith("mps"     ):
														lowercase         =      torch.manual_seed(lowerCAmelCase__     )
										else:
														lowercase         =      torch.Generator(device=lowerCAmelCase__     ).manual_seed(lowerCAmelCase__     )
										lowercase         =      {
										    "prompt": "A painting of a squirrel eating a burger",
										    "image": image,
										    "generator": generator,
										    "num_inference_steps": 2,
										    "guidance_scale": 5.0,
										    "output_type": "numpy",
										    "strength": 0.75,
										}
										return inputs





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->List[str]:
										lowercase         =      "cpu"  # ensure determinism for the device-dependent torch.Generator
										lowercase         =      self.get_dummy_components()
										lowercase         =      StableDiffusionXLImgaImgPipeline(**lowerCAmelCase__     )
										lowercase         =      sd_pipe.to(lowerCAmelCase__     )
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

										lowercase         =      self.get_dummy_inputs(lowerCAmelCase__     )
										lowercase         =      sd_pipe(**lowerCAmelCase__     ).images
										lowercase         =      image[0, -3:, -3:, -1]

										assert image.shape == (1, 32, 32, 3)

										lowercase         =      np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]     )

										assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2





						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Tuple:
										super().test_attention_slicing_forward_pass(expected_max_diff=3E-3     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->List[str]:
										super().test_inference_batch_single_identical(expected_max_diff=3E-3     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]     )  ->Union[str, Any]:
										pass





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->Tuple:
										lowercase         =      self.get_dummy_components()
										lowercase         =      StableDiffusionXLImgaImgPipeline(**lowerCAmelCase__     )
										lowercase         =      sd_pipe.to(lowerCAmelCase__     )
										lowercase         =      sd_pipe.to(lowerCAmelCase__     )
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

										# forward without prompt embeds
										lowercase         =      self.get_dummy_inputs(lowerCAmelCase__     )
										lowercase         =      3 * ["this is a negative prompt"]
										lowercase         =      negative_prompt
										lowercase         =      3 * [inputs["prompt"]]

										lowercase         =      sd_pipe(**lowerCAmelCase__     )
										lowercase         =      output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										lowercase         =      self.get_dummy_inputs(lowerCAmelCase__     )
										lowercase         =      3 * ["this is a negative prompt"]
										lowercase         =      3 * [inputs.pop("prompt"     )]

										(
										    (
										    lowercase
										)     ,	(
										    lowercase
										)     ,	(
										    lowercase
										)     ,	(
										    lowercase
										)     ,	
										)         =      sd_pipe.encode_prompt(lowerCAmelCase__		,    negative_prompt=lowerCAmelCase__     )

										lowercase         =      sd_pipe(
										    **lowerCAmelCase__		,    prompt_embeds=lowerCAmelCase__		,    negative_prompt_embeds=lowerCAmelCase__		,    pooled_prompt_embeds=lowerCAmelCase__		,    negative_pooled_prompt_embeds=lowerCAmelCase__		,    )
										lowercase         =      output.images[0, -3:, -3:, -1]

										# make sure that it's equal
										assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()     ).max() < 1E-4





@slow
@require_torch_gpu
class   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Optional[Any]     )  ->str:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]		,    lowerCAmelCase__							:Union[str, Any]		,    lowerCAmelCase__							:Dict="cpu"		,    lowerCAmelCase__							:Optional[Any]=torch.floataa		,    lowerCAmelCase__							:Optional[int]=0     )  ->Union[str, Any]:
										lowercase         =      torch.Generator(device=lowerCAmelCase__     ).manual_seed(lowerCAmelCase__     )
										lowercase         =      np.random.RandomState(lowerCAmelCase__     ).standard_normal((1, 4, 64, 64)     )
										lowercase         =      torch.from_numpy(lowerCAmelCase__     ).to(device=lowerCAmelCase__		,    dtype=lowerCAmelCase__     )
										lowercase         =      {
										    "prompt": "a photograph of an astronaut riding a horse",
										    "latents": latents,
										    "generator": generator,
										    "num_inference_steps": 3,
										    "guidance_scale": 7.5,
										    "output_type": "numpy",
										}
										return inputs





						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->List[str]:
										lowercase         =      DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"     )
										pipe.to(lowerCAmelCase__     )
										pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

										lowercase         =      self.get_inputs(lowerCAmelCase__     )
										lowercase         =      pipe(**lowerCAmelCase__     ).images
										lowercase         =      image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 512, 512, 3)
										lowercase         =      np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]     )
										assert np.abs(image_slice - expected_slice     ).max() < 7E-3


import numpy as np

# Importing the Keras libraries and packages
import tensorflow as tf
from tensorflow.keras import layers, models

if __name__ == "__main__":
						# Initialising the CNN
						# (Sequential- Building the model layer by layer)
						_snake_case      :							Tuple     	=    models.Sequential()

						# Step 1 - Convolution
						# Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel
						# (3,3) is the kernel size (filter matrix)
						classifier.add(
						    layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation="relu")
						)

						# Step 2 - Pooling
						classifier.add(layers.MaxPoolingaD(pool_size=(2, 2)))

						# Adding a second convolutional layer
						classifier.add(layers.ConvaD(32, (3, 3), activation="relu"))
						classifier.add(layers.MaxPoolingaD(pool_size=(2, 2)))

						# Step 3 - Flattening
						classifier.add(layers.Flatten())

						# Step 4 - Full connection
						classifier.add(layers.Dense(units=1_28, activation="relu"))
						classifier.add(layers.Dense(units=1, activation="sigmoid"))

						# Compiling the CNN
						classifier.compile(
						    optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]
						)

						# Part 2 - Fitting the CNN to the images

						# Load Trained model weights

						# from keras.models import load_model
						# regressor=load_model('cnn.h5')

						_snake_case      :							Optional[int]     	=    tf.keras.preprocessing.image.ImageDataGenerator(
						    rescale=1.0 / 2_55, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
						)

						_snake_case      :							Any     	=    tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 2_55)

						_snake_case      :							Dict     	=    train_datagen.flow_from_directory(
						    "dataset/training_set", target_size=(64, 64), batch_size=32, class_mode="binary"
						)

						_snake_case      :							Dict     	=    test_datagen.flow_from_directory(
						    "dataset/test_set", target_size=(64, 64), batch_size=32, class_mode="binary"
						)

						classifier.fit_generator(
						    training_set, steps_per_epoch=5, epochs=30, validation_data=test_set
						)

						classifier.save("cnn.h5")

						# Part 3 - Making new predictions

						_snake_case      :							int     	=    tf.keras.preprocessing.image.load_img(
						    "dataset/single_prediction/image.png", target_size=(64, 64)
						)
						_snake_case      :							Any     	=    tf.keras.preprocessing.image.img_to_array(test_image)
						_snake_case      :							int     	=    np.expand_dims(test_image, axis=0)
						_snake_case      :							Optional[Any]     	=    classifier.predict(test_image)
						# training_set.class_indices
						if result[0][0] == 0:
												_snake_case      :							str     	=    "Normal"
						if result[0][0] == 1:
												_snake_case      :							str     	=    "Abnormality detected"
