




'''simple docstring'''


import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







@skip_mps
class      SCREAMING_SNAKE_CASE    (						snake_case_							,      unittest.TestCase				):
      __magic_name__  :       int   							=					TextToVideoSDPipeline
      __magic_name__  :       Union[str, Any]   							=					TEXT_TO_IMAGE_PARAMS
      __magic_name__  :       Optional[int]   							=					TEXT_TO_IMAGE_BATCH_PARAMS
      # No `output_type`.
      __magic_name__  :       int   							=					frozenset(
          [
              '''num_inference_steps''',
              '''generator''',
              '''latents''',
              '''return_dict''',
              '''callback''',
              '''callback_steps''',
          ]				)






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           torch.manual_seed(0       )
           a_     :							List[str]     						=  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						,						)
           a_     :							Dict     						=  DDIMScheduler(
               beta_start=0.00085						,						beta_end=0.012						,						beta_schedule="""scaled_linear"""						,						clip_sample=lowercase__						,						set_alpha_to_one=lowercase__						,						)
           torch.manual_seed(0       )
           a_     :							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						,						sample_size=128						,						)
           torch.manual_seed(0       )
           a_     :							str     						=  CLIPTextConfig(
               bos_token_id=0						,						eos_token_id=2						,						hidden_size=32						,						intermediate_size=37						,						layer_norm_eps=1e-0_5						,						num_attention_heads=4						,						num_hidden_layers=5						,						pad_token_id=1						,						vocab_size=1000						,						hidden_act="""gelu"""						,						projection_dim=512						,						)
           a_     :							Tuple     						=  CLIPTextModel(lowercase__       )
           a_     :							Union[str, Any]     						=  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )

           a_     :							List[Any]     						=  {
               """unet""": unet,
               """scheduler""": scheduler,
               """vae""": vae,
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
           }
           return components






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  Tuple						,						lowercase__   :  int=0       ):


           '''simple docstring'''

           if str(lowercase__       ).startswith("""mps"""       ):
                a_     :							Tuple     						=  torch.manual_seed(lowercase__       )
           else:
                a_     :							str     						=  torch.Generator(device=lowercase__       ).manual_seed(lowercase__       )
           a_     :							Optional[Any]     						=  {
               """prompt""": """A painting of a squirrel eating a burger""",
               """generator""": generator,
               """num_inference_steps""": 2,
               """guidance_scale""": 6.0,
               """output_type""": """pt""",
           }
           return inputs






      def 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           a_     :							Any     						=  """cpu"""  # ensure determinism for the device-dependent torch.Generator
           a_     :							Union[str, Any]     						=  self.get_dummy_components()
           a_     :							List[Any]     						=  TextToVideoSDPipeline(**lowercase__       )
           a_     :							List[str]     						=  sd_pipe.to(lowercase__       )
           sd_pipe.set_progress_bar_config(disable=lowercase__       )

           a_     :							Optional[int]     						=  self.get_dummy_inputs(lowercase__       )
           a_     :							Dict     						=  """np"""
           a_     :							Optional[int]     						=  sd_pipe(**lowercase__       ).frames
           a_     :							List[str]     						=  frames[0][-3:, -3:, -1]

           assert frames[0].shape == (64, 64, 3)
           a_     :							Optional[int]     						=  np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0]       )

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






      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase__						,						expected_max_diff=3e-3       )






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


           '''simple docstring'''

           self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase__						,						expected_max_diff=1e-2       )






      @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""       )
      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""       )
      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline."""       )
      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           pass






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           return super().test_progress_bar()







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






      def 							lowercase_						( self   :  Optional[int]       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"""       )

           a_     :							Tuple     						=  TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""       )
           a_     :							str     						=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
           a_     :							Dict     						=  pipe.to("""cuda"""       )

           a_     :							List[str]     						=  """Spiderman is surfing"""
           a_     :							Tuple     						=  torch.Generator(device="""cpu"""       ).manual_seed(0       )

           a_     :							Any     						=  pipe(lowercase__						,						generator=lowercase__						,						num_inference_steps=25						,						output_type="""pt"""       ).frames
           a_     :							List[Any]     						=  video_frames.cpu().numpy()

           assert np.abs(expected_video - video       ).mean() < 5e-2






      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           a_     :							List[str]     						=  load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"""       )

           a_     :							Union[str, Any]     						=  TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""       )
           a_     :							Any     						=  pipe.to("""cuda"""       )

           a_     :							Tuple     						=  """Spiderman is surfing"""
           a_     :							str     						=  torch.Generator(device="""cpu"""       ).manual_seed(0       )

           a_     :							Dict     						=  pipe(lowercase__						,						generator=lowercase__						,						num_inference_steps=2						,						output_type="""pt"""       ).frames
           a_     :							int     						=  video_frames.cpu().numpy()

           assert np.abs(expected_video - video       ).mean() < 5e-2






'''simple docstring'''


import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


lowerCAmelCase_      :  Any				     =  datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
 import pyspark







@dataclass
class      SCREAMING_SNAKE_CASE    (						datasets.BuilderConfig				):
      __magic_name__  :       Optional[datasets.Features]   							=					None



def  _SCREAMING_SNAKE_CASE     (      UpperCamelCase__    :					"pyspark.sql.DataFrame" ,    UpperCamelCase__    :					List[int] ,    ):




     """simple docstring"""


     import pyspark

     def generate_fn():
          a_     :							Any     						=  df.select("""*""" ,    pyspark.sql.functions.spark_partition_id().alias("""part_id"""				)				)
          for partition_id in partition_order:
               a_     :							int     						=  df_with_partition_id.select("""*"""				).where(F"part_id = {partition_id}"				).drop("""part_id"""				)
               a_     :							str     						=  partition_df.collect()
               a_     :							List[str]     						=  0
               for row in rows:
                    yield F"{partition_id}_{row_id}", row.asDict()
                    row_id += 1

     return generate_fn







class      SCREAMING_SNAKE_CASE    (						_BaseExamplesIterable				):






      def __init__( self   :  Dict						,						lowercase__   :  "pyspark.sql.DataFrame"						,						lowercase__   :  Optional[int]=None						,						):


           '''simple docstring'''

           a_     :							Tuple     						=  df
           a_     :							Dict     						=  partition_order or range(self.df.rdd.getNumPartitions()       )
           a_     :							Dict     						=  _generate_iterable_examples(self.df						,						self.partition_order       )






      def __iter__( self   :  Optional[Any]       ):


           '''simple docstring'''

           yield from self.generate_examples_fn()






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  np.random.Generator       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  list(range(self.df.rdd.getNumPartitions()       )       )
           generator.shuffle(lowercase__       )
           return SparkExamplesIterable(self.df						,						partition_order=lowercase__       )






      def 							lowercase_						( self   :  Any						,						lowercase__   :  int						,						lowercase__   :  int       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.split_shard_indices_by_worker(lowercase__						,						lowercase__       )
           return SparkExamplesIterable(self.df						,						partition_order=lowercase__       )






      @property
      def 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           return len(self.partition_order       )







class      SCREAMING_SNAKE_CASE    (						datasets.DatasetBuilder				):
      __magic_name__  :       Optional[int]   							=					SparkConfig






      def __init__( self   :  Optional[Any]						,						lowercase__   :  "pyspark.sql.DataFrame"						,						lowercase__   :  str = None						,						lowercase__   :  str = None						,						**lowercase__   :  Dict						,						):


           '''simple docstring'''

           import pyspark

           a_     :							Dict     						=  pyspark.sql.SparkSession.builder.getOrCreate()
           a_     :							List[str]     						=  df
           a_     :							List[str]     						=  working_dir

           super().__init__(
               cache_dir=lowercase__						,						config_name=str(self.df.semanticHash()       )						,						**lowercase__						,						)






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           def create_cache_and_write_probe(lowercase__   :  Any       ):
                # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
                # already exist.
                os.makedirs(self._cache_dir						,						exist_ok=lowercase__       )
                a_     :							List[Any]     						=  os.path.join(self._cache_dir						,						"""fs_test""" + uuid.uuida().hex       )
                # Opening the file in append mode will create a new file unless it already exists, in which case it will not
                # change the file contents.
                open(lowercase__						,						"""a"""       )
                return [probe_file]

           if self._spark.conf.get("""spark.master"""						,						""""""       ).startswith("""local"""       ):
                return

           # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
           # accessible to the driver.
           # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
           if self._cache_dir:
                a_     :							str     						=  (
                    self._spark.sparkContext.parallelize(range(1       )						,						1       ).mapPartitions(lowercase__       ).collect()
                )
                if os.path.isfile(probe[0]       ):
                     return

           raise ValueError(
               """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir"""       )






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

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






      def 							lowercase_						( self   :  Tuple						,						lowercase__   :  datasets.download.download_manager.DownloadManager       ):


           '''simple docstring'''

           return [datasets.SplitGenerator(name=datasets.Split.TRAIN       )]






      def 							lowercase_						( self   :  Any						,						lowercase__   :  int       ):


           '''simple docstring'''

           import pyspark

           def get_arrow_batch_size(lowercase__   :  List[Any]       ):
                for batch in it:
                     yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]}       )

           a_     :							Union[str, Any]     						=  self.df.count()
           a_     :							List[str]     						=  df_num_rows if df_num_rows <= 100 else 100
           # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
           a_     :							str     						=  (
               self.df.limit(lowercase__       )
               .repartition(1       )
               .mapInArrow(lowercase__						,						"""batch_bytes: long"""       )
               .agg(pyspark.sql.functions.sum("""batch_bytes"""       ).alias("""sample_bytes"""       )       )
               .collect()[0]
               .sample_bytes
               / sample_num_rows
           )
           a_     :							List[str]     						=  approx_bytes_per_row * df_num_rows
           if approx_total_size > max_shard_size:
                # Make sure there is at least one row per partition.
                a_     :							List[str]     						=  min(lowercase__						,						int(approx_total_size / max_shard_size       )       )
                a_     :							Union[str, Any]     						=  self.df.repartition(lowercase__       )






      def 							lowercase_						( self   :  Optional[Any]						,						lowercase__   :  str						,						lowercase__   :  str						,						lowercase__   :  int						,						):


           '''simple docstring'''

           import pyspark

           a_     :							str     						=  ParquetWriter if file_format == """parquet""" else ArrowWriter
           a_     :							int     						=  os.path.join(self._working_dir						,						os.path.basename(lowercase__       )       ) if self._working_dir else fpath
           a_     :							Optional[int]     						=  file_format == """parquet"""

           # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
           # pickling the SparkContext.
           a_     :							int     						=  self.config.features
           a_     :							List[str]     						=  self._writer_batch_size
           a_     :							str     						=  self._fs.storage_options

           def write_arrow(lowercase__   :  Optional[Any]       ):
                # Within the same SparkContext, no two task attempts will share the same attempt ID.
                a_     :							int     						=  pyspark.TaskContext().taskAttemptId()
                a_     :							List[str]     						=  next(lowercase__						,						lowercase__       )
                if first_batch is None:
                     # Some partitions might not receive any data.
                     return pa.RecordBatch.from_arrays(
                         [[task_id], [0], [0]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)
                a_     :							List[str]     						=  0
                a_     :							Union[str, Any]     						=  writer_class(
                    features=lowercase__						,						path=working_fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						writer_batch_size=lowercase__						,						storage_options=lowercase__						,						embed_local_files=lowercase__						,						)
                a_     :							List[str]     						=  pa.Table.from_batches([first_batch]       )
                writer.write_table(lowercase__       )
                for batch in it:
                     if max_shard_size is not None and writer._num_bytes >= max_shard_size:
                          a_						,     a_     :							Optional[Any]     						=  writer.finalize()
                          writer.close()
                          yield pa.RecordBatch.from_arrays(
                              [[task_id], [num_examples], [num_bytes]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)
                          shard_id += 1
                          a_     :							Any     						=  writer_class(
                              features=writer._features						,						path=working_fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						writer_batch_size=lowercase__						,						storage_options=lowercase__						,						embed_local_files=lowercase__						,						)
                     a_     :							str     						=  pa.Table.from_batches([batch]       )
                     writer.write_table(lowercase__       )

                if writer._num_bytes > 0:
                     a_						,     a_     :							Any     						=  writer.finalize()
                     writer.close()
                     yield pa.RecordBatch.from_arrays(
                         [[task_id], [num_examples], [num_bytes]]						,						names=["""task_id""", """num_examples""", """num_bytes"""]						,						)

                if working_fpath != fpath:
                     for file in os.listdir(os.path.dirname(lowercase__       )       ):
                          a_     :							str     						=  os.path.join(os.path.dirname(lowercase__       )						,						os.path.basename(lowercase__       )       )
                          shutil.move(lowercase__						,						lowercase__       )

           a_     :							Any     						=  (
               self.df.mapInArrow(lowercase__						,						"""task_id: long, num_examples: long, num_bytes: long"""       )
               .groupBy("""task_id"""       )
               .agg(
                   pyspark.sql.functions.sum("""num_examples"""       ).alias("""total_num_examples"""       )						,						pyspark.sql.functions.sum("""num_bytes"""       ).alias("""total_num_bytes"""       )						,						pyspark.sql.functions.count("""num_bytes"""       ).alias("""num_shards"""       )						,						pyspark.sql.functions.collect_list("""num_examples"""       ).alias("""shard_lengths"""       )						,						)
               .collect()
           )
           for row in stats:
                yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  "datasets.SplitGenerator"						,						lowercase__   :  str = "arrow"						,						lowercase__   :  Optional[Union[str, int]] = None						,						lowercase__   :  Optional[int] = None						,						**lowercase__   :  Optional[int]						,						):


           '''simple docstring'''

           self._validate_cache_dir()

           a_     :							Dict     						=  convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE       )
           self._repartition_df_if_needed(lowercase__       )
           a_     :							Any     						=  not is_remote_filesystem(self._fs       )
           a_     :							str     						=  os.path.join if is_local else posixpath.join

           a_     :							Optional[Any]     						=  """-TTTTT-SSSSS-of-NNNNN"""
           a_     :							int     						=  F"{self.name}-{split_generator.name}{SUFFIX}.{file_format}"
           a_     :							Optional[Any]     						=  path_join(self._output_dir						,						lowercase__       )

           a_     :							Dict     						=  0
           a_     :							Optional[Any]     						=  0
           a_     :							Dict     						=  0
           a_     :							List[str]     						=  []
           a_     :							Dict     						=  []

           for task_id, content in self._prepare_split_single(lowercase__						,						lowercase__						,						lowercase__       ):
                (
                    (
                    a_
                )						,     (
                    a_
                )						,     (
                    a_
                )						,     (
                    a_
                )						,     
                )     :							Tuple     						=  content
                if num_bytes > 0:
                     total_num_examples += num_examples
                     total_num_bytes += num_bytes
                     total_shards += num_shards
                     task_id_and_num_shards.append((task_id, num_shards)       )
                     all_shard_lengths.extend(lowercase__       )

           a_     :							List[Any]     						=  total_num_examples
           a_     :							int     						=  total_num_bytes

           # should rename everything at the end
           logger.debug(F"Renaming {total_shards} shards."       )
           if total_shards > 1:
                a_     :							Dict     						=  all_shard_lengths

                # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
                # pickling error due to pickling the SparkContext.
                a_     :							List[str]     						=  self._fs

                # use the -SSSSS-of-NNNNN pattern
                def _rename_shard(
                    lowercase__   :  int						,						lowercase__   :  int						,						lowercase__   :  int						,						):
                     rename(
                         lowercase__						,						fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						fpath.replace("""TTTTT-SSSSS"""						,						F"{global_shard_id:05d}"       ).replace("""NNNNN"""						,						F"{total_shards:05d}"       )						,						)

                a_     :							int     						=  []
                a_     :							List[str]     						=  0
                for i in range(len(lowercase__       )       ):
                     a_						,     a_     :							List[str]     						=  task_id_and_num_shards[i]
                     for shard_id in range(lowercase__       ):
                          args.append([task_id, shard_id, global_shard_id]       )
                          global_shard_id += 1
                self._spark.sparkContext.parallelize(lowercase__						,						len(lowercase__       )       ).map(lambda lowercase__       : _rename_shard(*lowercase__       )       ).collect()
           else:
                # don't use any pattern
                a_     :							int     						=  0
                a_     :							Any     						=  task_id_and_num_shards[0][0]
                self._rename(
                    fpath.replace("""SSSSS"""						,						F"{shard_id:05d}"       ).replace("""TTTTT"""						,						F"{task_id:05d}"       )						,						fpath.replace(lowercase__						,						""""""       )						,						)






      def 							lowercase_						( self   :  Tuple						,						lowercase__   :  "datasets.SplitGenerator"						,						):


           '''simple docstring'''

           return SparkExamplesIterable(self.df       )
