


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


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

__snake_case   							=						['''names''', '''prefix''']
__snake_case   							=						['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
__snake_case   							=						['''encoding_errors''', '''on_bad_lines''']
__snake_case   							=						['''date_format''']



@dataclass
class 	__lowerCamelCase			(datasets.BuilderConfig						):
       _lowercase											=     ","
       _lowercase											=     None
       _lowercase											=     "infer"
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     False
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     True
       _lowercase											=     False
       _lowercase											=     True
       _lowercase											=     None
       _lowercase											=     "."
       _lowercase											=     None
       _lowercase											=     '"'
       _lowercase											=     0
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     None
       _lowercase											=     True
       _lowercase											=     True
       _lowercase											=     0
       _lowercase											=     True
       _lowercase											=     False
       _lowercase											=     None
       _lowercase											=     1_0000
       _lowercase											=     None
       _lowercase											=     "strict"
       _lowercase											=     "error"
       _lowercase											=     None







       def 		snake_case_	(			self: str					):






            '''simple docstring'''




            if self.delimiter is not None:
                 __UpperCamelCase =			self.delimiter
            if self.column_names is not None:
                 __UpperCamelCase =			self.column_names







       @property
       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            __UpperCamelCase =			{
                '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 	__lowerCamelCase			(datasets.ArrowBasedBuilder						):
       _lowercase											=     CsvConfig







       def 		snake_case_	(			self: Optional[int]					):






            '''simple docstring'''




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







       def 		snake_case_	(			self: List[str],A_: Any					):






            '''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}'''					)
            __UpperCamelCase =			dl_manager.download_and_extract(self.config.data_files					)
            if isinstance(A_,(str, list, tuple)					):
                 __UpperCamelCase =			data_files
                 if isinstance(A_,A_					):
                      __UpperCamelCase =			[files]
                 __UpperCamelCase =			[dl_manager.iter_files(A_					) for file in files]
                 return [datasets.SplitGenerator(name=datasets.Split.TRAIN,gen_kwargs={'files': files}					)]
            __UpperCamelCase =			[]
            for split_name, files in data_files.items():
                 if isinstance(A_,A_					):
                      __UpperCamelCase =			[files]
                 __UpperCamelCase =			[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: Dict,A_: pa.Table					):






            '''simple docstring'''




            if self.config.features is not None:
                 __UpperCamelCase =			self.config.features.arrow_schema
                 if all(not require_storage_cast(A_					) for feature in self.config.features.values()					):
                      # cheaper cast
                      __UpperCamelCase =			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
                      __UpperCamelCase =			table_cast(A_,A_					)
            return pa_table







       def 		snake_case_	(			self: Optional[Any],A_: Optional[int]					):






            '''simple docstring'''




            __UpperCamelCase =			self.config.features.arrow_schema if self.config.features else None
            # dtype allows reading an int column as str
            __UpperCamelCase =			(
                {
                    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_					)					):
                 __UpperCamelCase =			pd.read_csv(A_,iterator=A_,dtype=A_,**self.config.pd_read_csv_kwargs					)
                 try:
                      for batch_idx, df in enumerate(A_					):
                           __UpperCamelCase =			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 random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



@skip_mps
class 	__lowerCamelCase			(_a				,      unittest.TestCase						):
       _lowercase											=     VideoToVideoSDPipeline
       _lowercase											=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""}						) - {"""image""", """width""", """height"""}
       _lowercase											=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""}						) - {"""image"""}
       _lowercase											=     PipelineTesterMixin.required_optional_params - {"""latents"""}
       _lowercase											=     False

       # No `output_type`.
       _lowercase											=     frozenset(
           [
               """num_inference_steps""",
               """generator""",
               """latents""",
               """return_dict""",
               """callback""",
               """callback_steps""",
           ]						)







       def 		snake_case_	(			self: List[str]					):






            '''simple docstring'''




            torch.manual_seed(0					)
            __UpperCamelCase =			UNetaDConditionModel(
                block_out_channels=(32, 64, 64, 64),layers_per_block=2,sample_size=32,in_channels=4,out_channels=4,down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D'),up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D'),cross_attention_dim=32,attention_head_dim=4,)
            __UpperCamelCase =			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					)
            __UpperCamelCase =			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,sample_size=128,)
            torch.manual_seed(0					)
            __UpperCamelCase =			CLIPTextConfig(
                bos_token_id=0,eos_token_id=2,hidden_size=32,intermediate_size=37,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1000,hidden_act='gelu',projection_dim=512,)
            __UpperCamelCase =			CLIPTextModel(A_					)
            __UpperCamelCase =			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'					)

            __UpperCamelCase =			{
                'unet': unet,
                'scheduler': scheduler,
                'vae': vae,
                'text_encoder': text_encoder,
                'tokenizer': tokenizer,
            }
            return components







       def 		snake_case_	(			self: Union[str, Any],A_: Any,A_: Any=0					):






            '''simple docstring'''




            __UpperCamelCase =			floats_tensor((1, 3, 3, 32, 32),rng=random.Random(A_					)					).to(A_					)

            if str(A_					).startswith('mps'					):
                 __UpperCamelCase =			torch.manual_seed(A_					)
            else:
                 __UpperCamelCase =			torch.Generator(device=A_					).manual_seed(A_					)
            __UpperCamelCase =			{
                'prompt': 'A painting of a squirrel eating a burger',
                'video': video,
                'generator': generator,
                'num_inference_steps': 2,
                'guidance_scale': 6.0,
                'output_type': 'pt',
            }
            return inputs







       def 		snake_case_	(			self: Union[str, Any]					):






            '''simple docstring'''




            __UpperCamelCase =			'cpu'  # ensure determinism for the device-dependent torch.Generator
            __UpperCamelCase =			self.get_dummy_components()
            __UpperCamelCase =			VideoToVideoSDPipeline(**A_					)
            __UpperCamelCase =			sd_pipe.to(A_					)
            sd_pipe.set_progress_bar_config(disable=A_					)

            __UpperCamelCase =			self.get_dummy_inputs(A_					)
            __UpperCamelCase =			'np'
            __UpperCamelCase =			sd_pipe(**A_					).frames
            __UpperCamelCase =			frames[0][-3:, -3:, -1]

            assert frames[0].shape == (32, 32, 3)
            __UpperCamelCase =			np.array([106, 117, 113, 174, 137, 112, 148, 151, 131]					)

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







       @unittest.skipIf(
           torch_device != 'cuda' or not is_xformers_available(),reason='XFormers attention is only available with CUDA and `xformers` installed',)
       def 		snake_case_	(			self: Any					):






            '''simple docstring'''




            self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_,expected_max_diff=5E-3					)







       @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'					)
       def 		snake_case_	(			self: str					):






            '''simple docstring'''




            pass







       @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'					)
       def 		snake_case_	(			self: Optional[Any]					):






            '''simple docstring'''




            pass







       @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.'					)
       def 		snake_case_	(			self: int					):






            '''simple docstring'''




            pass







       def 		snake_case_	(			self: Any					):






            '''simple docstring'''




            return super().test_progress_bar()



@slow
@skip_mps
class 	__lowerCamelCase			(unittest.TestCase						):







       def 		snake_case_	(			self: Tuple					):






            '''simple docstring'''




            __UpperCamelCase =			VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL',torch_dtype=torch.floataa					)
            pipe.enable_model_cpu_offload()

            # 10 frames
            __UpperCamelCase =			torch.Generator(device='cpu'					).manual_seed(0					)
            __UpperCamelCase =			torch.randn((1, 10, 3, 1024, 576),generator=A_					)
            __UpperCamelCase =			video.to('cuda'					)

            __UpperCamelCase =			'Spiderman is surfing'

            __UpperCamelCase =			pipe(A_,video=A_,generator=A_,num_inference_steps=3,output_type='pt'					).frames

            __UpperCamelCase =			np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6]					)
            assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array					).sum() < 1E-2


