'''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    UpperCAmelCase__	(							_snake_case       ,  unittest.TestCase      ):






   """simple docstring"""
   A				:							Any			     =     KandinskyVaaPriorEmbaEmbPipeline
   A				:							Dict			     =     ['''prompt''', '''image''']
   A				:							Tuple			     =     ['''prompt''', '''image''']
   A				:							Tuple			     =     [
       '''num_images_per_prompt''',
       '''strength''',
       '''generator''',
       '''num_inference_steps''',
       '''latents''',
       '''negative_prompt''',
       '''guidance_scale''',
       '''output_type''',
       '''return_dict''',
   ]
   A				:							Optional[int]			     =     False
   @property
   def 		_lowerCamelCase			(self					)     ->  str:
        return 32
   @property
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        return 32
   @property
   def 		_lowerCamelCase			(self					)     ->  List[str]:
        return self.time_input_dim
   @property
   def 		_lowerCamelCase			(self					)     ->  Tuple:
        return self.time_input_dim * 4
   @property
   def 		_lowerCamelCase			(self					)     ->  str:
        return 100
   @property
   def 		_lowerCamelCase			(self					)     ->  Any:
        lowercase_       :							List[str]  					=       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'					)
        return tokenizer
   @property
   def 		_lowerCamelCase			(self					)     ->  str:
        torch.manual_seed(0					)
        lowercase_       :							int  					=       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=1_000							,					)
        return CLIPTextModelWithProjection(_a					)
   @property
   def 		_lowerCamelCase			(self					)     ->  List[str]:
        torch.manual_seed(0					)

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

        lowercase_       :							List[str]  					=       PriorTransformer(**_a					)
        # 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
        lowercase_       :							Tuple  					=       nn.Parameter(torch.ones(model.clip_std.shape					)					)
        return model
   @property
   def 		_lowerCamelCase			(self					)     ->  Optional[int]:
        torch.manual_seed(0					)
        lowercase_       :							Optional[int]  					=       CLIPVisionConfig(
            hidden_size=self.text_embedder_hidden_size							,					image_size=224							,					projection_dim=self.text_embedder_hidden_size							,					intermediate_size=37							,					num_attention_heads=4							,					num_channels=3							,					num_hidden_layers=5							,					patch_size=14							,					)

        lowercase_       :							str  					=       CLIPVisionModelWithProjection(_a					)
        return model
   @property
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        lowercase_       :							List[str]  					=       CLIPImageProcessor(
            crop_size=224							,					do_center_crop=_a							,					do_normalize=_a							,					do_resize=_a							,					image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]							,					image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]							,					resample=3							,					size=224							,					)

        return image_processor
   def 		_lowerCamelCase			(self					)     ->  Optional[int]:
        lowercase_       :							str  					=       self.dummy_prior
        lowercase_       :							Any  					=       self.dummy_image_encoder
        lowercase_       :							List[str]  					=       self.dummy_text_encoder
        lowercase_       :							Dict  					=       self.dummy_tokenizer
        lowercase_       :							Tuple  					=       self.dummy_image_processor

        lowercase_       :							str  					=       UnCLIPScheduler(
            variance_type='fixed_small_log'							,					prediction_type='sample'							,					num_train_timesteps=1_000							,					clip_sample=_a							,					clip_sample_range=10.0							,					)

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

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

        lowercase_       :							List[Any]  					=       floats_tensor((1, 3, 64, 64)							,					rng=random.Random(_a					)					).to(_a					)
        lowercase_       :							List[str]  					=       image.cpu().permute(0							,					2							,					3							,					1					)[0]
        lowercase_       :							str  					=       Image.fromarray(np.uinta(_a					)					).convert('RGB'					).resize((256, 256)					)

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

        lowercase_       :							Any  					=       self.get_dummy_components()

        lowercase_       :							Any  					=       self.pipeline_class(**_a					)
        lowercase_       :							Optional[int]  					=       pipe.to(_a					)

        pipe.set_progress_bar_config(disable=_a					)

        lowercase_       :							Any  					=       pipe(**self.get_dummy_inputs(_a					)					)
        lowercase_       :							Optional[Any]  					=       output.image_embeds

        lowercase_       :							Optional[Any]  					=       pipe(
            **self.get_dummy_inputs(_a					)							,					return_dict=_a							,					)[0]

        lowercase_       :							List[str]  					=       image[0, -10:]
        lowercase_       :							Tuple  					=       image_from_tuple[0, -10:]

        assert image.shape == (1, 32)

        lowercase_       :							List[Any]  					=       np.array(
            [
                0.1_07_12_84,
                1.3_33_02_71,
                0.61_26_02_23,
                -0.6_69_10_65,
                -0.3_84_68_52,
                -1.0_30_36_61,
                0.22_71_61_11,
                0.03_34_89_01,
                0.30_04_06_75,
                -0.24_80_50_29,
            ]					)

        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 		_lowerCamelCase			(self					)     ->  Optional[int]:
        lowercase_       :							Any  					=       torch_device == 'cpu'
        lowercase_       :							str  					=       True
        lowercase_       :							Union[str, Any]  					=       False

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





   @skip_mps
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        lowercase_       :							int  					=       torch_device == 'cpu'
        lowercase_       :							int  					=       False

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





'''simple docstring'''




from dataclasses import dataclass
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
# Copied from diffusers.pipelines.stable_diffusion.__init__.StableDiffusionPipelineOutput with Stable->Alt
class    UpperCAmelCase__	(							_snake_case      ):






   """simple docstring"""
   A				:							Union[List[PIL.Image.Image], np.ndarray]
   A				:							Optional[List[bool]]


if is_transformers_available() and is_torch_available():
 from .modeling_roberta_series import RobertaSeriesModelWithTransformation
 from .pipeline_alt_diffusion import AltDiffusionPipeline
 from .pipeline_alt_diffusion_imgaimg import AltDiffusionImgaImgPipeline




