






import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


_a    :   List[str]        =			get_logger(__name__)







class 	_UpperCAmelCase  :




      """simple docstring"""



      def __init__(   self    ,	_lowerCAmelCase = None		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				(
              os.path.join(_lowerCAmelCase    ,	config.EXTRACTED_DATASETS_DIR		) if cache_dir else config.EXTRACTED_DATASETS_PATH
          )
          lowerCAmelCase__   :str      							=				Extractor
      def 			snake_case_      (   self    ,	_lowerCAmelCase		):



          '''simple docstring'''
          from .file_utils import hash_url_to_filename

          # Path where we extract compressed archives
          # We extract in the cache dir, and get the extracted path name by hashing the original path"
          lowerCAmelCase__   :List[Any]      							=				os.path.abspath(_lowerCAmelCase		)
          return os.path.join(self.extract_dir    ,	hash_url_to_filename(_lowerCAmelCase		)		)
      def 			snake_case_      (   self    ,	_lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          return force_extract or (
              not os.path.isfile(_lowerCAmelCase		) and not (os.path.isdir(_lowerCAmelCase		) and os.listdir(_lowerCAmelCase		))
          )



      def 			snake_case_      (   self    ,	_lowerCAmelCase    ,	_lowerCAmelCase = False		):



          '''simple docstring'''
          lowerCAmelCase__   :str      							=				self.extractor.infer_extractor_format(_lowerCAmelCase		)
          if not extractor_format:
              return input_path
          lowerCAmelCase__   :int      							=				self._get_output_path(_lowerCAmelCase		)
          if self._do_extract(_lowerCAmelCase    ,	_lowerCAmelCase		):
              self.extractor.extract(_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase		)
          return output_path







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      @classmethod
      @abstractmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          ...



      @staticmethod
      @abstractmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          ...







class 	_UpperCAmelCase  (  _A				,							_A		):




      """simple docstring"""



      A          =    []
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          with open(_lowerCAmelCase    ,	"rb"		) as f:
              return f.read(_lowerCAmelCase		)



      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	_lowerCAmelCase = b""		):



          '''simple docstring'''
          if not magic_number:
              lowerCAmelCase__   :int      							=				max(len(_lowerCAmelCase		) for cls_magic_number in cls.magic_numbers		)
              try:
                  lowerCAmelCase__   :List[str]      							=				cls.read_magic_number(_lowerCAmelCase    ,	_lowerCAmelCase		)
              except OSError:
                  return False
          return any(magic_number.startswith(_lowerCAmelCase		) for cls_magic_number in cls.magic_numbers		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          return tarfile.is_tarfile(_lowerCAmelCase		)
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''

          def resolved(_lowerCAmelCase		) -> str:
              return os.path.realpath(os.path.abspath(_lowerCAmelCase		)		)

          def badpath(_lowerCAmelCase    ,	_lowerCAmelCase		) -> bool:
              # joinpath will ignore base if path is absolute
              return not resolved(os.path.join(_lowerCAmelCase    ,	_lowerCAmelCase		)		).startswith(_lowerCAmelCase		)

          def badlink(_lowerCAmelCase    ,	_lowerCAmelCase		) -> bool:
              # Links are interpreted relative to the directory containing the link
              lowerCAmelCase__   :Any      							=				resolved(os.path.join(_lowerCAmelCase    ,	os.path.dirname(info.name		)		)		)
              return badpath(info.linkname    ,	base=_lowerCAmelCase		)

          lowerCAmelCase__   :int      							=				resolved(_lowerCAmelCase		)

          for finfo in members:
              if badpath(finfo.name    ,	_lowerCAmelCase		):
                  logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)'''		)
              elif finfo.issym() and badlink(_lowerCAmelCase    ,	_lowerCAmelCase		):
                  logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'''		)
              elif finfo.islnk() and badlink(_lowerCAmelCase    ,	_lowerCAmelCase		):
                  logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'''		)
              else:
                  yield finfo



      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          os.makedirs(_lowerCAmelCase    ,	exist_ok=_lowerCAmelCase		)
          lowerCAmelCase__   :str      							=				tarfile.open(_lowerCAmelCase		)
          tar_file.extractall(_lowerCAmelCase    ,	members=TarExtractor.safemembers(_lowerCAmelCase    ,	_lowerCAmelCase		)		)
          tar_file.close()







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\x1F\x8B''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          with gzip.open(_lowerCAmelCase    ,	"rb"		) as gzip_file:
              with open(_lowerCAmelCase    ,	"wb"		) as extracted_file:
                  shutil.copyfileobj(_lowerCAmelCase    ,	_lowerCAmelCase		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [
          b'''PK\x03\x04''',
          b'''PK\x05\x06''',  # empty archive
          b'''PK\x07\x08''',  # spanned archive
      ]
      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	_lowerCAmelCase = b""		):



          '''simple docstring'''
          if super().is_extractable(_lowerCAmelCase    ,	magic_number=_lowerCAmelCase		):
              return True
          try:
              # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
              # From: https://github.com/python/cpython/pull/5053
              from zipfile import (
                  _CD_SIGNATURE,
                  _ECD_DISK_NUMBER,
                  _ECD_DISK_START,
                  _ECD_ENTRIES_TOTAL,
                  _ECD_OFFSET,
                  _ECD_SIZE,
                  _EndRecData,
                  sizeCentralDir,
                  stringCentralDir,
                  structCentralDir,
              )

              with open(_lowerCAmelCase    ,	"rb"		) as fp:
                  lowerCAmelCase__   :str      							=				_EndRecData(_lowerCAmelCase		)
                  if endrec:
                      if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
                          return True  # Empty zipfiles are still zipfiles
                      elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
                          fp.seek(endrec[_ECD_OFFSET]		)  # Central directory is on the same disk
                          if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
                              lowerCAmelCase__   :str      							=				fp.read(_lowerCAmelCase		)  # CD is where we expect it to be
                              if len(_lowerCAmelCase		) == sizeCentralDir:
                                  lowerCAmelCase__   :Dict      							=				struct.unpack(_lowerCAmelCase    ,	_lowerCAmelCase		)  # CD is the right size
                                  if centdir[_CD_SIGNATURE] == stringCentralDir:
                                      return True  # First central directory entry  has correct magic number
              return False
          except Exception:  # catch all errors in case future python versions change the zipfile internals
              return False



      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          os.makedirs(_lowerCAmelCase    ,	exist_ok=_lowerCAmelCase		)
          with zipfile.ZipFile(_lowerCAmelCase    ,	"r"		) as zip_file:
              zip_file.extractall(_lowerCAmelCase		)
              zip_file.close()







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\xFD\x37\x7A\x58\x5A\x00''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          with lzma.open(_lowerCAmelCase		) as compressed_file:
              with open(_lowerCAmelCase    ,	"wb"		) as extracted_file:
                  shutil.copyfileobj(_lowerCAmelCase    ,	_lowerCAmelCase		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          if not config.RARFILE_AVAILABLE:
              raise ImportError("Please pip install rarfile"		)
          import rarfile

          os.makedirs(_lowerCAmelCase    ,	exist_ok=_lowerCAmelCase		)
          lowerCAmelCase__   :Dict      							=				rarfile.RarFile(_lowerCAmelCase		)
          rf.extractall(_lowerCAmelCase		)
          rf.close()







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\x28\xb5\x2F\xFD''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          if not config.ZSTANDARD_AVAILABLE:
              raise ImportError("Please pip install zstandard"		)
          import zstandard as zstd

          lowerCAmelCase__   :Optional[int]      							=				zstd.ZstdDecompressor()
          with open(_lowerCAmelCase    ,	"rb"		) as ifh, open(_lowerCAmelCase    ,	"wb"		) as ofh:
              dctx.copy_stream(_lowerCAmelCase    ,	_lowerCAmelCase		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\x42\x5A\x68''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          with bza.open(_lowerCAmelCase    ,	"rb"		) as compressed_file:
              with open(_lowerCAmelCase    ,	"wb"		) as extracted_file:
                  shutil.copyfileobj(_lowerCAmelCase    ,	_lowerCAmelCase		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\x37\x7A\xBC\xAF\x27\x1C''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          if not config.PY7ZR_AVAILABLE:
              raise ImportError("Please pip install py7zr"		)
          import pyazr

          os.makedirs(_lowerCAmelCase    ,	exist_ok=_lowerCAmelCase		)
          with pyazr.SevenZipFile(_lowerCAmelCase    ,	"r"		) as archive:
              archive.extractall(_lowerCAmelCase		)







class 	_UpperCAmelCase  (  _A		):




      """simple docstring"""



      A          =    [b'''\x04\x22\x4D\x18''']
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          if not config.LZ4_AVAILABLE:
              raise ImportError("Please pip install lz4"		)
          import lza.frame

          with lza.frame.open(_lowerCAmelCase    ,	"rb"		) as compressed_file:
              with open(_lowerCAmelCase    ,	"wb"		) as extracted_file:
                  shutil.copyfileobj(_lowerCAmelCase    ,	_lowerCAmelCase		)







class 	_UpperCAmelCase  :




      """simple docstring"""



      A          =    {
          "tar": TarExtractor,
          "gzip": GzipExtractor,
          "zip": ZipExtractor,
          "xz": XzExtractor,
          "rar": RarExtractor,
          "zstd": ZstdExtractor,
          "bz2": BzipaExtractor,
          "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
          "lz4": LzaExtractor,  # <Added version="2.4.0"/>
      }
      @classmethod
      def 			snake_case_      (   cls		):



          '''simple docstring'''
          return max(
              len(_lowerCAmelCase		)
              for extractor in cls.extractors.values()
              if issubclass(_lowerCAmelCase    ,	_lowerCAmelCase		)
              for extractor_magic_number in extractor.magic_numbers		)
      @staticmethod
      def 			snake_case_      (   _lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          try:
              return MagicNumberBaseExtractor.read_magic_number(_lowerCAmelCase    ,	magic_number_length=_lowerCAmelCase		)
          except OSError:
              return b""
      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	_lowerCAmelCase = False		):



          '''simple docstring'''
          warnings.warn(
              "Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
              "Use 'infer_extractor_format' instead."    ,	category=_lowerCAmelCase    ,	)
          lowerCAmelCase__   :str      							=				cls.infer_extractor_format(_lowerCAmelCase		)
          if extractor_format:
              return True if not return_extractor else (True, cls.extractors[extractor_format])
          return False if not return_extractor else (False, None)
      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase		):  # <Added version="2.4.0"/>



          '''simple docstring'''
          lowerCAmelCase__   :str      							=				cls._get_magic_number_max_length()
          lowerCAmelCase__   :Optional[int]      							=				cls._read_magic_number(_lowerCAmelCase    ,	_lowerCAmelCase		)
          for extractor_format, extractor in cls.extractors.items():
              if extractor.is_extractable(_lowerCAmelCase    ,	magic_number=_lowerCAmelCase		):
                  return extractor_format



      @classmethod
      def 			snake_case_      (   cls    ,	_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase = None    ,	_lowerCAmelCase = "deprecated"    ,	):



          '''simple docstring'''
          os.makedirs(os.path.dirname(_lowerCAmelCase		)    ,	exist_ok=_lowerCAmelCase		)
          # Prevent parallel extractions
          lowerCAmelCase__   :Union[str, Any]      							=				str(Path(_lowerCAmelCase		).with_suffix(".lock"		)		)
          with FileLock(_lowerCAmelCase		):
              shutil.rmtree(_lowerCAmelCase    ,	ignore_errors=_lowerCAmelCase		)
              if extractor_format or extractor != "deprecated":
                  if extractor != "deprecated" or not isinstance(_lowerCAmelCase    ,	_lowerCAmelCase		):  # passed as positional arg
                      warnings.warn(
                          "Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
                          "Use 'extractor_format' instead."    ,	category=_lowerCAmelCase    ,	)
                      lowerCAmelCase__   :Optional[Any]      							=				extractor if extractor != "deprecated" else extractor_format
                  else:
                      lowerCAmelCase__   :List[Any]      							=				cls.extractors[extractor_format]
                  return extractor.extract(_lowerCAmelCase    ,	_lowerCAmelCase		)
              else:
                  warnings.warn(
                      "Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an "
                      "exception in 3.0.0."    ,	category=_lowerCAmelCase    ,	)
                  for extractor in cls.extractors.values():
                      if extractor.is_extractable(_lowerCAmelCase		):
                          return extractor.extract(_lowerCAmelCase    ,	_lowerCAmelCase		)











import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
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		):




      """simple docstring"""



      A          =    KandinskyVaaPipeline
      A          =    [
          '''image_embeds''',
          '''negative_image_embeds''',
      ]
      A          =    ['''image_embeds''', '''negative_image_embeds''']
      A          =    [
          '''generator''',
          '''height''',
          '''width''',
          '''latents''',
          '''guidance_scale''',
          '''num_inference_steps''',
          '''return_dict''',
          '''guidance_scale''',
          '''num_images_per_prompt''',
          '''output_type''',
          '''return_dict''',
      ]
      A          =    False
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return 32
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return 32
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return self.time_input_dim
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return self.time_input_dim * 4
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return 100
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          torch.manual_seed(0		)

          lowerCAmelCase__   :List[str]      							=				{
              "in_channels": 4,
              # Out channels is double in channels because predicts mean and variance
              "out_channels": 8,
              "addition_embed_type": "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": "image_proj",
              "cross_attention_dim": self.cross_attention_dim,
              "attention_head_dim": 4,
              "resnet_time_scale_shift": "scale_shift",
              "class_embed_type": None,
          }

          lowerCAmelCase__   :List[str]      							=				UNetaDConditionModel(**_lowerCAmelCase		)
          return model
      @property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          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 			snake_case_      (   self		):



          '''simple docstring'''
          torch.manual_seed(0		)
          lowerCAmelCase__   :Optional[Any]      							=				VQModel(**self.dummy_movq_kwargs		)
          return model
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				self.dummy_unet
          lowerCAmelCase__   :List[str]      							=				self.dummy_movq

          lowerCAmelCase__   :List[Any]      							=				DDIMScheduler(
              num_train_timesteps=1_000    ,	beta_schedule="linear"    ,	beta_start=0.0_0085    ,	beta_end=0.012    ,	clip_sample=_lowerCAmelCase    ,	set_alpha_to_one=_lowerCAmelCase    ,	steps_offset=1    ,	prediction_type="epsilon"    ,	thresholding=_lowerCAmelCase    ,	)

          lowerCAmelCase__   :Optional[Any]      							=				{
              "unet": unet,
              "scheduler": scheduler,
              "movq": movq,
          }
          return components
      def 			snake_case_      (   self    ,	_lowerCAmelCase    ,	_lowerCAmelCase=0		):



          '''simple docstring'''
          lowerCAmelCase__   :List[Any]      							=				floats_tensor((1, self.text_embedder_hidden_size)    ,	rng=random.Random(_lowerCAmelCase		)		).to(_lowerCAmelCase		)
          lowerCAmelCase__   :Any      							=				floats_tensor((1, self.text_embedder_hidden_size)    ,	rng=random.Random(seed + 1		)		).to(
              _lowerCAmelCase		)
          if str(_lowerCAmelCase		).startswith("mps"		):
              lowerCAmelCase__   :List[Any]      							=				torch.manual_seed(_lowerCAmelCase		)
          else:
              lowerCAmelCase__   :Optional[int]      							=				torch.Generator(device=_lowerCAmelCase		).manual_seed(_lowerCAmelCase		)
          lowerCAmelCase__   :Optional[int]      							=				{
              "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 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				"cpu"

          lowerCAmelCase__   :Dict      							=				self.get_dummy_components()

          lowerCAmelCase__   :Tuple      							=				self.pipeline_class(**_lowerCAmelCase		)
          lowerCAmelCase__   :List[Any]      							=				pipe.to(_lowerCAmelCase		)

          pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

          lowerCAmelCase__   :str      							=				pipe(**self.get_dummy_inputs(_lowerCAmelCase		)		)
          lowerCAmelCase__   :Dict      							=				output.images

          lowerCAmelCase__   :str      							=				pipe(
              **self.get_dummy_inputs(_lowerCAmelCase		)    ,	return_dict=_lowerCAmelCase    ,	)[0]

          lowerCAmelCase__   :Tuple      							=				image[0, -3:, -3:, -1]
          lowerCAmelCase__   :List[Any]      							=				image_from_tuple[0, -3:, -3:, -1]

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

          lowerCAmelCase__   :Tuple      							=				np.array(
              [0.623_7976, 1.0, 0.3644_1332, 1.0, 0.7063_9634, 0.2987_7186, 0.8565_2125, 0.521_6843, 0.5445_4046]		)

          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		):




      """simple docstring"""



      def 			snake_case_      (   self		):



          '''simple docstring'''
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()



      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				load_numpy(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"		)

          lowerCAmelCase__   :str      							=				KandinskyVaaPriorPipeline.from_pretrained(
              "kandinsky-community/kandinsky-2-2-prior"    ,	torch_dtype=torch.floataa		)
          pipe_prior.to(_lowerCAmelCase		)

          lowerCAmelCase__   :str      							=				KandinskyVaaPipeline.from_pretrained(
              "kandinsky-community/kandinsky-2-2-decoder"    ,	torch_dtype=torch.floataa		)
          lowerCAmelCase__   :Union[str, Any]      							=				pipeline.to(_lowerCAmelCase		)
          pipeline.set_progress_bar_config(disable=_lowerCAmelCase		)

          lowerCAmelCase__   :Optional[int]      							=				"red cat, 4k photo"

          lowerCAmelCase__   :Tuple      							=				torch.Generator(device="cuda"		).manual_seed(0		)
          lowerCAmelCase__							,lowerCAmelCase__   :Dict      							=				pipe_prior(
              _lowerCAmelCase    ,	generator=_lowerCAmelCase    ,	num_inference_steps=5    ,	negative_prompt=""    ,	).to_tuple()

          lowerCAmelCase__   :List[Any]      							=				torch.Generator(device="cuda"		).manual_seed(0		)
          lowerCAmelCase__   :List[str]      							=				pipeline(
              image_embeds=_lowerCAmelCase    ,	negative_image_embeds=_lowerCAmelCase    ,	generator=_lowerCAmelCase    ,	num_inference_steps=100    ,	output_type="np"    ,	)

          lowerCAmelCase__   :int      							=				output.images[0]

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

          assert_mean_pixel_difference(_lowerCAmelCase    ,	_lowerCAmelCase		)



