"""simple docstring"""





import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


_UpperCamelCase       :						List[Any]     =   get_logger(__name__)

# Datasets
_UpperCamelCase       :						int     =   "https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets"
_UpperCamelCase       :						Tuple     =   "https://cdn-datasets.huggingface.co/datasets/datasets"
_UpperCamelCase       :						int     =   "https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}"

# Metrics
_UpperCamelCase       :						str     =   "https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics"
_UpperCamelCase       :						Optional[Any]     =   "https://cdn-datasets.huggingface.co/datasets/metric"
_UpperCamelCase       :						Optional[Any]     =   "https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}"

# Hub
_UpperCamelCase       :						List[Any]     =   os.environ.get("HF_ENDPOINT", "https://huggingface.co")
_UpperCamelCase       :						int     =   HF_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}"
_UpperCamelCase       :						Tuple     =   "main"

_UpperCamelCase       :						Optional[int]     =   version.parse(platform.python_version())

if PY_VERSION < version.parse("3.8"):
       import importlib_metadata
else:
       import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
_UpperCamelCase       :						List[str]     =   {"1", "ON", "YES", "TRUE"}
_UpperCamelCase       :						Dict     =   ENV_VARS_TRUE_VALUES.union({"AUTO"})


# Imports
_UpperCamelCase       :						Dict     =   version.parse(importlib_metadata.version("dill"))
_UpperCamelCase       :						str     =   version.parse(importlib_metadata.version("pandas"))
_UpperCamelCase       :						int     =   version.parse(importlib_metadata.version("pyarrow"))

_UpperCamelCase       :						int     =   os.environ.get("USE_TF", "AUTO").upper()
_UpperCamelCase       :						List[str]     =   os.environ.get("USE_TORCH", "AUTO").upper()
_UpperCamelCase       :						Union[str, Any]     =   os.environ.get("USE_JAX", "AUTO").upper()

_UpperCamelCase       :						Union[str, Any]     =   "N/A"
_UpperCamelCase       :						List[str]     =   False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
       _UpperCamelCase       :						Any     =   importlib.util.find_spec("torch") is not None
       if TORCH_AVAILABLE:
              try:
                     _UpperCamelCase       :						Tuple     =   version.parse(importlib_metadata.version("torch"))
                     logger.info(f'''PyTorch version {TORCH_VERSION} available.''')
              except importlib_metadata.PackageNotFoundError:
                     pass
else:
       logger.info("Disabling PyTorch because USE_TF is set")

_UpperCamelCase       :						str     =   "N/A"
_UpperCamelCase       :						Any     =   False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
       _UpperCamelCase       :						Union[str, Any]     =   importlib.util.find_spec("tensorflow") is not None
       if TF_AVAILABLE:
              # For the metadata, we have to look for both tensorflow and tensorflow-cpu
              for package in [
                  "tensorflow",
                  "tensorflow-cpu",
                  "tensorflow-gpu",
                  "tf-nightly",
                  "tf-nightly-cpu",
                  "tf-nightly-gpu",
                  "intel-tensorflow",
                  "tensorflow-rocm",
                  "tensorflow-macos",
              ]:
                     try:
                            _UpperCamelCase       :						Optional[Any]     =   version.parse(importlib_metadata.version(package))
                     except importlib_metadata.PackageNotFoundError:
                            continue
                     else:
                            break
              else:
                     _UpperCamelCase       :						str     =   False
       if TF_AVAILABLE:
              if TF_VERSION.major < 2:
                     logger.info(f'''TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.''')
                     _UpperCamelCase       :						str     =   False
              else:
                     logger.info(f'''TensorFlow version {TF_VERSION} available.''')
else:
       logger.info("Disabling Tensorflow because USE_TORCH is set")


_UpperCamelCase       :						int     =   "N/A"
_UpperCamelCase       :						Union[str, Any]     =   False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
       _UpperCamelCase       :						Any     =   importlib.util.find_spec("jax") is not None and importlib.util.find_spec("jaxlib") is not None
       if JAX_AVAILABLE:
              try:
                     _UpperCamelCase       :						Optional[int]     =   version.parse(importlib_metadata.version("jax"))
                     logger.info(f'''JAX version {JAX_VERSION} available.''')
              except importlib_metadata.PackageNotFoundError:
                     pass
else:
       logger.info("Disabling JAX because USE_JAX is set to False")


_UpperCamelCase       :						Optional[int]     =   os.environ.get("USE_BEAM", "AUTO").upper()
_UpperCamelCase       :						Tuple     =   "N/A"
_UpperCamelCase       :						Optional[Any]     =   False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
       try:
              _UpperCamelCase       :						Dict     =   version.parse(importlib_metadata.version("apache_beam"))
              _UpperCamelCase       :						Dict     =   True
              logger.info(f'''Apache Beam version {BEAM_VERSION} available.''')
       except importlib_metadata.PackageNotFoundError:
              pass
else:
       logger.info("Disabling Apache Beam because USE_BEAM is set to False")


# Optional tools for data loading
_UpperCamelCase       :						Any     =   importlib.util.find_spec("sqlalchemy") is not None

# Optional tools for feature decoding
_UpperCamelCase       :						Tuple     =   importlib.util.find_spec("PIL") is not None
_UpperCamelCase       :						Optional[int]     =   importlib.util.find_spec("soundfile") is not None and version.parse(
    importlib.import_module("soundfile").__libsndfile_version__
) >= version.parse("1.0.31")
_UpperCamelCase       :						int     =   importlib.util.find_spec("soundfile") is not None and version.parse(
    importlib.import_module("soundfile").__libsndfile_version__
) >= version.parse("1.1.0")

# Optional compression tools
_UpperCamelCase       :						Any     =   importlib.util.find_spec("rarfile") is not None
_UpperCamelCase       :						Optional[int]     =   importlib.util.find_spec("zstandard") is not None
_UpperCamelCase       :						List[Any]     =   importlib.util.find_spec("lz4") is not None
_UpperCamelCase       :						Tuple     =   importlib.util.find_spec("py7zr") is not None


# Cache location
_UpperCamelCase       :						Tuple     =   "~/.cache"
_UpperCamelCase       :						Optional[Any]     =   os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
_UpperCamelCase       :						List[Any]     =   os.path.join(XDG_CACHE_HOME, "huggingface")
_UpperCamelCase       :						Union[str, Any]     =   os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))

_UpperCamelCase       :						Optional[Any]     =   os.path.join(HF_CACHE_HOME, "datasets")
_UpperCamelCase       :						Any     =   Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE))

_UpperCamelCase       :						Any     =   os.path.join(HF_CACHE_HOME, "metrics")
_UpperCamelCase       :						str     =   Path(os.getenv("HF_METRICS_CACHE", DEFAULT_HF_METRICS_CACHE))

_UpperCamelCase       :						Optional[int]     =   os.path.join(HF_CACHE_HOME, "modules")
_UpperCamelCase       :						List[str]     =   Path(os.getenv("HF_MODULES_CACHE", DEFAULT_HF_MODULES_CACHE))

_UpperCamelCase       :						Tuple     =   "downloads"
_UpperCamelCase       :						List[str]     =   os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
_UpperCamelCase       :						List[Any]     =   Path(os.getenv("HF_DATASETS_DOWNLOADED_DATASETS_PATH", DEFAULT_DOWNLOADED_DATASETS_PATH))

_UpperCamelCase       :						Optional[int]     =   "extracted"
_UpperCamelCase       :						Any     =   os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
_UpperCamelCase       :						Optional[Any]     =   Path(os.getenv("HF_DATASETS_EXTRACTED_DATASETS_PATH", DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
_UpperCamelCase       :						List[Any]     =   (
    os.environ.get("HF_UPDATE_DOWNLOAD_COUNTS", "AUTO").upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
_UpperCamelCase       :						List[str]     =   10_00

# Size of the preloaded record batch in `Dataset.__iter__`
_UpperCamelCase       :						List[str]     =   10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
_UpperCamelCase       :						Optional[Any]     =   4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
_UpperCamelCase       :						Optional[int]     =   "500MB"

# Parquet configuration
_UpperCamelCase       :						int     =   1_00
_UpperCamelCase       :						Optional[Any]     =   1_00
_UpperCamelCase       :						List[Any]     =   1_00

# Offline mode
_UpperCamelCase       :						Optional[int]     =   os.environ.get("HF_DATASETS_OFFLINE", "AUTO").upper() in ENV_VARS_TRUE_VALUES

# In-memory
_UpperCamelCase       :						Tuple     =   0  # Disabled
_UpperCamelCase       :						Dict     =   float(os.environ.get("HF_DATASETS_IN_MEMORY_MAX_SIZE", DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
_UpperCamelCase       :						Dict     =   "dataset.arrow"
_UpperCamelCase       :						Optional[Any]     =   "indices.arrow"
_UpperCamelCase       :						Optional[Any]     =   "state.json"
_UpperCamelCase       :						str     =   "dataset_info.json"
_UpperCamelCase       :						Dict     =   "dataset_infos.json"
_UpperCamelCase       :						Any     =   "LICENSE"
_UpperCamelCase       :						str     =   "metric_info.json"
_UpperCamelCase       :						int     =   "dataset_dict.json"

_UpperCamelCase       :						Optional[int]     =   "datasets_modules"

_UpperCamelCase       :						int     =   2_55

# Streaming
_UpperCamelCase       :						Tuple     =   20
_UpperCamelCase       :						str     =   5

# Datasets without script
_UpperCamelCase       :						Tuple     =   2_00
_UpperCamelCase       :						Optional[Any]     =   10
_UpperCamelCase       :						Tuple     =   2_00

# Progress bars
_UpperCamelCase       :						Union[str, Any]     =   0.0_5  # 20 progress updates per sec


"""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 KandinskyPriorPipeline, 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 					UpperCAmelCase_     (   _a			,							unittest.TestCase):
      lowerCamelCase__		:   Tuple			  =  KandinskyPriorPipeline
      lowerCamelCase__		:   Tuple			  =  ["prompt"]
      lowerCamelCase__		:   List[str]			  =  ["prompt", "negative_prompt"]
      lowerCamelCase__		:   List[Any]			  =  [
          "num_images_per_prompt",
          "generator",
          "num_inference_steps",
          "latents",
          "negative_prompt",
          "guidance_scale",
          "output_type",
          "return_dict",
      ]
      lowerCamelCase__		:   Optional[Any]			  =  False


      @property
      def 		_UpperCAmelCase	(       self							)	-> Union[str, Any]:
             return 3_2


      @property
      def 		_UpperCAmelCase	(       self							)	-> str:
             return 3_2


      @property
      def 		_UpperCAmelCase	(       self							)	-> Optional[Any]:
             return self.time_input_dim


      @property
      def 		_UpperCAmelCase	(       self							)	-> Any:
             return self.time_input_dim * 4


      @property
      def 		_UpperCAmelCase	(       self							)	-> Optional[int]:
             return 1_0_0


      @property
      def 		_UpperCAmelCase	(       self							)	-> List[Any]:
             lowercase__      :		Tuple          =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'							)
             return tokenizer


      @property
      def 		_UpperCAmelCase	(       self							)	-> Any:
             torch.manual_seed(0							)
             lowercase__      :		Optional[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=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(a							)


      @property
      def 		_UpperCAmelCase	(       self							)	-> Union[str, Any]:
             torch.manual_seed(0							)

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

             lowercase__      :		Tuple          =     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__      :		int          =     nn.Parameter(torch.ones(model.clip_std.shape							)							)
             return model


      @property
      def 		_UpperCAmelCase	(       self							)	-> Optional[int]:
             torch.manual_seed(0							)
             lowercase__      :		Optional[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		,      )

             lowercase__      :		Optional[Any]          =     CLIPVisionModelWithProjection(a							)
             return model


      @property
      def 		_UpperCAmelCase	(       self							)	-> Tuple:
             lowercase__      :		Dict          =     CLIPImageProcessor(
                 crop_size=2_2_4		,      do_center_crop=a		,      do_normalize=a		,      do_resize=a		,      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 		_UpperCAmelCase	(       self							)	-> Dict:
             lowercase__      :		List[str]          =     self.dummy_prior
             lowercase__      :		Tuple          =     self.dummy_image_encoder
             lowercase__      :		Optional[Any]          =     self.dummy_text_encoder
             lowercase__      :		List[str]          =     self.dummy_tokenizer
             lowercase__      :		Optional[int]          =     self.dummy_image_processor

             lowercase__      :		List[Any]          =     UnCLIPScheduler(
                 variance_type='fixed_small_log'		,      prediction_type='sample'		,      num_train_timesteps=1_0_0_0		,      clip_sample=a		,      clip_sample_range=10.0		,      )

             lowercase__      :		List[str]          =     {
                 'prior': prior,
                 'image_encoder': image_encoder,
                 'text_encoder': text_encoder,
                 'tokenizer': tokenizer,
                 'scheduler': scheduler,
                 'image_processor': image_processor,
             }

             return components


      def 		_UpperCAmelCase	(       self		,      a		,      a=0							)	-> Union[str, Any]:
             if str(a							).startswith('mps'							):
                    lowercase__      :		Optional[Any]          =     torch.manual_seed(a							)
             else:
                    lowercase__      :		Any          =     torch.Generator(device=a							).manual_seed(a							)
             lowercase__      :		str          =     {
                 'prompt': 'horse',
                 'generator': generator,
                 'guidance_scale': 4.0,
                 'num_inference_steps': 2,
                 'output_type': 'np',
             }
             return inputs


      def 		_UpperCAmelCase	(       self							)	-> Dict:
             lowercase__      :		Optional[int]          =     'cpu'

             lowercase__      :		Optional[Any]          =     self.get_dummy_components()

             lowercase__      :		Optional[Any]          =     self.pipeline_class(**a							)
             lowercase__      :		Optional[int]          =     pipe.to(a							)

             pipe.set_progress_bar_config(disable=a							)

             lowercase__      :		Optional[int]          =     pipe(**self.get_dummy_inputs(a							)							)
             lowercase__      :		Optional[Any]          =     output.image_embeds

             lowercase__      :		Dict          =     pipe(
                 **self.get_dummy_inputs(a							)		,      return_dict=a		,      )[0]

             lowercase__      :		List[str]          =     image[0, -1_0:]
             lowercase__      :		Optional[Any]          =     image_from_tuple[0, -1_0:]

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

             lowercase__      :		Union[str, Any]          =     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 		_UpperCAmelCase	(       self							)	-> List[Any]:
             lowercase__      :		Tuple          =     torch_device == 'cpu'
             lowercase__      :		Union[str, Any]          =     True
             lowercase__      :		int          =     False

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


      @skip_mps
      def 		_UpperCAmelCase	(       self							)	-> int:
             lowercase__      :		Tuple          =     torch_device == 'cpu'
             lowercase__      :		Any          =     False

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

