

'''simple docstring'''






from typing import List, Optional, Union

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

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


snake_case_					  =	logging.get_logger(__name__)  # pylint: disable=invalid-name

snake_case_					  =	'\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)["depth"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline("depth-estimation")\n\n        >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to("cuda")\n\n        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to("cuda")\n\n        >>> img = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/cat.png"\n        ... ).resize((768, 768))\n\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n        >>> prompt = "A robot, 4k photo"\n        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n        >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)\n        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)\n\n        >>> images = pipe(\n        ...     image=img,\n        ...     strength=0.5,\n        ...     image_embeds=img_emb.image_embeds,\n        ...     negative_image_embeds=negative_emb.image_embeds,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save("robot_cat.png")\n        ```\n'

def  __lowerCamelCase      (				SCREAMING_SNAKE_CASE_					:     int  ,  SCREAMING_SNAKE_CASE_					:     str  ,  SCREAMING_SNAKE_CASE_					:     Dict=8   )							->       Optional[Any]:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_				:      Any					=	height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      SCREAMING_SNAKE_CASE_				:      Tuple					=	width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor

def  __lowerCamelCase      (				SCREAMING_SNAKE_CASE_					:     Union[str, Any]  ,  SCREAMING_SNAKE_CASE_					:     Any=5_1_2  ,  SCREAMING_SNAKE_CASE_					:     List[Any]=5_1_2   )							->       Optional[Any]:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	pil_image.resize((w, h)  ,  resample=Image.BICUBIC  ,  reducing_gap=1   )
      SCREAMING_SNAKE_CASE_				:      List[str]					=	np.array(pil_image.convert("RGB"   )   )
      SCREAMING_SNAKE_CASE_				:      int					=	arr.astype(np.floataa   ) / 127.5 - 1
      SCREAMING_SNAKE_CASE_				:      Any					=	np.transpose(SCREAMING_SNAKE_CASE_  ,  [2, 0, 1]   )
      SCREAMING_SNAKE_CASE_				:      List[Any]					=	torch.from_numpy(SCREAMING_SNAKE_CASE_   ).unsqueeze(0   )
      return image





class      SCREAMING_SNAKE_CASE__      (    _UpperCAmelCase				):




    def __init__( self    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					):






          """simple docstring"""






          super().__init__()

          self.register_modules(
              unet=lowercase__    ,					scheduler=lowercase__    ,					movq=lowercase__    ,					)
          SCREAMING_SNAKE_CASE_				:      Dict					=	2 ** (len(self.movq.config.block_out_channels      ) - 1)




    def   __lowerCamelCase				( self    ,					lowercase__    ,					lowercase__    ,					lowercase__      ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	min(int(num_inference_steps * strength      )    ,					lowercase__      )

          SCREAMING_SNAKE_CASE_				:      Dict					=	max(num_inference_steps - init_timestep    ,					0      )
          SCREAMING_SNAKE_CASE_				:      List[Any]					=	self.scheduler.timesteps[t_start:]

          return timesteps, num_inference_steps - t_start




    def   __lowerCamelCase				( self    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__=None      ):






          """simple docstring"""






          if not isinstance(lowercase__    ,					(torch.Tensor, PIL.Image.Image, list)      ):
                raise ValueError(
                    F"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowercase__      )}"      )

          SCREAMING_SNAKE_CASE_				:      str					=	image.to(device=lowercase__    ,					dtype=lowercase__      )

          SCREAMING_SNAKE_CASE_				:      List[Any]					=	batch_size * num_images_per_prompt

          if image.shape[1] == 4:
                SCREAMING_SNAKE_CASE_				:      Dict					=	image

          else:
                if isinstance(lowercase__    ,					lowercase__      ) and len(lowercase__      ) != batch_size:
                      raise ValueError(
                          F"You have passed a list of generators of length {len(lowercase__      )}, but requested an effective batch"
                          F" size of {batch_size}. Make sure the batch size matches the length of the generators."      )

                elif isinstance(lowercase__    ,					lowercase__      ):
                      SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	[
                          self.movq.encode(image[i : i + 1]      ).latent_dist.sample(generator[i]      ) for i in range(lowercase__      )
                      ]
                      SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	torch.cat(lowercase__    ,					dim=0      )
                else:
                      SCREAMING_SNAKE_CASE_				:      List[str]					=	self.movq.encode(lowercase__      ).latent_dist.sample(lowercase__      )

                SCREAMING_SNAKE_CASE_				:      Any					=	self.movq.config.scaling_factor * init_latents

          SCREAMING_SNAKE_CASE_				:      Tuple					=	torch.cat([init_latents]    ,					dim=0      )

          SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	init_latents.shape
          SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	randn_tensor(lowercase__    ,					generator=lowercase__    ,					device=lowercase__    ,					dtype=lowercase__      )

          # get latents
          SCREAMING_SNAKE_CASE_				:      str					=	self.scheduler.add_noise(lowercase__    ,					lowercase__    ,					lowercase__      )

          SCREAMING_SNAKE_CASE_				:      Optional[int]					=	init_latents

          return latents




    def   __lowerCamelCase				( self    ,					lowercase__=0      ):






          """simple docstring"""






          if is_accelerate_available():
                from accelerate import cpu_offload
          else:
                raise ImportError("Please install accelerate via `pip install accelerate`"      )

          SCREAMING_SNAKE_CASE_				:      List[Any]					=	torch.device(F"cuda:{gpu_id}"      )

          SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	[
              self.unet,
              self.movq,
          ]
          for cpu_offloaded_model in models:
                if cpu_offloaded_model is not None:
                      cpu_offload(lowercase__    ,					lowercase__      )




    def   __lowerCamelCase				( self    ,					lowercase__=0      ):






          """simple docstring"""






          if is_accelerate_available() and is_accelerate_version(">="    ,					"0.17.0.dev0"      ):
                from accelerate import cpu_offload_with_hook
          else:
                raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."      )

          SCREAMING_SNAKE_CASE_				:      Dict					=	torch.device(F"cuda:{gpu_id}"      )

          if self.device.type != "cpu":
                self.to("cpu"    ,					silence_dtype_warnings=lowercase__      )
                torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

          SCREAMING_SNAKE_CASE_				:      int					=	None
          for cpu_offloaded_model in [self.unet, self.movq]:
                SCREAMING_SNAKE_CASE_				:      str					=	cpu_offload_with_hook(lowercase__    ,					lowercase__    ,					prev_module_hook=lowercase__      )

          # We'll offload the last model manually.
          SCREAMING_SNAKE_CASE_				:      Any					=	hook




    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def   __lowerCamelCase				( self      ):






          """simple docstring"""






          if not hasattr(self.unet    ,					"_hf_hook"      ):
                return self.device
          for module in self.unet.modules():
                if (
                    hasattr(lowercase__    ,					"_hf_hook"      )
                    and hasattr(module._hf_hook    ,					"execution_device"      )
                    and module._hf_hook.execution_device is not None
                ):
                      return torch.device(module._hf_hook.execution_device      )
          return self.device







    @torch.no_grad()
    @replace_example_docstring(lowercase__      )
    def __call__( self    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__ = 512    ,					lowercase__ = 512    ,					lowercase__ = 100    ,					lowercase__ = 4.0    ,					lowercase__ = 0.3    ,					lowercase__ = 1    ,					lowercase__ = None    ,					lowercase__ = "pil"    ,					lowercase__ = True    ,					):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      int					=	self._execution_device

          SCREAMING_SNAKE_CASE_				:      str					=	guidance_scale > 1.0

          if isinstance(lowercase__    ,					lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      int					=	torch.cat(lowercase__    ,					dim=0      )
          if isinstance(lowercase__    ,					lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	torch.cat(lowercase__    ,					dim=0      )
          if isinstance(lowercase__    ,					lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	torch.cat(lowercase__    ,					dim=0      )

          SCREAMING_SNAKE_CASE_				:      List[Any]					=	image_embeds.shape[0]

          if do_classifier_free_guidance:
                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	image_embeds.repeat_interleave(lowercase__    ,					dim=0      )
                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	negative_image_embeds.repeat_interleave(lowercase__    ,					dim=0      )
                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	hint.repeat_interleave(lowercase__    ,					dim=0      )

          SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	torch.cat([negative_image_embeds, image_embeds]    ,					dim=0      ).to(dtype=self.unet.dtype    ,					device=lowercase__      )
          SCREAMING_SNAKE_CASE_				:      List[Any]					=	torch.cat([hint, hint]    ,					dim=0      ).to(dtype=self.unet.dtype    ,					device=lowercase__      )

          if not isinstance(lowercase__    ,					lowercase__      ):
                SCREAMING_SNAKE_CASE_				:      List[Any]					=	[image]
          if not all(isinstance(lowercase__    ,					(PIL.Image.Image, torch.Tensor)      ) for i in image      ):
                raise ValueError(
                    F"Input is in incorrect format: {[type(lowercase__      ) for i in image]}. Currently, we only support  PIL image and pytorch tensor"      )

          SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	torch.cat([prepare_image(lowercase__    ,					lowercase__    ,					lowercase__      ) for i in image]    ,					dim=0      )
          SCREAMING_SNAKE_CASE_				:      Dict					=	image.to(dtype=image_embeds.dtype    ,					device=lowercase__      )

          SCREAMING_SNAKE_CASE_				:      List[Any]					=	self.movq.encode(lowercase__      )["latents"]
          SCREAMING_SNAKE_CASE_				:      Any					=	latents.repeat_interleave(lowercase__    ,					dim=0      )
          self.scheduler.set_timesteps(lowercase__    ,					device=lowercase__      )
          SCREAMING_SNAKE_CASE_				:      str					=	self.get_timesteps(lowercase__    ,					lowercase__    ,					lowercase__      )
          SCREAMING_SNAKE_CASE_				:      str					=	timesteps[:1].repeat(batch_size * num_images_per_prompt      )
          SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	downscale_height_and_width(lowercase__    ,					lowercase__    ,					self.movq_scale_factor      )
          SCREAMING_SNAKE_CASE_				:      str					=	self.prepare_latents(
              lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					image_embeds.dtype    ,					lowercase__    ,					lowercase__      )
          for i, t in enumerate(self.progress_bar(lowercase__      )      ):
                # expand the latents if we are doing classifier free guidance
                SCREAMING_SNAKE_CASE_				:      Tuple					=	torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents

                SCREAMING_SNAKE_CASE_				:      List[Any]					=	{"image_embeds": image_embeds, "hint": hint}
                SCREAMING_SNAKE_CASE_				:      Dict					=	self.unet(
                    sample=lowercase__    ,					timestep=lowercase__    ,					encoder_hidden_states=lowercase__    ,					added_cond_kwargs=lowercase__    ,					return_dict=lowercase__    ,					)[0]

                if do_classifier_free_guidance:
                      SCREAMING_SNAKE_CASE_				:      str					=	noise_pred.split(latents.shape[1]    ,					dim=1      )
                      SCREAMING_SNAKE_CASE_				:      Any					=	noise_pred.chunk(2      )
                      SCREAMING_SNAKE_CASE_				:      List[Any]					=	variance_pred.chunk(2      )
                      SCREAMING_SNAKE_CASE_				:      Tuple					=	noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                      SCREAMING_SNAKE_CASE_				:      Dict					=	torch.cat([noise_pred, variance_pred_text]    ,					dim=1      )

                if not (
                    hasattr(self.scheduler.config    ,					"variance_type"      )
                    and self.scheduler.config.variance_type in ["learned", "learned_range"]
                ):
                      SCREAMING_SNAKE_CASE_				:      Dict					=	noise_pred.split(latents.shape[1]    ,					dim=1      )

                # compute the previous noisy sample x_t -> x_t-1

                SCREAMING_SNAKE_CASE_				:      str					=	self.scheduler.step(
                    lowercase__    ,					lowercase__    ,					lowercase__    ,					generator=lowercase__    ,					)[0]

          # post-processing
          SCREAMING_SNAKE_CASE_				:      int					=	self.movq.decode(lowercase__    ,					force_not_quantize=lowercase__      )["sample"]

          if output_type not in ["pt", "np", "pil"]:
                raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"      )

          if output_type in ["np", "pil"]:
                SCREAMING_SNAKE_CASE_				:      str					=	image * 0.5 + 0.5
                SCREAMING_SNAKE_CASE_				:      Union[str, Any]					=	image.clamp(0    ,					1      )
                SCREAMING_SNAKE_CASE_				:      Dict					=	image.cpu().permute(0    ,					2    ,					3    ,					1      ).float().numpy()

          if output_type == "pil":
                SCREAMING_SNAKE_CASE_				:      Optional[Any]					=	self.numpy_to_pil(lowercase__      )

          if not return_dict:
                return (image,)

          return ImagePipelineOutput(images=lowercase__      )




'''simple docstring'''






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      (				SCREAMING_SNAKE_CASE_					:     int  ,  **SCREAMING_SNAKE_CASE_					:     int   )							->       str:
      """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  ,  **SCREAMING_SNAKE_CASE_  ,  )





class      SCREAMING_SNAKE_CASE__      (    _UpperCAmelCase				):




    @staticmethod
    def   __lowerCamelCase				( lowercase__      ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_				:      str					=	parser.add_parser("run_beam"    ,					help="Run a Beam dataset processing pipeline"      )
          run_beam_parser.add_argument("dataset"    ,					type=lowercase__    ,					help="Name of the dataset to download"      )
          run_beam_parser.add_argument("--name"    ,					type=lowercase__    ,					default=lowercase__    ,					help="Dataset config name"      )
          run_beam_parser.add_argument(
              "--cache_dir"    ,					type=lowercase__    ,					default=lowercase__    ,					help="Cache directory where the datasets are stored"    ,					)
          run_beam_parser.add_argument(
              "--beam_pipeline_options"    ,					type=lowercase__    ,					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=lowercase__    ,					default=lowercase__    ,					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=lowercase__      )




    def __init__( self    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					lowercase__    ,					**lowercase__    ,					):






          """simple docstring"""






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







    def   __lowerCamelCase				( self      ):






          """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      )
          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_				:      Any					=	self._dataset, self._name
          SCREAMING_SNAKE_CASE_				:      List[str]					=	dataset_module_factory(lowercase__      )
          SCREAMING_SNAKE_CASE_				:      Optional[int]					=	import_main_class(dataset_module.module_path      )
          SCREAMING_SNAKE_CASE_				:      List[DatasetBuilder]					=	[]
          if self._beam_pipeline_options:
                SCREAMING_SNAKE_CASE_				:      List[str]					=	beam.options.pipeline_options.PipelineOptions(
                    flags=[F"--{opt.strip()}" for opt in self._beam_pipeline_options.split(","      ) if opt]      )
          else:
                SCREAMING_SNAKE_CASE_				:      Dict					=	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=lowercase__    ,					cache_dir=self._cache_dir    ,					base_path=dataset_module.builder_kwargs.get("base_path"      )    ,					)      )
          else:
                builders.append(
                    builder_cls(
                        config_name=lowercase__    ,					data_dir=self._data_dir    ,					beam_options=lowercase__    ,					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=lowercase__    ,					)
                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:
                SCREAMING_SNAKE_CASE_				:      Dict					=	os.path.join(builder_cls.get_imported_module_dir()    ,					config.DATASETDICT_INFOS_FILENAME      )

                SCREAMING_SNAKE_CASE_				:      List[Any]					=	Path(lowercase__      ).name + ".py"

                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	os.path.join(lowercase__    ,					lowercase__      )
                if os.path.isfile(lowercase__      ):
                      SCREAMING_SNAKE_CASE_				:      Any					=	os.path.dirname(lowercase__      )
                elif os.path.isfile(lowercase__      ):
                      SCREAMING_SNAKE_CASE_				:      List[str]					=	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
                SCREAMING_SNAKE_CASE_				:      Optional[int]					=	os.path.join(lowercase__    ,					config.DATASETDICT_INFOS_FILENAME      )
                copyfile(lowercase__    ,					lowercase__      )
                print(F"Dataset Infos file saved at {user_dataset_infos_path}"      )

