



"""simple docstring"""
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


SCREAMING_SNAKE_CASE_				= datasets.utils.logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_				= ["""names""", """prefix"""]
SCREAMING_SNAKE_CASE_				= ["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
SCREAMING_SNAKE_CASE_				= ["""encoding_errors""", """on_bad_lines"""]
SCREAMING_SNAKE_CASE_				= ["""date_format"""]




@dataclass
class 			snake_case_						(						datasets.BuilderConfig				):
							__lowerCAmelCase    					=					","
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					"infer"
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					False
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					False
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					"."
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					"\""
							__lowerCAmelCase    					=					0
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					0
							__lowerCAmelCase    					=					True
							__lowerCAmelCase    					=					False
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					1_0_0_0_0
							__lowerCAmelCase    					=					None
							__lowerCAmelCase    					=					"strict"
							__lowerCAmelCase    					=					"error"
							__lowerCAmelCase    					=					None






							def snake_case_  (   self      ):
									if self.delimiter is not None:
											a_     :      Dict 						=     self.delimiter
									if self.column_names is not None:
											a_     :      int 						=     self.column_names






							@property
							def snake_case_  (   self      ):
									a_     :      Optional[Any] 						=     {
									    "sep": self.sep,
									    "header": self.header,
									    "names": self.names,
									    "index_col": self.index_col,
									    "usecols": self.usecols,
									    "prefix": self.prefix,
									    "mangle_dupe_cols": self.mangle_dupe_cols,
									    "engine": self.engine,
									    "converters": self.converters,
									    "true_values": self.true_values,
									    "false_values": self.false_values,
									    "skipinitialspace": self.skipinitialspace,
									    "skiprows": self.skiprows,
									    "nrows": self.nrows,
									    "na_values": self.na_values,
									    "keep_default_na": self.keep_default_na,
									    "na_filter": self.na_filter,
									    "verbose": self.verbose,
									    "skip_blank_lines": self.skip_blank_lines,
									    "thousands": self.thousands,
									    "decimal": self.decimal,
									    "lineterminator": self.lineterminator,
									    "quotechar": self.quotechar,
									    "quoting": self.quoting,
									    "escapechar": self.escapechar,
									    "comment": self.comment,
									    "encoding": self.encoding,
									    "dialect": self.dialect,
									    "error_bad_lines": self.error_bad_lines,
									    "warn_bad_lines": self.warn_bad_lines,
									    "skipfooter": self.skipfooter,
									    "doublequote": self.doublequote,
									    "memory_map": self.memory_map,
									    "float_precision": self.float_precision,
									    "chunksize": self.chunksize,
									    "encoding_errors": self.encoding_errors,
									    "on_bad_lines": self.on_bad_lines,
									    "date_format": self.date_format,
									}

									# some kwargs must not be passed if they don't have a default value
									# some others are deprecated and we can also not pass them if they are the default value
									for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
											if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()			,     a_      ):
													del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
									if not (datasets.config.PANDAS_VERSION.major >= 2):
											for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
													del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
									if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
											for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
													del pd_read_csv_kwargs[pd_read_csv_parameter]

									return pd_read_csv_kwargs




class 			snake_case_						(						datasets.ArrowBasedBuilder				):
							__lowerCAmelCase    					=					CsvConfig






							def snake_case_  (   self      ):
									return datasets.DatasetInfo(features=self.config.features      )






							def snake_case_  (   self			,     a_      ):
									if not self.config.data_files:
											raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""      )
									a_     :      int 						=     dl_manager.download_and_extract(self.config.data_files      )
									if isinstance(a_			,     (str, list, tuple)      ):
											a_     :      List[str] 						=     data_files
											if isinstance(a_			,     a_      ):
													a_     :      Dict 						=     [files]
											a_     :      List[str] 						=     [dl_manager.iter_files(a_      ) for file in files]
											return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,     gen_kwargs={"files": files}      )]
									a_     :      List[str] 						=     []
									for split_name, files in data_files.items():
											if isinstance(a_			,     a_      ):
													a_     :      Optional[int] 						=     [files]
											a_     :      Optional[int] 						=     [dl_manager.iter_files(a_      ) for file in files]
											splits.append(datasets.SplitGenerator(name=a_			,     gen_kwargs={"files": files}      )      )
									return splits






							def snake_case_  (   self			,     a_      ):
									if self.config.features is not None:
											a_     :      str 						=     self.config.features.arrow_schema
											if all(not require_storage_cast(a_      ) for feature in self.config.features.values()      ):
													# cheaper cast
													a_     :      int 						=     pa.Table.from_arrays([pa_table[field.name] for field in schema]			,     schema=a_      )
											else:
													# more expensive cast; allows str <-> int/float or str to Audio for example
													a_     :      str 						=     table_cast(a_			,     a_      )
									return pa_table






							def snake_case_  (   self			,     a_      ):
									a_     :      str 						=     self.config.features.arrow_schema if self.config.features else None
									# dtype allows reading an int column as str
									a_     :      Optional[Any] 						=     (
									    {
									        name: dtype.to_pandas_dtype() if not require_storage_cast(a_      ) else object
									        for name, dtype, feature in zip(schema.names			,     schema.types			,     self.config.features.values()      )
									    }
									    if schema is not None
									    else None
									)
									for file_idx, file in enumerate(itertools.chain.from_iterable(a_      )      ):
											a_     :      Union[str, Any] 						=     pd.read_csv(a_			,     iterator=a_			,     dtype=a_			,     **self.config.pd_read_csv_kwargs      )
											try:
													for batch_idx, df in enumerate(a_      ):
															a_     :      Tuple 						=     pa.Table.from_pandas(a_      )
															# Uncomment for debugging (will print the Arrow table size and elements)
															# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
															# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
															yield (file_idx, batch_idx), self._cast_table(a_      )
											except ValueError as e:
													logger.error(F"""Failed to read file '{file}' with error {type(a_      )}: {e}"""      )
													raise




"""simple docstring"""
import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, 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 			snake_case_						(						a_     ,unittest.TestCase				):
							__lowerCAmelCase    					=					KandinskyImgaImgPipeline
							__lowerCAmelCase    					=					["prompt", "image_embeds", "negative_image_embeds", "image"]
							__lowerCAmelCase    					=					[
							    "prompt",
							    "negative_prompt",
							    "image_embeds",
							    "negative_image_embeds",
							    "image",
							]
							__lowerCAmelCase    					=					[
							    "generator",
							    "height",
							    "width",
							    "strength",
							    "guidance_scale",
							    "negative_prompt",
							    "num_inference_steps",
							    "return_dict",
							    "guidance_scale",
							    "num_images_per_prompt",
							    "output_type",
							    "return_dict",
							]
							__lowerCAmelCase    					=					False






							@property
							def snake_case_  (   self      ):
									return 3_2






							@property
							def snake_case_  (   self      ):
									return 3_2






							@property
							def snake_case_  (   self      ):
									return self.time_input_dim






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






							@property
							def snake_case_  (   self      ):
									return 1_0_0






							@property
							def snake_case_  (   self      ):
									a_     :      List[str] 						=     XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"      )
									return tokenizer






							@property
							def snake_case_  (   self      ):
									torch.manual_seed(0      )
									a_     :      List[Any] 						=     MCLIPConfig(
									    numDims=self.cross_attention_dim			,     transformerDimensions=self.text_embedder_hidden_size			,     hidden_size=self.text_embedder_hidden_size			,     intermediate_size=3_7			,     num_attention_heads=4			,     num_hidden_layers=5			,     vocab_size=1_0_0_5			,     )

									a_     :      str 						=     MultilingualCLIP(a_      )
									a_     :      Any 						=     text_encoder.eval()

									return text_encoder






							@property
							def snake_case_  (   self      ):
									torch.manual_seed(0      )

									a_     :      Union[str, Any] 						=     {
									    "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_     :      Dict 						=     UNetaDConditionModel(**a_      )
									return model






							@property
							def snake_case_  (   self      ):
									return {
									    "block_out_channels": [3_2, 6_4],
									    "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": 1_2,
									    "out_channels": 3,
									    "up_block_types": [
									        "AttnUpDecoderBlock2D",
									        "UpDecoderBlock2D",
									    ],
									    "vq_embed_dim": 4,
									}






							@property
							def snake_case_  (   self      ):
									torch.manual_seed(0      )
									a_     :      int 						=     VQModel(**self.dummy_movq_kwargs      )
									return model






							def snake_case_  (   self      ):
									a_     :      Dict 						=     self.dummy_text_encoder
									a_     :      Dict 						=     self.dummy_tokenizer
									a_     :      Optional[int] 						=     self.dummy_unet
									a_     :      Dict 						=     self.dummy_movq

									a_     :      List[str] 						=     {
									    "num_train_timesteps": 1_0_0_0,
									    "beta_schedule": "linear",
									    "beta_start": 0.00_085,
									    "beta_end": 0.012,
									    "clip_sample": False,
									    "set_alpha_to_one": False,
									    "steps_offset": 0,
									    "prediction_type": "epsilon",
									    "thresholding": False,
									}

									a_     :      List[Any] 						=     DDIMScheduler(**a_      )

									a_     :      Union[str, Any] 						=     {
									    "text_encoder": text_encoder,
									    "tokenizer": tokenizer,
									    "unet": unet,
									    "scheduler": scheduler,
									    "movq": movq,
									}

									return components






							def snake_case_  (   self			,     a_			,     a_=0      ):
									a_     :      Optional[int] 						=     floats_tensor((1, self.cross_attention_dim)			,     rng=random.Random(a_      )      ).to(a_      )
									a_     :      Tuple 						=     floats_tensor((1, self.cross_attention_dim)			,     rng=random.Random(seed + 1      )      ).to(a_      )
									# create init_image
									a_     :      Optional[int] 						=     floats_tensor((1, 3, 6_4, 6_4)			,     rng=random.Random(a_      )      ).to(a_      )
									a_     :      Any 						=     image.cpu().permute(0			,     2			,     3			,     1      )[0]
									a_     :      int 						=     Image.fromarray(np.uinta(a_      )      ).convert("RGB"      ).resize((2_5_6, 2_5_6)      )

									if str(a_      ).startswith("mps"      ):
											a_     :      Any 						=     torch.manual_seed(a_      )
									else:
											a_     :      Any 						=     torch.Generator(device=a_      ).manual_seed(a_      )
									a_     :      List[Any] 						=     {
									    "prompt": "horse",
									    "image": init_image,
									    "image_embeds": image_embeds,
									    "negative_image_embeds": negative_image_embeds,
									    "generator": generator,
									    "height": 6_4,
									    "width": 6_4,
									    "num_inference_steps": 1_0,
									    "guidance_scale": 7.0,
									    "strength": 0.2,
									    "output_type": "np",
									}
									return inputs






							def snake_case_  (   self      ):
									a_     :      Optional[Any] 						=     "cpu"

									a_     :      List[Any] 						=     self.get_dummy_components()

									a_     :      Union[str, Any] 						=     self.pipeline_class(**a_      )
									a_     :      Tuple 						=     pipe.to(a_      )

									pipe.set_progress_bar_config(disable=a_      )

									a_     :      Union[str, Any] 						=     pipe(**self.get_dummy_inputs(a_      )      )
									a_     :      Any 						=     output.images

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

									a_     :      List[str] 						=     image[0, -3:, -3:, -1]
									a_     :      Optional[Any] 						=     image_from_tuple[0, -3:, -3:, -1]

									assert image.shape == (1, 6_4, 6_4, 3)

									a_     :      Optional[int] 						=     np.array(
									    [0.61_474_943, 0.6_073_539, 0.43_308_544, 0.5_928_269, 0.47_493_595, 0.46_755_973, 0.4_613_838, 0.45_368_797, 0.50_119_233]      )
									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 			snake_case_						(						unittest.TestCase				):






							def snake_case_  (   self      ):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()






							def snake_case_  (   self      ):
									a_     :      Optional[int] 						=     load_numpy(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									    "/kandinsky/kandinsky_img2img_frog.npy"      )

									a_     :      Union[str, Any] 						=     load_image(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"      )
									a_     :      Optional[Any] 						=     "A red cartoon frog, 4k"

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

									a_     :      int 						=     KandinskyImgaImgPipeline.from_pretrained(
									    "kandinsky-community/kandinsky-2-1"			,     torch_dtype=torch.floataa      )
									a_     :      List[Any] 						=     pipeline.to(a_      )

									pipeline.set_progress_bar_config(disable=a_      )

									a_     :      int 						=     torch.Generator(device="cpu"      ).manual_seed(0      )
									a_						,				a_     :      Optional[int] 						=     pipe_prior(
									    a_			,     generator=a_			,     num_inference_steps=5			,     negative_prompt=""			,     ).to_tuple()

									a_     :      List[Any] 						=     pipeline(
									    a_			,     image=a_			,     image_embeds=a_			,     negative_image_embeds=a_			,     generator=a_			,     num_inference_steps=1_0_0			,     height=7_6_8			,     width=7_6_8			,     strength=0.2			,     output_type="np"			,     )

									a_     :      int 						=     output.images[0]

									assert image.shape == (7_6_8, 7_6_8, 3)

									assert_mean_pixel_difference(a_			,     a_      )