


'''simple docstring'''






import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class 			a  (  _SCREAMING_SNAKE_CASE	,					unittest.TestCase							):
 _lowerCAmelCase			       =						KandinskyVaaPriorEmbaEmbPipeline
 _lowerCAmelCase			       =						["""prompt""", """image"""]
 _lowerCAmelCase			       =						["""prompt""", """image"""]
 _lowerCAmelCase			       =						[
     """num_images_per_prompt""",
     """strength""",
     """generator""",
     """num_inference_steps""",
     """latents""",
     """negative_prompt""",
     """guidance_scale""",
     """output_type""",
     """return_dict""",
 ]
 _lowerCAmelCase			       =						False
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Dict:
      return 32
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Tuple:
      return 32
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Any:
      return self.time_input_dim
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Union[str, Any]:
      return self.time_input_dim * 4
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Dict:
      return 1_00
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Any:
      _a         =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )
      return tokenizer
 @property
 def 				__UpperCAmelCase		(			self    )       ->				int:
      torch.manual_seed(0    )
      _a         =				CLIPTextConfig(
          bos_token_id=0   ,					eos_token_id=2   ,					hidden_size=self.text_embedder_hidden_size   ,					projection_dim=self.text_embedder_hidden_size   ,					intermediate_size=37   ,					layer_norm_eps=1e-05   ,					num_attention_heads=4   ,					num_hidden_layers=5   ,					pad_token_id=1   ,					vocab_size=10_00   ,					)
      return CLIPTextModelWithProjection(__magic_name__    )
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Union[str, Any]:
      torch.manual_seed(0    )

      _a         =				{
          'num_attention_heads': 2,
          'attention_head_dim': 12,
          'embedding_dim': self.text_embedder_hidden_size,
          'num_layers': 1,
      }

      _a         =				PriorTransformer(**__magic_name__    )
      # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
      _a         =				nn.Parameter(torch.ones(model.clip_std.shape    )    )
      return model
 @property
 def 				__UpperCAmelCase		(			self    )       ->				str:
      torch.manual_seed(0    )
      _a         =				CLIPVisionConfig(
          hidden_size=self.text_embedder_hidden_size   ,					image_size=2_24   ,					projection_dim=self.text_embedder_hidden_size   ,					intermediate_size=37   ,					num_attention_heads=4   ,					num_channels=3   ,					num_hidden_layers=5   ,					patch_size=14   ,					)

      _a         =				CLIPVisionModelWithProjection(__magic_name__    )
      return model
 @property
 def 				__UpperCAmelCase		(			self    )       ->				List[Any]:
      _a         =				CLIPImageProcessor(
          crop_size=2_24   ,					do_center_crop=__magic_name__   ,					do_normalize=__magic_name__   ,					do_resize=__magic_name__   ,					image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]   ,					image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]   ,					resample=3   ,					size=2_24   ,					)

      return image_processor
 def 				__UpperCAmelCase		(			self    )       ->				List[str]:
      _a         =				self.dummy_prior
      _a         =				self.dummy_image_encoder
      _a         =				self.dummy_text_encoder
      _a         =				self.dummy_tokenizer
      _a         =				self.dummy_image_processor

      _a         =				UnCLIPScheduler(
          variance_type='fixed_small_log'   ,					prediction_type='sample'   ,					num_train_timesteps=10_00   ,					clip_sample=__magic_name__   ,					clip_sample_range=1_0.0   ,					)

      _a         =				{
          'prior': prior,
          'image_encoder': image_encoder,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'scheduler': scheduler,
          'image_processor': image_processor,
      }

      return components
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__=0    )       ->				Optional[int]:
      if str(__magic_name__    ).startswith('mps'    ):
           _a         =				torch.manual_seed(__magic_name__    )
      else:
           _a         =				torch.Generator(device=__magic_name__    ).manual_seed(__magic_name__    )

      _a         =				floats_tensor((1, 3, 64, 64)   ,					rng=random.Random(__magic_name__    )    ).to(__magic_name__    )
      _a         =				image.cpu().permute(0   ,					2   ,					3   ,					1    )[0]
      _a         =				Image.fromarray(np.uinta(__magic_name__    )    ).convert('RGB'    ).resize((2_56, 2_56)    )

      _a         =				{
          'prompt': 'horse',
          'image': init_image,
          'strength': 0.5,
          'generator': generator,
          'guidance_scale': 4.0,
          'num_inference_steps': 2,
          'output_type': 'np',
      }
      return inputs
 def 				__UpperCAmelCase		(			self    )       ->				List[str]:
      _a         =				'cpu'

      _a         =				self.get_dummy_components()

      _a         =				self.pipeline_class(**__magic_name__    )
      _a         =				pipe.to(__magic_name__    )

      pipe.set_progress_bar_config(disable=__magic_name__    )

      _a         =				pipe(**self.get_dummy_inputs(__magic_name__    )    )
      _a         =				output.image_embeds

      _a         =				pipe(
          **self.get_dummy_inputs(__magic_name__    )   ,					return_dict=__magic_name__   ,					)[0]

      _a         =				image[0, -10:]
      _a         =				image_from_tuple[0, -10:]

      assert image.shape == (1, 32)

      _a         =				np.array(
          [
              0.1_0_7_1_2_8_4,
              1.3_3_3_0_2_7_1,
              0.6_1_2_6_0_2_2_3,
              -0.6_6_9_1_0_6_5,
              -0.3_8_4_6_8_5_2,
              -1.0_3_0_3_6_6_1,
              0.2_2_7_1_6_1_1_1,
              0.0_3_3_4_8_9_0_1,
              0.3_0_0_4_0_6_7_5,
              -0.2_4_8_0_5_0_2_9,
          ]    )

      assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2
 @skip_mps
 def 				__UpperCAmelCase		(			self    )       ->				Tuple:
      _a         =				torch_device == 'cpu'
      _a         =				True
      _a         =				False

      self._test_inference_batch_single_identical(
          test_max_difference=__magic_name__   ,					relax_max_difference=__magic_name__   ,					test_mean_pixel_difference=__magic_name__   ,					)




 @skip_mps
 def 				__UpperCAmelCase		(			self    )       ->				Optional[int]:
      _a         =				torch_device == 'cpu'
      _a         =				False

      self._test_attention_slicing_forward_pass(
          test_max_difference=__magic_name__   ,					test_mean_pixel_difference=__magic_name__   ,					)





'''simple docstring'''






from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available




@dataclass
class 			a  (  _SCREAMING_SNAKE_CASE							):
 _lowerCAmelCase			       =						{
     """sld_warmup_steps""": 1_5,
     """sld_guidance_scale""": 2_0,
     """sld_threshold""": 0.0,
     """sld_momentum_scale""": 0.0,
     """sld_mom_beta""": 0.0,
 }
 _lowerCAmelCase			       =						{
     """sld_warmup_steps""": 1_0,
     """sld_guidance_scale""": 1_0_0_0,
     """sld_threshold""": 0.01,
     """sld_momentum_scale""": 0.3,
     """sld_mom_beta""": 0.4,
 }
 _lowerCAmelCase			       =						{
     """sld_warmup_steps""": 7,
     """sld_guidance_scale""": 2_0_0_0,
     """sld_threshold""": 0.025,
     """sld_momentum_scale""": 0.5,
     """sld_mom_beta""": 0.7,
 }
 _lowerCAmelCase			       =						{
     """sld_warmup_steps""": 0,
     """sld_guidance_scale""": 5_0_0_0,
     """sld_threshold""": 1.0,
     """sld_momentum_scale""": 0.5,
     """sld_mom_beta""": 0.7,
 }





@dataclass
class 			a  (  _SCREAMING_SNAKE_CASE							):
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42


if is_transformers_available() and is_torch_available():
 from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
 from .safety_checker import SafeStableDiffusionSafetyChecker

