
"""simple docstring"""





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(   lowerCamelCase				,					lowerCamelCase				,					unittest.TestCase     ):
		lowercase__      =				StableDiffusionXLImgaImgPipeline
		lowercase__      =				TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
		lowercase__      =				PipelineTesterMixin.required_optional_params - {'latents'}
		lowercase__      =				TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
		lowercase__      =				IMAGE_TO_IMAGE_IMAGE_PARAMS
		lowercase__      =				IMAGE_TO_IMAGE_IMAGE_PARAMS



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							torch.manual_seed(0)
							_UpperCamelCase										=  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=__a    ,		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    ,		)
							_UpperCamelCase										=  EulerDiscreteScheduler(
							    beta_start=0.0_0085    ,		beta_end=0.012    ,		steps_offset=1    ,		beta_schedule='''scaled_linear'''    ,		timestep_spacing='''leading'''    ,		)
							torch.manual_seed(0)
							_UpperCamelCase										=  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=1_28    ,		)
							torch.manual_seed(0)
							_UpperCamelCase										=  CLIPTextConfig(
							    bos_token_id=0    ,		eos_token_id=2    ,		hidden_size=32    ,		intermediate_size=37    ,		layer_norm_eps=1e-05    ,		num_attention_heads=4    ,		num_hidden_layers=5    ,		pad_token_id=1    ,		vocab_size=10_00    ,		hidden_act='''gelu'''    ,		projection_dim=32    ,		)
							_UpperCamelCase										=  CLIPTextModel(__a)
							_UpperCamelCase										=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,		local_files_only=__a)

							_UpperCamelCase										=  CLIPTextModelWithProjection(__a)
							_UpperCamelCase										=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,		local_files_only=__a)

							_UpperCamelCase										=  {
							    '''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 						UpperCAmelCase							( self    ,		__a    ,		__a=0)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  floats_tensor((1, 3, 32, 32)    ,		rng=random.Random(__a)).to(__a)
							_UpperCamelCase										=  image / 2 + 0.5
							if str(__a).startswith('''mps'''):
												_UpperCamelCase										=  torch.manual_seed(__a)
							else:
												_UpperCamelCase										=  torch.Generator(device=__a).manual_seed(__a)
							_UpperCamelCase										=  {
							    '''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 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCamelCase										=  self.get_dummy_components()
							_UpperCamelCase										=  StableDiffusionXLImgaImgPipeline(**__a)
							_UpperCamelCase										=  sd_pipe.to(__a)
							sd_pipe.set_progress_bar_config(disable=__a)

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

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

							_UpperCamelCase										=  np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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



		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)



		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							super().test_inference_batch_single_identical(expected_max_diff=3e-3)



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							pass




		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							_UpperCamelCase										=  self.get_dummy_components()
							_UpperCamelCase										=  StableDiffusionXLImgaImgPipeline(**__a)
							_UpperCamelCase										=  sd_pipe.to(__a)
							_UpperCamelCase										=  sd_pipe.to(__a)
							sd_pipe.set_progress_bar_config(disable=__a)

							# forward without prompt embeds
							_UpperCamelCase										=  self.get_dummy_inputs(__a)
							_UpperCamelCase										=  3 * ['''this is a negative prompt''']
							_UpperCamelCase										=  negative_prompt
							_UpperCamelCase										=  3 * [inputs['''prompt''']]

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

							# forward with prompt embeds
							_UpperCamelCase										=  self.get_dummy_inputs(__a)
							_UpperCamelCase										=  3 * ['''this is a negative prompt''']
							_UpperCamelCase										=  3 * [inputs.pop('''prompt''')]

							(
							    (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  
							)										=  sd_pipe.encode_prompt(__a    ,		negative_prompt=__a)

							_UpperCamelCase										=  sd_pipe(
							    **__a    ,		prompt_embeds=__a    ,		negative_prompt_embeds=__a    ,		pooled_prompt_embeds=__a    ,		negative_pooled_prompt_embeds=__a    ,		)
							_UpperCamelCase										=  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     ):



		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def 						UpperCAmelCase							( self    ,		__a    ,		__a="cpu"    ,		__a=torch.floataa    ,		__a=0)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  torch.Generator(device=__a).manual_seed(__a)
							_UpperCamelCase										=  np.random.RandomState(__a).standard_normal((1, 4, 64, 64))
							_UpperCamelCase										=  torch.from_numpy(__a).to(device=__a    ,		dtype=__a)
							_UpperCamelCase										=  {
							    '''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 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''')
							pipe.to(__a)
							pipe.set_progress_bar_config(disable=__a)

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

							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506])
							assert np.abs(image_slice - expected_slice).max() < 7e-3








"""simple docstring"""





import os
from collections import namedtuple

import pytest

from datasets import ClassLabel, Features, Sequence, Value
from datasets.commands.test import TestCommand
from datasets.info import DatasetInfo, DatasetInfosDict


_a														=		namedtuple(
    """_TestCommandArgs""",
    [
        """dataset""",
        """name""",
        """cache_dir""",
        """data_dir""",
        """all_configs""",
        """save_infos""",
        """ignore_verifications""",
        """force_redownload""",
        """clear_cache""",
    ],
    defaults=[None, None, None, False, False, False, False, False],
)



def 				lowerCamelCase__		(      __snake_case,					__snake_case     )							->		Optional[int]:


					"""simple docstring"""





					return (abs(source - target     ) / target) < 0.01



@pytest.mark.integration
def 				lowerCamelCase__		(      __snake_case     )							->		Dict:


					"""simple docstring"""





					_UpperCamelCase										=  _TestCommandArgs(dataset=__snake_case,					all_configs=__snake_case,					save_infos=__snake_case     )
					_UpperCamelCase										=  TestCommand(*__snake_case     )
					test_command.run()
					_UpperCamelCase										=  os.path.join(__snake_case,					'''README.md'''     )
					assert os.path.exists(__snake_case     )
					_UpperCamelCase										=  DatasetInfosDict.from_directory(__snake_case     )
					_UpperCamelCase										=  DatasetInfosDict(
					    {
					        '''default''': DatasetInfo(
					            features=Features(
					                {
					                    '''tokens''': Sequence(Value('''string'''     )     ),
					                    '''ner_tags''': Sequence(
					                        ClassLabel(names=['''O''', '''B-PER''', '''I-PER''', '''B-ORG''', '''I-ORG''', '''B-LOC''', '''I-LOC''']     )     ),
					                    '''langs''': Sequence(Value('''string'''     )     ),
					                    '''spans''': Sequence(Value('''string'''     )     ),
					                }     ),					splits=[
					                {
					                    '''name''': '''train''',
					                    '''num_bytes''': 2_35_15_63,
					                    '''num_examples''': 1_00_00,
					                },
					                {
					                    '''name''': '''validation''',
					                    '''num_bytes''': 23_84_18,
					                    '''num_examples''': 10_00,
					                },
					            ],					download_size=3_94_06_80,					dataset_size=2_58_99_81,					)
					    }     )
					assert dataset_infos.keys() == expected_dataset_infos.keys()
					for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
										_UpperCamelCase			,  _UpperCamelCase										=  getattr(dataset_infos['''default'''],					__snake_case     ), getattr(expected_dataset_infos['''default'''],					__snake_case     )
										if key == "num_bytes":
															assert is_apercent_close(__snake_case,					__snake_case     )
										elif key == "splits":
															assert list(__snake_case     ) == list(__snake_case     )
															for split in result:
																				assert result[split].name == expected[split].name
																				assert result[split].num_examples == expected[split].num_examples
																				assert is_apercent_close(result[split].num_bytes,					expected[split].num_bytes     )
										else:
															result == expected






