






'''simple docstring'''
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

UpperCamelCase__ =			'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'


@dataclass
class        _UpperCAmelCase						(		snake_case			):
    __lowerCamelCase:   Union[PIL.Image.Image, np.ndarray]


class        _UpperCAmelCase						(		snake_case			):




    def __init__(			self  :       Union[str, Any]  ,     a  :       PriorTransformer  ,     a  :       CLIPVisionModel  ,     a  :       CLIPImageProcessor  ,     a  :       HeunDiscreteScheduler  ,     a  :       ShapERenderer  ,     ):






       '''simple docstring'''






       super().__init__()

       self.register_modules(
           prior=a  ,     image_encoder=a  ,     image_processor=a  ,     scheduler=a  ,     renderer=a  ,     )




    def 				lowerCAmelCase__				(			self  :       List[str]  ,     a  :       List[Any]  ,     a  :       List[str]  ,     a  :       str  ,     a  :       str  ,     a  :       Tuple  ,     a  :       Tuple			):






       '''simple docstring'''






       if latents is None:
          lowercase_	:    Any           =     randn_tensor(a  ,     generator=a  ,     device=a  ,     dtype=a			)
       else:
          if latents.shape != shape:
             raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""			)
          lowercase_	:    Optional[int]           =     latents.to(a			)

       lowercase_	:    Optional[int]           =     latents * scheduler.init_noise_sigma
       return latents




    def 				lowerCAmelCase__				(			self  :       Dict  ,     a  :       Union[str, Any]=0			):






       '''simple docstring'''






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

       lowercase_	:    Optional[int]           =     torch.device(f"""cuda:{gpu_id}"""			)

       lowercase_	:    Union[str, Any]           =     [self.image_encoder, self.prior]
       for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
             cpu_offload(a  ,     a			)




    @property
    def 				lowerCAmelCase__				(			self  :       Optional[Any]			):






       '''simple docstring'''






       if self.device != torch.device("meta"			) or not hasattr(self.image_encoder  ,     "_hf_hook"			):
          return self.device
       for module in self.image_encoder.modules():
          if (
              hasattr(a  ,     "_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




    def 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       List[str]  ,     a  :       List[Any]  ,     a  :       Any  ,     a  :       Optional[int]  ,     ):






       '''simple docstring'''






       if isinstance(a  ,     a			) and isinstance(image[0]  ,     torch.Tensor			):
          lowercase_	:    List[str]           =     torch.cat(a  ,     axis=0			) if image[0].ndim == 4 else torch.stack(a  ,     axis=0			)

       if not isinstance(a  ,     torch.Tensor			):
          lowercase_	:    Any           =     self.image_processor(a  ,     return_tensors="pt"			).pixel_values[0].unsqueeze(0			)

       lowercase_	:    Optional[Any]           =     image.to(dtype=self.image_encoder.dtype  ,     device=a			)

       lowercase_	:    int           =     self.image_encoder(a			)["last_hidden_state"]
       lowercase_	:    Tuple           =     image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       lowercase_	:    Dict           =     image_embeds.repeat_interleave(a  ,     dim=0			)

       if do_classifier_free_guidance:
          lowercase_	:    Union[str, Any]           =     torch.zeros_like(a			)

          # For classifier free guidance, we need to do two forward passes.
          # Here we concatenate the unconditional and text embeddings into a single batch
          # to avoid doing two forward passes
          lowercase_	:    List[str]           =     torch.cat([negative_image_embeds, image_embeds]			)

       return image_embeds





    @torch.no_grad()
    @replace_example_docstring(a			)
    def __call__(			self  :       Tuple  ,     a  :       Union[PIL.Image.Image, List[PIL.Image.Image]]  ,     a  :       int = 1  ,     a  :       int = 2_5  ,     a  :       Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,     a  :       Optional[torch.FloatTensor] = None  ,     a  :       float = 4.0  ,     a  :       int = 6_4  ,     a  :       Optional[str] = "pil"  ,     a  :       bool = True  ,     ):






       '''simple docstring'''






       if isinstance(a  ,     PIL.Image.Image			):
          lowercase_	:    Optional[Any]           =     1
       elif isinstance(a  ,     torch.Tensor			):
          lowercase_	:    str           =     image.shape[0]
       elif isinstance(a  ,     a			) and isinstance(image[0]  ,     (torch.Tensor, PIL.Image.Image)			):
          lowercase_	:    Tuple           =     len(a			)
       else:
          raise ValueError(
              f"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(a			)}"""			)

       lowercase_	:    Union[str, Any]           =     self._execution_device

       lowercase_	:    Dict           =     batch_size * num_images_per_prompt

       lowercase_	:    Dict           =     guidance_scale > 1.0
       lowercase_	:    Optional[Any]           =     self._encode_image(a  ,     a  ,     a  ,     a			)

       # prior

       self.scheduler.set_timesteps(a  ,     device=a			)
       lowercase_	:    Any           =     self.scheduler.timesteps

       lowercase_	:    List[str]           =     self.prior.config.num_embeddings
       lowercase_	:    Optional[int]           =     self.prior.config.embedding_dim

       lowercase_	:    str           =     self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)  ,     image_embeds.dtype  ,     a  ,     a  ,     a  ,     self.scheduler  ,     )

       # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
       lowercase_	:    Dict           =     latents.reshape(latents.shape[0]  ,     a  ,     a			)

       for i, t in enumerate(self.progress_bar(a			)			):
          # expand the latents if we are doing classifier free guidance
          lowercase_	:    Dict           =     torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
          lowercase_	:    Any           =     self.scheduler.scale_model_input(a  ,     a			)

          lowercase_	:    List[Any]           =     self.prior(
              a  ,     timestep=a  ,     proj_embedding=a  ,     ).predicted_image_embedding

          # remove the variance
          lowercase_	:    Optional[Any]           =     noise_pred.split(
              scaled_model_input.shape[2]  ,     dim=2			)  # batch_size, num_embeddings, embedding_dim

          if do_classifier_free_guidance is not None:
             lowercase_	:    Dict           =     noise_pred.chunk(2			)
             lowercase_	:    List[str]           =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

          lowercase_	:    List[Any]           =     self.scheduler.step(
              a  ,     timestep=a  ,     sample=a  ,     ).prev_sample

       if output_type == "latent":
          return ShapEPipelineOutput(images=a			)

       lowercase_	:    Any           =     []
       for i, latent in enumerate(a			):
          print()
          lowercase_	:    Optional[int]           =     self.renderer.decode(
              latent[None, :]  ,     a  ,     size=a  ,     ray_batch_size=4_0_9_6  ,     n_coarse_samples=6_4  ,     n_fine_samples=1_2_8  ,     )

          images.append(a			)

       lowercase_	:    int           =     torch.stack(a			)

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

       lowercase_	:    str           =     images.cpu().numpy()

       if output_type == "pil":
          lowercase_	:    Optional[int]           =     [self.numpy_to_pil(a			) for image in images]

       # Offload last model to CPU
       if hasattr(self  ,     "final_offload_hook"			) and self.final_offload_hook is not None:
          self.final_offload_hook.offload()

       if not return_dict:
          return (images,)

       return ShapEPipelineOutput(images=a			)












'''simple docstring'''
import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader


class        _UpperCAmelCase						(		snake_case			):




    def __init__(			self  :       Tuple  ,     a  :       NestedDataStructureLike[PathLike]  ,     a  :       Optional[NamedSplit] = None  ,     a  :       Optional[Features] = None  ,     a  :       str = None  ,     a  :       bool = False  ,     a  :       bool = False  ,     a  :       Optional[str] = None  ,     a  :       Optional[int] = None  ,     **a  :       List[Any]  ,     ):






       '''simple docstring'''






       super().__init__(
           a  ,     split=a  ,     features=a  ,     cache_dir=a  ,     keep_in_memory=a  ,     streaming=a  ,     num_proc=a  ,     **a  ,     )
       lowercase_	:    str           =     field
       lowercase_	:    Optional[Any]           =     path_or_paths if isinstance(a  ,     a			) else {self.split: path_or_paths}
       lowercase_	:    Any           =     Json(
           cache_dir=a  ,     data_files=a  ,     features=a  ,     field=a  ,     **a  ,     )





    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       if self.streaming:
          lowercase_	:    Any           =     self.builder.as_streaming_dataset(split=self.split			)
       # Build regular (map-style) dataset
       else:
          lowercase_	:    Dict           =     None
          lowercase_	:    Optional[int]           =     None
          lowercase_	:    str           =     None
          lowercase_	:    str           =     None

          self.builder.download_and_prepare(
              download_config=a  ,     download_mode=a  ,     verification_mode=a  ,     base_path=a  ,     num_proc=self.num_proc  ,     )
          lowercase_	:    int           =     self.builder.as_dataset(
              split=self.split  ,     verification_mode=a  ,     in_memory=self.keep_in_memory			)
       return dataset


class        _UpperCAmelCase						:




    def __init__(			self  :       str  ,     a  :       Dataset  ,     a  :       Union[PathLike, BinaryIO]  ,     a  :       Optional[int] = None  ,     a  :       Optional[int] = None  ,     **a  :       List[Any]  ,     ):






       '''simple docstring'''






       if num_proc is not None and num_proc <= 0:
          raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""			)

       lowercase_	:    Dict           =     dataset
       lowercase_	:    Optional[int]           =     path_or_buf
       lowercase_	:    List[Any]           =     batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
       lowercase_	:    Optional[Any]           =     num_proc
       lowercase_	:    List[Any]           =     "utf-8"
       lowercase_	:    List[str]           =     to_json_kwargs




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    str           =     self.to_json_kwargs.pop("path_or_buf"  ,     a			)
       lowercase_	:    Any           =     self.to_json_kwargs.pop("orient"  ,     "records"			)
       lowercase_	:    Any           =     self.to_json_kwargs.pop("lines"  ,     True if orient == "records" else False			)
       lowercase_	:    List[str]           =     self.to_json_kwargs.pop("index"  ,     False if orient in ["split", "table"] else True			)
       lowercase_	:    int           =     self.to_json_kwargs.pop("compression"  ,     a			)

       if compression not in [None, "infer", "gzip", "bz2", "xz"]:
          raise NotImplementedError(f"""`datasets` currently does not support {compression} compression"""			)

       if isinstance(self.path_or_buf  ,     (str, bytes, os.PathLike)			):
          with fsspec.open(self.path_or_buf  ,     "wb"  ,     compression=a			) as buffer:
             lowercase_	:    Dict           =     self._write(file_obj=a  ,     orient=a  ,     lines=a  ,     index=a  ,     **self.to_json_kwargs			)
       else:
          if compression:
             raise NotImplementedError(
                 f"""The compression parameter is not supported when writing to a buffer, but compression={compression}"""
                 " was passed. Please provide a local path instead."			)
          lowercase_	:    Dict           =     self._write(
              file_obj=self.path_or_buf  ,     orient=a  ,     lines=a  ,     index=a  ,     **self.to_json_kwargs			)
       return written




    def 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       List[str]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_	:    List[Any]           =     args

       lowercase_	:    Optional[int]           =     query_table(
           table=self.dataset.data  ,     key=slice(a  ,     offset + self.batch_size			)  ,     indices=self.dataset._indices  ,     )
       lowercase_	:    Dict           =     batch.to_pandas().to_json(
           path_or_buf=a  ,     orient=a  ,     lines=a  ,     index=a  ,     **a			)
       if not json_str.endswith("\n"			):
          json_str += "\n"
       return json_str.encode(self.encoding			)





    def 				lowerCAmelCase__				(			self  :       int  ,     a  :       BinaryIO  ,     a  :       int  ,     a  :       str  ,     a  :       Union[str, Any]  ,     **a  :       str  ,     ):






       '''simple docstring'''






       lowercase_	:    Union[str, Any]           =     0

       if self.num_proc is None or self.num_proc == 1:
          for offset in logging.tqdm(
              range(0  ,     len(self.dataset			)  ,     self.batch_size			)  ,     unit="ba"  ,     disable=not logging.is_progress_bar_enabled()  ,     desc="Creating json from Arrow format"  ,     ):
             lowercase_	:    Dict           =     self._batch_json((offset, orient, lines, index, to_json_kwargs)			)
             written += file_obj.write(a			)
       else:
          lowercase_    ,		lowercase_	:    Any           =     len(self.dataset			), self.batch_size
          with multiprocessing.Pool(self.num_proc			) as pool:
             for json_str in logging.tqdm(
                 pool.imap(
                     self._batch_json  ,     [(offset, orient, lines, index, to_json_kwargs) for offset in range(0  ,     a  ,     a			)]  ,     )  ,     total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size  ,     unit="ba"  ,     disable=not logging.is_progress_bar_enabled()  ,     desc="Creating json from Arrow format"  ,     ):
                written += file_obj.write(a			)

       return written




