import gc
import unittest

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

from diffusers import PriorTransformer, UnCLIPPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

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


enable_full_determinism()







class 			__snake_case   (     lowerCamelCase__					,   unittest.TestCase   ):
 __lowerCamelCase    :   Tuple     =      UnCLIPPipeline
 __lowerCamelCase    :   Tuple     =      TEXT_TO_IMAGE_PARAMS - {
     """negative_prompt""",
     """height""",
     """width""",
     """negative_prompt_embeds""",
     """guidance_scale""",
     """prompt_embeds""",
     """cross_attention_kwargs""",
 }
 __lowerCamelCase    :   Dict     =      TEXT_TO_IMAGE_BATCH_PARAMS
 __lowerCamelCase    :   int     =      [
     """generator""",
     """return_dict""",
     """prior_num_inference_steps""",
     """decoder_num_inference_steps""",
     """super_res_num_inference_steps""",
 ]
 __lowerCamelCase    :   Optional[int]     =      False
 @property
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       return 32
 @property
 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       return 32
 @property
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       return self.time_input_dim
 @property
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       return self.time_input_dim * 4
 @property
 def 	UpperCAmelCase__       (  self						)	->							Any:
       '''simple docstring'''





       return 100
 @property
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)
       return tokenizer
 @property
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       torch.manual_seed(0						)
       UpperCAmelCase    : List[str]      =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=37		,   layer_norm_eps=1e-05		,   num_attention_heads=4		,   num_hidden_layers=5		,   pad_token_id=1		,   vocab_size=1000		,   )
       return CLIPTextModelWithProjection(snake_case__						)
 @property
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       torch.manual_seed(0						)

       UpperCAmelCase    : Any      ={
           '''num_attention_heads''': 2,
           '''attention_head_dim''': 12,
           '''embedding_dim''': self.text_embedder_hidden_size,
           '''num_layers''': 1,
       }

       UpperCAmelCase    : Tuple      =PriorTransformer(**snake_case__						)
       return model
 @property
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       torch.manual_seed(0						)

       UpperCAmelCase    : List[str]      ={
           '''clip_embeddings_dim''': self.text_embedder_hidden_size,
           '''time_embed_dim''': self.time_embed_dim,
           '''cross_attention_dim''': self.cross_attention_dim,
       }

       UpperCAmelCase    : Any      =UnCLIPTextProjModel(**snake_case__						)
       return model
 @property
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       torch.manual_seed(0						)

       UpperCAmelCase    : List[str]      ={
           '''sample_size''': 32,
           # RGB in channels
           '''in_channels''': 3,
           # Out channels is double in channels because predicts mean and variance
           '''out_channels''': 6,
           '''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,
           '''cross_attention_dim''': self.cross_attention_dim,
           '''attention_head_dim''': 4,
           '''resnet_time_scale_shift''': '''scale_shift''',
           '''class_embed_type''': '''identity''',
       }

       UpperCAmelCase    : Tuple      =UNetaDConditionModel(**snake_case__						)
       return model
 @property
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       return {
           "sample_size": 64,
           "layers_per_block": 1,
           "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
           "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
           "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
           "in_channels": 6,
           "out_channels": 3,
       }
 @property
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       torch.manual_seed(0						)

       UpperCAmelCase    : int      =UNetaDModel(**self.dummy_super_res_kwargs						)
       return model
 @property
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       torch.manual_seed(1						)

       UpperCAmelCase    : List[str]      =UNetaDModel(**self.dummy_super_res_kwargs						)
       return model
 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =self.dummy_prior
       UpperCAmelCase    : Tuple      =self.dummy_decoder
       UpperCAmelCase    : List[str]      =self.dummy_text_proj
       UpperCAmelCase    : Any      =self.dummy_text_encoder
       UpperCAmelCase    : Any      =self.dummy_tokenizer
       UpperCAmelCase    : int      =self.dummy_super_res_first
       UpperCAmelCase    : Optional[int]      =self.dummy_super_res_last

       UpperCAmelCase    : Any      =UnCLIPScheduler(
           variance_type='''fixed_small_log'''		,   prediction_type='''sample'''		,   num_train_timesteps=1000		,   clip_sample_range=5.0		,   )

       UpperCAmelCase    : Dict      =UnCLIPScheduler(
           variance_type='''learned_range'''		,   prediction_type='''epsilon'''		,   num_train_timesteps=1000		,   )

       UpperCAmelCase    : List[Any]      =UnCLIPScheduler(
           variance_type='''fixed_small_log'''		,   prediction_type='''epsilon'''		,   num_train_timesteps=1000		,   )

       UpperCAmelCase    : Union[str, Any]      ={
           '''prior''': prior,
           '''decoder''': decoder,
           '''text_proj''': text_proj,
           '''text_encoder''': text_encoder,
           '''tokenizer''': tokenizer,
           '''super_res_first''': super_res_first,
           '''super_res_last''': super_res_last,
           '''prior_scheduler''': prior_scheduler,
           '''decoder_scheduler''': decoder_scheduler,
           '''super_res_scheduler''': super_res_scheduler,
       }

       return components
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__=0						)	->							int:
       '''simple docstring'''





       if str(snake_case__						).startswith('''mps'''						):
             UpperCAmelCase    : List[str]      =torch.manual_seed(snake_case__						)
       else:
             UpperCAmelCase    : Optional[Any]      =torch.Generator(device=snake_case__						).manual_seed(snake_case__						)
       UpperCAmelCase    : int      ={
           '''prompt''': '''horse''',
           '''generator''': generator,
           '''prior_num_inference_steps''': 2,
           '''decoder_num_inference_steps''': 2,
           '''super_res_num_inference_steps''': 2,
           '''output_type''': '''numpy''',
       }
       return inputs
 def 	UpperCAmelCase__       (  self						)	->							Any:
       '''simple docstring'''





       UpperCAmelCase    : Tuple      ='''cpu'''

       UpperCAmelCase    : Any      =self.get_dummy_components()

       UpperCAmelCase    : str      =self.pipeline_class(**snake_case__						)
       UpperCAmelCase    : Dict      =pipe.to(snake_case__						)

       pipe.set_progress_bar_config(disable=snake_case__						)

       UpperCAmelCase    : Tuple      =pipe(**self.get_dummy_inputs(snake_case__						)						)
       UpperCAmelCase    : List[str]      =output.images

       UpperCAmelCase    : List[Any]      =pipe(
           **self.get_dummy_inputs(snake_case__						)		,   return_dict=snake_case__		,   )[0]

       UpperCAmelCase    : Optional[int]      =image[0, -3:, -3:, -1]
       UpperCAmelCase    : Any      =image_from_tuple[0, -3:, -3:, -1]

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

       UpperCAmelCase    : Union[str, Any]      =np.array(
           [
               0.9997,
               0.9988,
               0.0028,
               0.9997,
               0.9984,
               0.9965,
               0.0029,
               0.9986,
               0.0025,
           ]						)

       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1e-2
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : Union[str, Any]      =torch.device('''cpu'''						)







       class 			__snake_case   :
        __lowerCamelCase    :   Optional[int]     =      1



       UpperCAmelCase    : Union[str, Any]      =self.get_dummy_components()

       UpperCAmelCase    : List[str]      =self.pipeline_class(**snake_case__						)
       UpperCAmelCase    : int      =pipe.to(snake_case__						)

       UpperCAmelCase    : int      =components['''prior''']
       UpperCAmelCase    : Any      =components['''decoder''']
       UpperCAmelCase    : List[str]      =components['''super_res_first''']
       UpperCAmelCase    : Union[str, Any]      =components['''tokenizer''']
       UpperCAmelCase    : Union[str, Any]      =components['''text_encoder''']

       UpperCAmelCase    : List[Any]      =torch.Generator(device=snake_case__						).manual_seed(0						)
       UpperCAmelCase    : Any      =prior.dtype
       UpperCAmelCase    : int      =1

       UpperCAmelCase    : List[str]      =(batch_size, prior.config.embedding_dim)
       UpperCAmelCase    : Tuple      =pipe.prepare_latents(
           snake_case__		,   dtype=snake_case__		,   device=snake_case__		,   generator=snake_case__		,   latents=snake_case__		,   scheduler=DummyScheduler()						)
       UpperCAmelCase    : Union[str, Any]      =(batch_size, decoder.config.in_channels, decoder.config.sample_size, decoder.config.sample_size)
       UpperCAmelCase    : Dict      =pipe.prepare_latents(
           snake_case__		,   dtype=snake_case__		,   device=snake_case__		,   generator=snake_case__		,   latents=snake_case__		,   scheduler=DummyScheduler()						)

       UpperCAmelCase    : Tuple      =(
           batch_size,
           super_res_first.config.in_channels // 2,
           super_res_first.config.sample_size,
           super_res_first.config.sample_size,
       )
       UpperCAmelCase    : Tuple      =pipe.prepare_latents(
           snake_case__		,   dtype=snake_case__		,   device=snake_case__		,   generator=snake_case__		,   latents=snake_case__		,   scheduler=DummyScheduler()						)

       pipe.set_progress_bar_config(disable=snake_case__						)

       UpperCAmelCase    : Any      ='''this is a prompt example'''

       UpperCAmelCase    : Union[str, Any]      =torch.Generator(device=snake_case__						).manual_seed(0						)
       UpperCAmelCase    : Tuple      =pipe(
           [prompt]		,   generator=snake_case__		,   prior_num_inference_steps=2		,   decoder_num_inference_steps=2		,   super_res_num_inference_steps=2		,   prior_latents=snake_case__		,   decoder_latents=snake_case__		,   super_res_latents=snake_case__		,   output_type='''np'''		,   )
       UpperCAmelCase    : Dict      =output.images

       UpperCAmelCase    : Any      =tokenizer(
           snake_case__		,   padding='''max_length'''		,   max_length=tokenizer.model_max_length		,   return_tensors='''pt'''		,   )
       UpperCAmelCase    : Optional[int]      =text_encoder(text_inputs.input_ids						)
       UpperCAmelCase    : Union[str, Any]      =text_inputs.attention_mask

       UpperCAmelCase    : List[str]      =torch.Generator(device=snake_case__						).manual_seed(0						)
       UpperCAmelCase    : str      =pipe(
           generator=snake_case__		,   prior_num_inference_steps=2		,   decoder_num_inference_steps=2		,   super_res_num_inference_steps=2		,   prior_latents=snake_case__		,   decoder_latents=snake_case__		,   super_res_latents=snake_case__		,   text_model_output=snake_case__		,   text_attention_mask=snake_case__		,   output_type='''np'''		,   )[0]

       # make sure passing text embeddings manually is identical
       assert np.abs(image - image_from_text						).max() < 1e-4
 @skip_mps
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       UpperCAmelCase    : Optional[int]      =torch_device == '''cpu'''

       self._test_attention_slicing_forward_pass(test_max_difference=snake_case__		,   expected_max_diff=0.01						)
 @skip_mps
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase    : int      =torch_device == '''cpu'''
       UpperCAmelCase    : Any      =True
       UpperCAmelCase    : Any      =[
           '''prior_num_inference_steps''',
           '''decoder_num_inference_steps''',
           '''super_res_num_inference_steps''',
       ]

       self._test_inference_batch_single_identical(
           test_max_difference=snake_case__		,   relax_max_difference=snake_case__		,   additional_params_copy_to_batched_inputs=snake_case__		,   )
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =[
           '''prior_num_inference_steps''',
           '''decoder_num_inference_steps''',
           '''super_res_num_inference_steps''',
       ]

       if torch_device == "mps":
             # TODO: MPS errors with larger batch sizes
             UpperCAmelCase    : Any      =[2, 3]
             self._test_inference_batch_consistent(
                 batch_sizes=snake_case__		,   additional_params_copy_to_batched_inputs=snake_case__		,   )
       else:
             self._test_inference_batch_consistent(
                 additional_params_copy_to_batched_inputs=snake_case__						)
 @skip_mps
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       return super().test_dict_tuple_outputs_equivalent()
 @skip_mps
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       return super().test_save_load_local()






 @skip_mps
 def 	UpperCAmelCase__       (  self						)	->							List[str]:
       '''simple docstring'''





       return super().test_save_load_optional_components()







@nightly
class 			__snake_case   (     unittest.TestCase   ):
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





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






 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/unclip/karlo_v1_alpha_horse_cpu.npy'''						)

       UpperCAmelCase    : List[Any]      =UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''						)
       pipeline.set_progress_bar_config(disable=snake_case__						)

       UpperCAmelCase    : List[Any]      =torch.manual_seed(0						)
       UpperCAmelCase    : List[str]      =pipeline(
           '''horse'''		,   num_images_per_prompt=1		,   generator=snake_case__		,   output_type='''np'''		,   )

       UpperCAmelCase    : Union[str, Any]      =output.images[0]

       assert image.shape == (256, 256, 3)
       assert np.abs(expected_image - image						).max() < 1e-1







@slow
@require_torch_gpu
class 			__snake_case   (     unittest.TestCase   ):
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()
 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       UpperCAmelCase    : int      =load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/unclip/karlo_v1_alpha_horse_fp16.npy'''						)

       UpperCAmelCase    : Dict      =UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''		,   torch_dtype=torch.floataa						)
       UpperCAmelCase    : Optional[int]      =pipeline.to(snake_case__						)
       pipeline.set_progress_bar_config(disable=snake_case__						)

       UpperCAmelCase    : str      =torch.Generator(device='''cpu'''						).manual_seed(0						)
       UpperCAmelCase    : List[Any]      =pipeline(
           '''horse'''		,   generator=snake_case__		,   output_type='''np'''		,   )

       UpperCAmelCase    : Dict      =output.images[0]

       assert image.shape == (256, 256, 3)

       assert_mean_pixel_difference(snake_case__		,   snake_case__						)






 def 	UpperCAmelCase__       (  self						)	->							List[Any]:
       '''simple docstring'''





       torch.cuda.empty_cache()
       torch.cuda.reset_max_memory_allocated()
       torch.cuda.reset_peak_memory_stats()

       UpperCAmelCase    : List[Any]      =UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''		,   torch_dtype=torch.floataa						)
       UpperCAmelCase    : List[str]      =pipe.to(snake_case__						)
       pipe.set_progress_bar_config(disable=snake_case__						)
       pipe.enable_attention_slicing()
       pipe.enable_sequential_cpu_offload()

       UpperCAmelCase    : int      =pipe(
           '''horse'''		,   num_images_per_prompt=1		,   prior_num_inference_steps=2		,   decoder_num_inference_steps=2		,   super_res_num_inference_steps=2		,   output_type='''np'''		,   )

       UpperCAmelCase    : str      =torch.cuda.max_memory_allocated()
       # make sure that less than 7 GB is allocated
       assert mem_bytes < 7 * 10**9

import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile
from typing import List

from datasets import config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.info_utils import VerificationMode





def   lowerCAmelCase_ (				__lowerCAmelCase		,					**__lowerCAmelCase						)->  Union[str, Any]:






      '''simple docstring'''





      return RunBeamCommand(
          args.dataset		,					args.name		,					args.cache_dir		,					args.beam_pipeline_options		,					args.data_dir		,					args.all_configs		,					args.save_info or args.save_infos		,					args.ignore_verifications		,					args.force_redownload		,					**__lowerCAmelCase		,					)







class 			__snake_case   (     lowerCamelCase__   ):
 @staticmethod
 def 	UpperCAmelCase__       (  snake_case__						)	->							List[str]:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =parser.add_parser('''run_beam'''		,   help='''Run a Beam dataset processing pipeline'''						)
       run_beam_parser.add_argument('''dataset'''		,   type=snake_case__		,   help='''Name of the dataset to download'''						)
       run_beam_parser.add_argument('''--name'''		,   type=snake_case__		,   default=snake_case__		,   help='''Dataset config name'''						)
       run_beam_parser.add_argument(
           '''--cache_dir'''		,   type=snake_case__		,   default=snake_case__		,   help='''Cache directory where the datasets are stored'''		,   )
       run_beam_parser.add_argument(
           '''--beam_pipeline_options'''		,   type=snake_case__		,   default=''''''		,   help='''Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`'''		,   )
       run_beam_parser.add_argument(
           '''--data_dir'''		,   type=snake_case__		,   default=snake_case__		,   help='''Can be used to specify a manual directory to get the files from'''		,   )
       run_beam_parser.add_argument('''--all_configs'''		,   action='''store_true'''		,   help='''Test all dataset configurations'''						)
       run_beam_parser.add_argument('''--save_info'''		,   action='''store_true'''		,   help='''Save the dataset infos file'''						)
       run_beam_parser.add_argument(
           '''--ignore_verifications'''		,   action='''store_true'''		,   help='''Run the test without checksums and splits checks'''						)
       run_beam_parser.add_argument('''--force_redownload'''		,   action='''store_true'''		,   help='''Force dataset redownload'''						)
       # aliases
       run_beam_parser.add_argument('''--save_infos'''		,   action='''store_true'''		,   help='''alias for save_info'''						)
       run_beam_parser.set_defaults(func=snake_case__						)
 def __init__(  self		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__		,   **snake_case__		,   )	->							Any:
       '''simple docstring'''





       UpperCAmelCase    : str      =dataset
       UpperCAmelCase    : Optional[Any]      =name
       UpperCAmelCase    : str      =cache_dir
       UpperCAmelCase    : Union[str, Any]      =beam_pipeline_options
       UpperCAmelCase    : List[str]      =data_dir
       UpperCAmelCase    : int      =all_configs
       UpperCAmelCase    : List[Any]      =save_infos
       UpperCAmelCase    : Dict      =ignore_verifications
       UpperCAmelCase    : Optional[int]      =force_redownload
       UpperCAmelCase    : Optional[int]      =config_kwargs






 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       import apache_beam as beam

       if self._name is not None and self._all_configs:
             print('''Both parameters `name` and `all_configs` can\'t be used at once.'''						)
             exit(1						)
       UpperCAmelCase  ,						UpperCAmelCase    : str      =self._dataset, self._name
       UpperCAmelCase    : Any      =dataset_module_factory(snake_case__						)
       UpperCAmelCase    : str      =import_main_class(dataset_module.module_path						)
       UpperCAmelCase    : List[DatasetBuilder]      =[]
       if self._beam_pipeline_options:
             UpperCAmelCase    : Optional[Any]      =beam.options.pipeline_options.PipelineOptions(
                 flags=[f'''--{opt.strip()}''' for opt in self._beam_pipeline_options.split(''','''						) if opt]						)
       else:
             UpperCAmelCase    : int      =None
       if self._all_configs and len(builder_cls.BUILDER_CONFIGS						) > 0:
             for builder_config in builder_cls.BUILDER_CONFIGS:
                   builders.append(
                       builder_cls(
                           config_name=builder_config.name		,   data_dir=self._data_dir		,   hash=dataset_module.hash		,   beam_options=snake_case__		,   cache_dir=self._cache_dir		,   base_path=dataset_module.builder_kwargs.get('''base_path'''						)		,   )						)
       else:
             builders.append(
                 builder_cls(
                     config_name=snake_case__		,   data_dir=self._data_dir		,   beam_options=snake_case__		,   cache_dir=self._cache_dir		,   base_path=dataset_module.builder_kwargs.get('''base_path'''						)		,   **self._config_kwargs		,   )						)

       for builder in builders:
             builder.download_and_prepare(
                 download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                 if not self._force_redownload
                 else DownloadMode.FORCE_REDOWNLOAD		,   download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH						)		,   verification_mode=VerificationMode.NO_CHECKS
                 if self._ignore_verifications
                 else VerificationMode.ALL_CHECKS		,   try_from_hf_gcs=snake_case__		,   )
             if self._save_infos:
                   builder._save_infos()

       print('''Apache beam run successful.'''						)

       # If save_infos=True, the dataset infos file is created next to the loaded module file.
       # Let's move it to the original directory of the dataset script, to allow the user to
       # upload them on S3 at the same time afterwards.
       if self._save_infos:
             UpperCAmelCase    : Dict      =os.path.join(builder_cls.get_imported_module_dir()		,   config.DATASETDICT_INFOS_FILENAME						)

             UpperCAmelCase    : List[str]      =Path(snake_case__						).name + '''.py'''

             UpperCAmelCase    : Tuple      =os.path.join(snake_case__		,   snake_case__						)
             if os.path.isfile(snake_case__						):
                   UpperCAmelCase    : Dict      =os.path.dirname(snake_case__						)
             elif os.path.isfile(snake_case__						):
                   UpperCAmelCase    : Union[str, Any]      =path
             else:  # in case of a remote dataset
                   print(f'''Dataset Infos file saved at {dataset_infos_path}'''						)
                   exit(1						)

             # Move datasetinfo back to the user
             UpperCAmelCase    : Tuple      =os.path.join(snake_case__		,   config.DATASETDICT_INFOS_FILENAME						)
             copyfile(snake_case__		,   snake_case__						)
             print(f'''Dataset Infos file saved at {user_dataset_infos_path}'''						)
