


"""simple docstring"""





import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 		snake_case_(       a__							,					unittest.TestCase			):
     __UpperCamelCase  =					KandinskyVaaPriorPipeline
     __UpperCamelCase  =					['''prompt''']
     __UpperCamelCase  =					['''prompt''', '''negative_prompt''']
     __UpperCamelCase  =					[
         '''num_images_per_prompt''',
         '''generator''',
         '''num_inference_steps''',
         '''latents''',
         '''negative_prompt''',
         '''guidance_scale''',
         '''output_type''',
         '''return_dict''',
     ]
     __UpperCamelCase  =					False






     @property
     def      lowerCamelCase__     (	self  :					List[Any]				):
           return 3_2






     @property
     def      lowerCamelCase__     (	self  :					str				):
           return 3_2






     @property
     def      lowerCamelCase__     (	self  :					Tuple				):
           return self.time_input_dim






     @property
     def      lowerCamelCase__     (	self  :					Any				):
           return self.time_input_dim * 4






     @property
     def      lowerCamelCase__     (	self  :					int				):
           return 1_0_0






     @property
     def      lowerCamelCase__     (	self  :					int				):
           lowerCAmelCase					:	List[str]       =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)
           return tokenizer






     @property
     def      lowerCamelCase__     (	self  :					Optional[int]				):
           torch.manual_seed(0				)
           lowerCAmelCase					:	Tuple       =   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=3_7					,				layer_norm_eps=1E-05					,				num_attention_heads=4					,				num_hidden_layers=5					,				pad_token_id=1					,				vocab_size=1_0_0_0					,				)
           return CLIPTextModelWithProjection(UpperCamelCase_				)






     @property
     def      lowerCamelCase__     (	self  :					List[Any]				):
           torch.manual_seed(0				)

           lowerCAmelCase					:	Any       =   {
               '''num_attention_heads''': 2,
               '''attention_head_dim''': 1_2,
               '''embedding_dim''': self.text_embedder_hidden_size,
               '''num_layers''': 1,
           }

           lowerCAmelCase					:	List[Any]       =   PriorTransformer(**UpperCamelCase_				)
           # 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
           lowerCAmelCase					:	int       =   nn.Parameter(torch.ones(model.clip_std.shape				)				)
           return model






     @property
     def      lowerCamelCase__     (	self  :					Union[str, Any]				):
           torch.manual_seed(0				)
           lowerCAmelCase					:	int       =   CLIPVisionConfig(
               hidden_size=self.text_embedder_hidden_size					,				image_size=2_2_4					,				projection_dim=self.text_embedder_hidden_size					,				intermediate_size=3_7					,				num_attention_heads=4					,				num_channels=3					,				num_hidden_layers=5					,				patch_size=1_4					,				)

           lowerCAmelCase					:	Union[str, Any]       =   CLIPVisionModelWithProjection(UpperCamelCase_				)
           return model






     @property
     def      lowerCamelCase__     (	self  :					Optional[int]				):
           lowerCAmelCase					:	Dict       =   CLIPImageProcessor(
               crop_size=2_2_4					,				do_center_crop=UpperCamelCase_					,				do_normalize=UpperCamelCase_					,				do_resize=UpperCamelCase_					,				image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]					,				image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]					,				resample=3					,				size=2_2_4					,				)

           return image_processor






     def      lowerCamelCase__     (	self  :					Optional[int]				):
           lowerCAmelCase					:	Optional[int]       =   self.dummy_prior
           lowerCAmelCase					:	List[str]       =   self.dummy_image_encoder
           lowerCAmelCase					:	Tuple       =   self.dummy_text_encoder
           lowerCAmelCase					:	List[Any]       =   self.dummy_tokenizer
           lowerCAmelCase					:	List[str]       =   self.dummy_image_processor

           lowerCAmelCase					:	Optional[int]       =   UnCLIPScheduler(
               variance_type='''fixed_small_log'''					,				prediction_type='''sample'''					,				num_train_timesteps=1_0_0_0					,				clip_sample=UpperCamelCase_					,				clip_sample_range=10.0					,				)

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

           return components






     def      lowerCamelCase__     (	self  :					Dict					,				UpperCamelCase_  :					Union[str, Any]					,				UpperCamelCase_  :					Tuple=0				):
           if str(UpperCamelCase_				).startswith('''mps'''				):
                 lowerCAmelCase					:	Dict       =   torch.manual_seed(UpperCamelCase_				)
           else:
                 lowerCAmelCase					:	List[Any]       =   torch.Generator(device=UpperCamelCase_				).manual_seed(UpperCamelCase_				)
           lowerCAmelCase					:	str       =   {
               '''prompt''': '''horse''',
               '''generator''': generator,
               '''guidance_scale''': 4.0,
               '''num_inference_steps''': 2,
               '''output_type''': '''np''',
           }
           return inputs






     def      lowerCamelCase__     (	self  :					Tuple				):
           lowerCAmelCase					:	Optional[Any]       =   '''cpu'''

           lowerCAmelCase					:	List[str]       =   self.get_dummy_components()

           lowerCAmelCase					:	List[Any]       =   self.pipeline_class(**UpperCamelCase_				)
           lowerCAmelCase					:	List[str]       =   pipe.to(UpperCamelCase_				)

           pipe.set_progress_bar_config(disable=UpperCamelCase_				)

           lowerCAmelCase					:	Any       =   pipe(**self.get_dummy_inputs(UpperCamelCase_				)				)
           lowerCAmelCase					:	Tuple       =   output.image_embeds

           lowerCAmelCase					:	Optional[int]       =   pipe(
               **self.get_dummy_inputs(UpperCamelCase_				)					,				return_dict=UpperCamelCase_					,				)[0]

           lowerCAmelCase					:	Dict       =   image[0, -1_0:]
           lowerCAmelCase					:	str       =   image_from_tuple[0, -1_0:]

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

           lowerCAmelCase					:	List[str]       =   np.array(
               [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]				)

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

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






     @skip_mps
     def      lowerCamelCase__     (	self  :					Optional[int]				):
           lowerCAmelCase					:	List[Any]       =   torch_device == '''cpu'''
           lowerCAmelCase					:	Tuple       =   False

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






"""simple docstring"""





from __future__ import annotations

from PIL import Image

# Define glider example
snake_case__		:     int    				=				[
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

# Define blinker example
snake_case__		:     Any    				=				[[0, 1, 0], [0, 1, 0], [0, 1, 0]]


def      _snake_case						(						_snake_case				:			list[list[int]]			):
      lowerCAmelCase					:	Union[str, Any]       =   []
      for i in range(len(_snake_case			)			):
            lowerCAmelCase					:	Any       =   []
            for j in range(len(cells[i]			)			):
                  # Get the number of live neighbours
                  lowerCAmelCase					:	Optional[int]       =   0
                  if i > 0 and j > 0:
                        neighbour_count += cells[i - 1][j - 1]
                  if i > 0:
                        neighbour_count += cells[i - 1][j]
                  if i > 0 and j < len(cells[i]			) - 1:
                        neighbour_count += cells[i - 1][j + 1]
                  if j > 0:
                        neighbour_count += cells[i][j - 1]
                  if j < len(cells[i]			) - 1:
                        neighbour_count += cells[i][j + 1]
                  if i < len(_snake_case			) - 1 and j > 0:
                        neighbour_count += cells[i + 1][j - 1]
                  if i < len(_snake_case			) - 1:
                        neighbour_count += cells[i + 1][j]
                  if i < len(_snake_case			) - 1 and j < len(cells[i]			) - 1:
                        neighbour_count += cells[i + 1][j + 1]

                  # Rules of the game of life (excerpt from Wikipedia):
                  # 1. Any live cell with two or three live neighbours survives.
                  # 2. Any dead cell with three live neighbours becomes a live cell.
                  # 3. All other live cells die in the next generation.
                  #    Similarly, all other dead cells stay dead.
                  lowerCAmelCase					:	str       =   cells[i][j] == 1
                  if (
                      (alive and 2 <= neighbour_count <= 3)
                      or not alive
                      and neighbour_count == 3
                  ):
                        next_generation_row.append(1			)
                  else:
                        next_generation_row.append(0			)

            next_generation.append(_snake_case			)
      return next_generation


def      _snake_case						(						_snake_case				:			list[list[int]] ,   _snake_case				:			int			):
      lowerCAmelCase					:	int       =   []
      for _ in range(_snake_case			):
            # Create output image
            lowerCAmelCase					:	Union[str, Any]       =   Image.new('''RGB''' ,   (len(cells[0]			), len(_snake_case			))			)
            lowerCAmelCase					:	Union[str, Any]       =   img.load()

            # Save cells to image
            for x in range(len(_snake_case			)			):
                  for y in range(len(cells[0]			)			):
                        lowerCAmelCase					:	Optional[int]       =   255 - cells[y][x] * 255
                        lowerCAmelCase					:	List[Any]       =   (colour, colour, colour)

        # Save image
            images.append(_snake_case			)
            lowerCAmelCase					:	Union[str, Any]       =   new_generation(_snake_case			)
      return images


if __name__ == "__main__":
 snake_case__		:     Union[str, Any]    				=				generate_images(GLIDER, 16)
 images[0].save('''out.gif''', save_all=True, append_images=images[1:])


