





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 SCREAMING_SNAKE_CASE_  (   datasets.BuilderConfig   ):
						__magic_name__:     str  =    ","
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     Optional[Union[int, List[int], str]]  =    "infer"
						__magic_name__:     Optional[List[str]]  =    None
						__magic_name__:     Optional[List[str]]  =    None
						__magic_name__:     Optional[Union[int, str, List[int], List[str]]]  =    None
						__magic_name__:     Optional[Union[List[int], List[str]]]  =    None
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     bool  =    True
						__magic_name__:     Optional[Literal["c", "python", "pyarrow"]]  =    None
						__magic_name__:     Dict[Union[int, str], Callable[[Any], Any]]  =    None
						__magic_name__:     Optional[list]  =    None
						__magic_name__:     Optional[list]  =    None
						__magic_name__:     bool  =    False
						__magic_name__:     Optional[Union[int, List[int]]]  =    None
						__magic_name__:     Optional[int]  =    None
						__magic_name__:     Optional[Union[str, List[str]]]  =    None
						__magic_name__:     bool  =    True
						__magic_name__:     bool  =    True
						__magic_name__:     bool  =    False
						__magic_name__:     bool  =    True
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     str  =    "."
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     str  =    '"'
						__magic_name__:     int  =    0
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     bool  =    True
						__magic_name__:     bool  =    True
						__magic_name__:     int  =    0
						__magic_name__:     bool  =    True
						__magic_name__:     bool  =    False
						__magic_name__:     Optional[str]  =    None
						__magic_name__:     int  =    10000
						__magic_name__:     Optional[datasets.Features]  =    None
						__magic_name__:     Optional[str]  =    "strict"
						__magic_name__:     Literal["error", "warn", "skip"]  =    "error"
						__magic_name__:     Optional[str]  =    None






						def UpperCAmelCase_			( self : Dict		)							->      Tuple:







							"""simple docstring"""


							if self.delimiter is not None:
								snake_case_						:     Optional[int]     =		self.delimiter
							if self.column_names is not None:
								snake_case_						:     List[str]     =		self.column_names






						@property
						def UpperCAmelCase_			( self : Optional[int]		)							->      Optional[int]:







							"""simple docstring"""


							snake_case_						:     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 SCREAMING_SNAKE_CASE_  (   datasets.ArrowBasedBuilder   ):
						__magic_name__:     List[str]  =    CsvConfig






						def UpperCAmelCase_			( self : List[Any]		)							->      Union[str, Any]:







							"""simple docstring"""


							return datasets.DatasetInfo(features=self.config.features		)






						def UpperCAmelCase_			( self : str						,				_A : Dict		)							->      List[str]:







							"""simple docstring"""


							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}"""		)
							snake_case_						:     List[str]     =		dl_manager.download_and_extract(self.config.data_files		)
							if isinstance(a__						,				(str, list, tuple)		):
								snake_case_						:     str     =		data_files
								if isinstance(a__						,				a__		):
									snake_case_						:     Any     =		[files]
								snake_case_						:     List[str]     =		[dl_manager.iter_files(a__		) for file in files]
								return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,				gen_kwargs={'files': files}		)]
							snake_case_						:     Any     =		[]
							for split_name, files in data_files.items():
								if isinstance(a__						,				a__		):
									snake_case_						:     Union[str, Any]     =		[files]
								snake_case_						:     int     =		[dl_manager.iter_files(a__		) for file in files]
								splits.append(datasets.SplitGenerator(name=a__						,				gen_kwargs={'files': files}		)		)
							return splits






						def UpperCAmelCase_			( self : Dict						,				_A : pa.Table		)							->      Optional[Any]:







							"""simple docstring"""


							if self.config.features is not None:
								snake_case_						:     Union[str, Any]     =		self.config.features.arrow_schema
								if all(not require_storage_cast(a__		) for feature in self.config.features.values()		):
									# cheaper cast
									snake_case_						:     Optional[Any]     =		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
									snake_case_						:     List[Any]     =		table_cast(a__						,				a__		)
							return pa_table






						def UpperCAmelCase_			( self : Tuple						,				_A : str		)							->      str:







							"""simple docstring"""


							snake_case_						:     int     =		self.config.features.arrow_schema if self.config.features else None
							# dtype allows reading an int column as str
							snake_case_						:     Union[str, 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__		)		):
								snake_case_						:     Any     =		pd.read_csv(a__						,				iterator=a__						,				dtype=a__						,				**self.config.pd_read_csv_kwargs		)
								try:
									for batch_idx, df in enumerate(a__		):
										snake_case_						:     Optional[int]     =		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








import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class SCREAMING_SNAKE_CASE_  (   snake_case_    ,			snake_case_    ,			snake_case_    ,			unittest.TestCase   ):
						__magic_name__:     int	 =    AltDiffusionPipeline
						__magic_name__:     Any	 =    TEXT_TO_IMAGE_PARAMS
						__magic_name__:     Any	 =    TEXT_TO_IMAGE_BATCH_PARAMS
						__magic_name__:     Any	 =    TEXT_TO_IMAGE_IMAGE_PARAMS
						__magic_name__:     Union[str, Any]	 =    TEXT_TO_IMAGE_IMAGE_PARAMS






						def UpperCAmelCase_			( self : List[Any]		)							->      int:







							"""simple docstring"""


							torch.manual_seed(0		)
							snake_case_						:     List[str]     =		UNetaDConditionModel(
							    block_out_channels=(32, 64)						,				layers_per_block=2						,				sample_size=32						,				in_channels=4						,				out_channels=4						,				down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')						,				up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')						,				cross_attention_dim=32						,				)
							snake_case_						:     Optional[Any]     =		DDIMScheduler(
							    beta_start=0.0_0_0_8_5						,				beta_end=0.0_1_2						,				beta_schedule='scaled_linear'						,				clip_sample=_A						,				set_alpha_to_one=_A						,				)
							torch.manual_seed(0		)
							snake_case_						:     Union[str, Any]     =		AutoencoderKL(
							    block_out_channels=[32, 64]						,				in_channels=3						,				out_channels=3						,				down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']						,				up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']						,				latent_channels=4						,				)

							# TODO: address the non-deterministic text encoder (fails for save-load tests)
							# torch.manual_seed(0)
							# text_encoder_config = RobertaSeriesConfig(
							#     hidden_size=32,
							#     project_dim=32,
							#     intermediate_size=37,
							#     layer_norm_eps=1e-05,
							#     num_attention_heads=4,
							#     num_hidden_layers=5,
							#     vocab_size=5002,
							# )
							# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

							torch.manual_seed(0		)
							snake_case_						:     Optional[Any]     =		CLIPTextConfig(
							    bos_token_id=0						,				eos_token_id=2						,				hidden_size=32						,				projection_dim=32						,				intermediate_size=37						,				layer_norm_eps=1E-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=5002						,				)
							snake_case_						:     Any     =		CLIPTextModel(_A		)

							snake_case_						:     Any     =		XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'		)
							snake_case_						:     Dict     =		77

							snake_case_						:     List[Any]     =		{
							    'unet': unet,
							    'scheduler': scheduler,
							    'vae': vae,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'safety_checker': None,
							    'feature_extractor': None,
							}
							return components






						def UpperCAmelCase_			( self : int						,				_A : Optional[int]						,				_A : int=0		)							->      Dict:







							"""simple docstring"""


							if str(_A		).startswith('mps'		):
								snake_case_						:     Union[str, Any]     =		torch.manual_seed(_A		)
							else:
								snake_case_						:     Union[str, Any]     =		torch.Generator(device=_A		).manual_seed(_A		)
							snake_case_						:     Any     =		{
							    'prompt': 'A painting of a squirrel eating a burger',
							    'generator': generator,
							    'num_inference_steps': 2,
							    'guidance_scale': 6.0,
							    'output_type': 'numpy',
							}
							return inputs






						def UpperCAmelCase_			( self : Optional[Any]		)							->      Any:







							"""simple docstring"""


							super().test_attention_slicing_forward_pass(expected_max_diff=3E-3		)






						def UpperCAmelCase_			( self : List[Any]		)							->      Dict:







							"""simple docstring"""


							super().test_inference_batch_single_identical(expected_max_diff=3E-3		)






						def UpperCAmelCase_			( self : Dict		)							->      Any:







							"""simple docstring"""


							snake_case_						:     Tuple     =		'cpu'  # ensure determinism for the device-dependent torch.Generator

							snake_case_						:     Any     =		self.get_dummy_components()
							torch.manual_seed(0		)
							snake_case_						:     Any     =		RobertaSeriesConfig(
							    hidden_size=32						,				project_dim=32						,				intermediate_size=37						,				layer_norm_eps=1E-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				vocab_size=5002						,				)
							# TODO: remove after fixing the non-deterministic text encoder
							snake_case_						:     Optional[Any]     =		RobertaSeriesModelWithTransformation(_A		)
							snake_case_						:     Optional[Any]     =		text_encoder

							snake_case_						:     Optional[Any]     =		AltDiffusionPipeline(**_A		)
							snake_case_						:     List[Any]     =		alt_pipe.to(_A		)
							alt_pipe.set_progress_bar_config(disable=_A		)

							snake_case_						:     Optional[Any]     =		self.get_dummy_inputs(_A		)
							snake_case_						:     int     =		'A photo of an astronaut'
							snake_case_						:     Tuple     =		alt_pipe(**_A		)
							snake_case_						:     Any     =		output.images
							snake_case_						:     Optional[int]     =		image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case_						:     Any     =		np.array(
							    [0.5_7_4_8_1_6_2, 0.6_0_4_4_7_1_4_5, 0.4_8_8_2_1_2_1_7, 0.5_0_1_0_0_6_3_6, 0.5_4_3_1_1_8_5, 0.4_5_7_6_3_6_8_3, 0.4_9_6_5_7_6_9_6, 0.4_8_1_3_2_7_3_3, 0.4_7_5_7_3_0_9_3]		)

							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2






						def UpperCAmelCase_			( self : Optional[int]		)							->      Optional[int]:







							"""simple docstring"""


							snake_case_						:     Optional[Any]     =		'cpu'  # ensure determinism for the device-dependent torch.Generator

							snake_case_						:     Any     =		self.get_dummy_components()
							snake_case_						:     List[str]     =		PNDMScheduler(skip_prk_steps=_A		)
							torch.manual_seed(0		)
							snake_case_						:     Optional[int]     =		RobertaSeriesConfig(
							    hidden_size=32						,				project_dim=32						,				intermediate_size=37						,				layer_norm_eps=1E-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				vocab_size=5002						,				)
							# TODO: remove after fixing the non-deterministic text encoder
							snake_case_						:     Tuple     =		RobertaSeriesModelWithTransformation(_A		)
							snake_case_						:     Any     =		text_encoder
							snake_case_						:     Tuple     =		AltDiffusionPipeline(**_A		)
							snake_case_						:     Dict     =		alt_pipe.to(_A		)
							alt_pipe.set_progress_bar_config(disable=_A		)

							snake_case_						:     Dict     =		self.get_dummy_inputs(_A		)
							snake_case_						:     Tuple     =		alt_pipe(**_A		)
							snake_case_						:     int     =		output.images
							snake_case_						:     List[Any]     =		image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case_						:     Optional[int]     =		np.array(
							    [0.5_1_6_0_5_0_9_3, 0.5_7_0_7_2_4_1, 0.4_7_3_6_5_5_0_7, 0.5_0_5_7_8_8_8_6, 0.5_6_3_3_8_7_7, 0.4_6_4_2_5_0_3, 0.5_1_8_2_0_8_1, 0.4_8_7_6_3_4_8_4, 0.4_9_0_8_4_2_3_7]		)

							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2
@slow
@require_torch_gpu
class SCREAMING_SNAKE_CASE_  (   unittest.TestCase   ):






						def UpperCAmelCase_			( self : List[Any]		)							->      Tuple:







							"""simple docstring"""


							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()






						def UpperCAmelCase_			( self : int		)							->      List[str]:







							"""simple docstring"""


							snake_case_						:     Optional[int]     =		AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'						,				safety_checker=_A		)
							snake_case_						:     Optional[int]     =		alt_pipe.to(_A		)
							alt_pipe.set_progress_bar_config(disable=_A		)

							snake_case_						:     str     =		'A painting of a squirrel eating a burger'
							snake_case_						:     Tuple     =		torch.manual_seed(0		)
							snake_case_						:     str     =		alt_pipe([prompt]						,				generator=_A						,				guidance_scale=6.0						,				num_inference_steps=20						,				output_type='np'		)

							snake_case_						:     Any     =		output.images

							snake_case_						:     List[Any]     =		image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							snake_case_						:     Union[str, Any]     =		np.array([0.1_0_1_0, 0.0_8_0_0, 0.0_7_9_4, 0.0_8_8_5, 0.0_8_4_3, 0.0_7_6_2, 0.0_7_6_9, 0.0_7_2_9, 0.0_5_8_6]		)

							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2






						def UpperCAmelCase_			( self : Optional[int]		)							->      Union[str, Any]:







							"""simple docstring"""


							snake_case_						:     Optional[Any]     =		DDIMScheduler.from_pretrained('BAAI/AltDiffusion'						,				subfolder='scheduler'		)

							snake_case_						:     Union[str, Any]     =		AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'						,				scheduler=_A						,				safety_checker=_A		)
							snake_case_						:     List[str]     =		alt_pipe.to(_A		)
							alt_pipe.set_progress_bar_config(disable=_A		)

							snake_case_						:     List[Any]     =		'A painting of a squirrel eating a burger'
							snake_case_						:     int     =		torch.manual_seed(0		)

							snake_case_						:     List[Any]     =		alt_pipe([prompt]						,				generator=_A						,				num_inference_steps=2						,				output_type='numpy'		)
							snake_case_						:     Any     =		output.images

							snake_case_						:     Dict     =		image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							snake_case_						:     List[Any]     =		np.array([0.4_0_1_9, 0.4_0_5_2, 0.3_8_1_0, 0.4_1_1_9, 0.3_9_1_6, 0.3_9_8_2, 0.4_6_5_1, 0.4_1_9_5, 0.5_3_2_3]		)

							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2

