import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()







class 					UpperCAmelCase_				(							_a     ,     unittest.TestCase    ):
    UpperCAmelCase_			:       Optional[Any]						 =							KandinskyPipeline
    UpperCAmelCase_			:       Dict						 =							[
        'prompt',
        'image_embeds',
        'negative_image_embeds',
    ]
    UpperCAmelCase_			:       List[Any]						 =							['prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds']
    UpperCAmelCase_			:       int						 =							[
        'generator',
        'height',
        'width',
        'latents',
        'guidance_scale',
        'negative_prompt',
        'num_inference_steps',
        'return_dict',
        'guidance_scale',
        'num_images_per_prompt',
        'output_type',
        'return_dict',
    ]
    UpperCAmelCase_			:       Optional[Any]						 =							False




    @property
    def 						__lowerCamelCase (					self  :   str   )	-> Tuple:
      return 32




    @property
    def 						__lowerCamelCase (					self  :   List[str]   )	-> str:
      return 32




    @property
    def 						__lowerCamelCase (					self  :   str   )	-> str:
      return self.time_input_dim




    @property
    def 						__lowerCamelCase (					self  :   List[str]   )	-> Tuple:
      return self.time_input_dim * 4




    @property
    def 						__lowerCamelCase (					self  :   Optional[int]   )	-> Dict:
      return 100




    @property
    def 						__lowerCamelCase (					self  :   List[Any]   )	-> Any:
      a__     		=     XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"   )
      return tokenizer




    @property
    def 						__lowerCamelCase (					self  :   str   )	-> Tuple:
      torch.manual_seed(0   )
      a__     		=     MCLIPConfig(
          numDims=self.cross_attention_dim      ,      transformerDimensions=self.text_embedder_hidden_size      ,      hidden_size=self.text_embedder_hidden_size      ,      intermediate_size=37      ,      num_attention_heads=4      ,      num_hidden_layers=5      ,      vocab_size=1005      ,      )

      a__     		=     MultilingualCLIP(lowerCAmelCase   )
      a__     		=     text_encoder.eval()

      return text_encoder




    @property
    def 						__lowerCamelCase (					self  :   int   )	-> List[Any]:
      torch.manual_seed(0   )

      a__     		=     {
          "in_channels": 4,
          # Out channels is double in channels because predicts mean and variance
          "out_channels": 8,
          "addition_embed_type": "text_image",
          "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
          "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
          "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
          "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
          "layers_per_block": 1,
          "encoder_hid_dim": self.text_embedder_hidden_size,
          "encoder_hid_dim_type": "text_image_proj",
          "cross_attention_dim": self.cross_attention_dim,
          "attention_head_dim": 4,
          "resnet_time_scale_shift": "scale_shift",
          "class_embed_type": None,
      }

      a__     		=     UNetaDConditionModel(**lowerCAmelCase   )
      return model




    @property
    def 						__lowerCamelCase (					self  :   List[Any]   )	-> Optional[Any]:
      return {
          "block_out_channels": [32, 64],
          "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
          "in_channels": 3,
          "latent_channels": 4,
          "layers_per_block": 1,
          "norm_num_groups": 8,
          "norm_type": "spatial",
          "num_vq_embeddings": 12,
          "out_channels": 3,
          "up_block_types": [
              "AttnUpDecoderBlock2D",
              "UpDecoderBlock2D",
          ],
          "vq_embed_dim": 4,
      }




    @property
    def 						__lowerCamelCase (					self  :   str   )	-> int:
      torch.manual_seed(0   )
      a__     		=     VQModel(**self.dummy_movq_kwargs   )
      return model




    def 						__lowerCamelCase (					self  :   Dict   )	-> int:
      a__     		=     self.dummy_text_encoder
      a__     		=     self.dummy_tokenizer
      a__     		=     self.dummy_unet
      a__     		=     self.dummy_movq

      a__     		=     DDIMScheduler(
          num_train_timesteps=1000      ,      beta_schedule="linear"      ,      beta_start=0.00_085      ,      beta_end=0.012      ,      clip_sample=lowerCAmelCase      ,      set_alpha_to_one=lowerCAmelCase      ,      steps_offset=1      ,      prediction_type="epsilon"      ,      thresholding=lowerCAmelCase      ,      )

      a__     		=     {
          "text_encoder": text_encoder,
          "tokenizer": tokenizer,
          "unet": unet,
          "scheduler": scheduler,
          "movq": movq,
      }
      return components




    def 						__lowerCamelCase (					self  :   List[Any]      ,      lowerCAmelCase  :   int      ,      lowerCAmelCase  :   Optional[Any]=0   )	-> Union[str, Any]:
      a__     		=     floats_tensor((1, self.cross_attention_dim)      ,      rng=random.Random(lowerCAmelCase   )   ).to(lowerCAmelCase   )
      a__     		=     floats_tensor((1, self.cross_attention_dim)      ,      rng=random.Random(seed + 1   )   ).to(lowerCAmelCase   )
      if str(lowerCAmelCase   ).startswith("mps"   ):
        a__     		=     torch.manual_seed(lowerCAmelCase   )
      else:
        a__     		=     torch.Generator(device=lowerCAmelCase   ).manual_seed(lowerCAmelCase   )
      a__     		=     {
          "prompt": "horse",
          "image_embeds": image_embeds,
          "negative_image_embeds": negative_image_embeds,
          "generator": generator,
          "height": 64,
          "width": 64,
          "guidance_scale": 4.0,
          "num_inference_steps": 2,
          "output_type": "np",
      }
      return inputs




    def 						__lowerCamelCase (					self  :   str   )	-> Optional[int]:
      a__     		=     "cpu"

      a__     		=     self.get_dummy_components()

      a__     		=     self.pipeline_class(**lowerCAmelCase   )
      a__     		=     pipe.to(lowerCAmelCase   )

      pipe.set_progress_bar_config(disable=lowerCAmelCase   )

      a__     		=     pipe(**self.get_dummy_inputs(lowerCAmelCase   )   )
      a__     		=     output.images

      a__     		=     pipe(
          **self.get_dummy_inputs(lowerCAmelCase   )      ,      return_dict=lowerCAmelCase      ,      )[0]

      a__     		=     image[0, -3:, -3:, -1]
      a__     		=     image_from_tuple[0, -3:, -3:, -1]

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

      a__     		=     np.array(
          [0.328_663, 1.0, 0.23_216_873, 1.0, 0.92_717_564, 0.4_639_046, 0.96_894_777, 0.31_713_378, 0.6_293_953]   )

      assert (
          np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
      ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
      assert (
          np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1e-2
      ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"







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




    def 						__lowerCamelCase (					self  :   str   )	-> List[str]:
      # clean up the VRAM after each test
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()




    def 						__lowerCamelCase (					self  :   Optional[Any]   )	-> Optional[Any]:
      a__     		=     load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/kandinsky/kandinsky_text2img_cat_fp16.npy"   )

      a__     		=     KandinskyPriorPipeline.from_pretrained(
          "kandinsky-community/kandinsky-2-1-prior"      ,      torch_dtype=torch.floataa   )
      pipe_prior.to(lowerCAmelCase   )

      a__     		=     KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1"      ,      torch_dtype=torch.floataa   )
      a__     		=     pipeline.to(lowerCAmelCase   )
      pipeline.set_progress_bar_config(disable=lowerCAmelCase   )

      a__     		=     "red cat, 4k photo"

      a__     		=     torch.Generator(device="cuda"   ).manual_seed(0   )
      a__		,a__     		=     pipe_prior(
          lowerCAmelCase      ,      generator=lowerCAmelCase      ,      num_inference_steps=5      ,      negative_prompt=""      ,      ).to_tuple()

      a__     		=     torch.Generator(device="cuda"   ).manual_seed(0   )
      a__     		=     pipeline(
          lowerCAmelCase      ,      image_embeds=lowerCAmelCase      ,      negative_image_embeds=lowerCAmelCase      ,      generator=lowerCAmelCase      ,      num_inference_steps=100      ,      output_type="np"      ,      )

      a__     		=     output.images[0]

      assert image.shape == (512, 512, 3)

      assert_mean_pixel_difference(lowerCAmelCase      ,      lowerCAmelCase   )


from unittest.mock import patch

import datasets
from datasets import Dataset
def 				__lowercase	(						)				->Union[str, Any]:

  '''simple docstring'''




  a__     		=     Dataset.from_dict({"col_1": [3, 2, 0, 1]}					)

  with patch("tqdm.auto.tqdm"					) as mock_tqdm:
    datasets.disable_progress_bar()
    dset.map(lambda lowerCamelCase__					: {"col_2": x["col_1"] + 1}					)
    mock_tqdm.assert_not_called()

    mock_tqdm.reset_mock()

    datasets.enable_progress_bar()
    dset.map(lambda lowerCamelCase__					: {"col_2": x["col_1"] + 1}					)
    mock_tqdm.assert_called()

