code: 
  
  
  """simple docstring"""
  import math
  from dataclasses import dataclass
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  import torch
  from transformers import CLIPTextModelWithProjection, CLIPTokenizer
  
  from ...models import PriorTransformer
  from ...pipelines import DiffusionPipeline
  from ...schedulers import HeunDiscreteScheduler
  from ...utils import (
      BaseOutput,
      is_accelerate_available,
      is_accelerate_version,
      logging,
      randn_tensor,
      replace_example_docstring,
  )
  from .renderer import ShapERenderer
  
  
  UpperCAmelCase   =	logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  UpperCAmelCase   =	"""
      Examples:
          ```py
          >>> import torch
          >>> from diffusers import DiffusionPipeline
          >>> from diffusers.utils import export_to_gif
  
          >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")
  
          >>> repo = \"openai/shap-e\"
          >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
          >>> pipe = pipe.to(device)
  
          >>> guidance_scale = 15.0
          >>> prompt = \"a shark\"
  
          >>> images = pipe(
          ...     prompt,
          ...     guidance_scale=guidance_scale,
          ...     num_inference_steps=64,
          ...     frame_size=256,
          ... ).images
  
          >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
          ```
  """
  
  
  
  
  @dataclass
  class   lowercase__							(				A_							):
     __UpperCAmelCase       					=				42
  
  
  
  
  
  
  
  class   lowercase__							(				A_							):
  
  
  
  
  
     def __init__(       self			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      )     ->     Optional[int]:
        super().__init__()
  
        self.register_modules(
            prior=SCREAMING_SNAKE_CASE			,      text_encoder=SCREAMING_SNAKE_CASE			,      tokenizer=SCREAMING_SNAKE_CASE			,      scheduler=SCREAMING_SNAKE_CASE			,      renderer=SCREAMING_SNAKE_CASE			,      )
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)     ->     Optional[int]:
        if latents is None:
           _lowerCamelCase  :				Tuple      =		randn_tensor(SCREAMING_SNAKE_CASE			,      generator=SCREAMING_SNAKE_CASE			,      device=SCREAMING_SNAKE_CASE			,      dtype=SCREAMING_SNAKE_CASE)
        else:
           if latents.shape != shape:
              raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}')
           _lowerCamelCase  :				Union[str, Any]      =		latents.to(SCREAMING_SNAKE_CASE)
  
        _lowerCamelCase  :				Union[str, Any]      =		latents * scheduler.init_noise_sigma
        return latents
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE=0)     ->     int:
        if is_accelerate_available():
           from accelerate import cpu_offload
        else:
           raise ImportError("""Please install accelerate via `pip install accelerate`""")
  
        _lowerCamelCase  :				int      =		torch.device(F'cuda:{gpu_id}')
  
        _lowerCamelCase  :				int      =		[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
           if cpu_offloaded_model is not None:
              cpu_offload(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE=0)     ->     Tuple:
        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.""")
  
        _lowerCamelCase  :				List[Any]      =		torch.device(F'cuda:{gpu_id}')
  
        if self.device.type != "cpu":
           self.to("""cpu"""			,      silence_dtype_warnings=SCREAMING_SNAKE_CASE)
           torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
        _lowerCamelCase  :				Union[str, Any]      =		None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
           _lowerCamelCase  :				Any      =		cpu_offload_with_hook(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      prev_module_hook=SCREAMING_SNAKE_CASE)
  
        if self.safety_checker is not None:
           _lowerCamelCase  :				str      =		cpu_offload_with_hook(self.safety_checker			,      SCREAMING_SNAKE_CASE			,      prev_module_hook=SCREAMING_SNAKE_CASE)
  
        # We'll offload the last model manually.
        _lowerCamelCase  :				List[str]      =		hook
  
  
  
  
  
     @property
     def 		UpperCamelCase_     (       self)     ->     Union[str, Any]:
        if self.device != torch.device("""meta""") or not hasattr(self.text_encoder			,      """_hf_hook"""):
           return self.device
        for module in self.text_encoder.modules():
           if (
               hasattr(SCREAMING_SNAKE_CASE			,      """_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 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      )     ->     Union[str, Any]:
        len(SCREAMING_SNAKE_CASE) if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE) else 1
  
        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        _lowerCamelCase  :				List[str]      =		0
        # get prompt text embeddings
        _lowerCamelCase  :				List[str]      =		self.tokenizer(
            SCREAMING_SNAKE_CASE			,      padding="""max_length"""			,      max_length=self.tokenizer.model_max_length			,      truncation=SCREAMING_SNAKE_CASE			,      return_tensors="""pt"""			,      )
        _lowerCamelCase  :				List[str]      =		text_inputs.input_ids
        _lowerCamelCase  :				Tuple      =		self.tokenizer(SCREAMING_SNAKE_CASE			,      padding="""longest"""			,      return_tensors="""pt""").input_ids
  
        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
           _lowerCamelCase  :				str      =		self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
           logger.warning(
               """The following part of your input was truncated because CLIP can only handle sequences up to"""
               F' {self.tokenizer.model_max_length} tokens: {removed_text}')
  
        _lowerCamelCase  :				List[str]      =		self.text_encoder(text_input_ids.to(SCREAMING_SNAKE_CASE))
        _lowerCamelCase  :				int      =		text_encoder_output.text_embeds
  
        _lowerCamelCase  :				Union[str, Any]      =		prompt_embeds.repeat_interleave(SCREAMING_SNAKE_CASE			,      dim=0)
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        _lowerCamelCase  :				Tuple      =		prompt_embeds / torch.linalg.norm(SCREAMING_SNAKE_CASE			,      dim=-1			,      keepdim=SCREAMING_SNAKE_CASE)
  
        if do_classifier_free_guidance:
           _lowerCamelCase  :				Optional[Any]      =		torch.zeros_like(SCREAMING_SNAKE_CASE)
  
           # 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
           _lowerCamelCase  :				Dict      =		torch.cat([negative_prompt_embeds, prompt_embeds])
  
        # Rescale the features to have unit variance
        _lowerCamelCase  :				str      =		math.sqrt(prompt_embeds.shape[1]) * prompt_embeds
  
        return prompt_embeds
  
  
  
  
  
     @torch.no_grad()
     @replace_example_docstring(SCREAMING_SNAKE_CASE)
     def __call__(       self			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE = 1			,      SCREAMING_SNAKE_CASE = 25			,      SCREAMING_SNAKE_CASE = None			,      SCREAMING_SNAKE_CASE = None			,      SCREAMING_SNAKE_CASE = 4.0			,      SCREAMING_SNAKE_CASE = 64			,      SCREAMING_SNAKE_CASE = "pil"			,      SCREAMING_SNAKE_CASE = True			,      )     ->     Any:
  
        if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
           _lowerCamelCase  :				Optional[int]      =		1
        elif isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
           _lowerCamelCase  :				Optional[Any]      =		len(SCREAMING_SNAKE_CASE)
        else:
           raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE)}')
  
        _lowerCamelCase  :				Optional[int]      =		self._execution_device
  
        _lowerCamelCase  :				Optional[Any]      =		batch_size * num_images_per_prompt
  
        _lowerCamelCase  :				List[Any]      =		guidance_scale > 1.0
        _lowerCamelCase  :				Dict      =		self._encode_prompt(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
  
        # prior
  
        self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE			,      device=SCREAMING_SNAKE_CASE)
        _lowerCamelCase  :				str      =		self.scheduler.timesteps
  
        _lowerCamelCase  :				str      =		self.prior.config.num_embeddings
        _lowerCamelCase  :				Dict      =		self.prior.config.embedding_dim
  
        _lowerCamelCase  :				str      =		self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)			,      prompt_embeds.dtype			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE			,      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
        _lowerCamelCase  :				Dict      =		latents.reshape(latents.shape[0]			,      SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
  
        for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE)):
           # expand the latents if we are doing classifier free guidance
           _lowerCamelCase  :				Optional[Any]      =		torch.cat([latents] * 2) if do_classifier_free_guidance else latents
           _lowerCamelCase  :				Dict      =		self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
  
           _lowerCamelCase  :				str      =		self.prior(
               SCREAMING_SNAKE_CASE			,      timestep=SCREAMING_SNAKE_CASE			,      proj_embedding=SCREAMING_SNAKE_CASE			,      ).predicted_image_embedding
  
           # remove the variance
           _lowerCamelCase  :				List[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:
              _lowerCamelCase  :				Any      =		noise_pred.chunk(2)
              _lowerCamelCase  :				List[str]      =		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
           _lowerCamelCase  :				Union[str, Any]      =		self.scheduler.step(
               SCREAMING_SNAKE_CASE			,      timestep=SCREAMING_SNAKE_CASE			,      sample=SCREAMING_SNAKE_CASE			,      ).prev_sample
  
        if output_type == "latent":
           return ShapEPipelineOutput(images=SCREAMING_SNAKE_CASE)
  
        _lowerCamelCase  :				Tuple      =		[]
        for i, latent in enumerate(SCREAMING_SNAKE_CASE):
           _lowerCamelCase  :				Dict      =		self.renderer.decode(
               latent[None, :]			,      SCREAMING_SNAKE_CASE			,      size=SCREAMING_SNAKE_CASE			,      ray_batch_size=4096			,      n_coarse_samples=64			,      n_fine_samples=128			,      )
           images.append(SCREAMING_SNAKE_CASE)
  
        _lowerCamelCase  :				List[str]      =		torch.stack(SCREAMING_SNAKE_CASE)
  
        if output_type not in ["np", "pil"]:
           raise ValueError(F'Only the output types `pil` and `np` are supported not output_type={output_type}')
  
        _lowerCamelCase  :				List[str]      =		images.cpu().numpy()
  
        if output_type == "pil":
           _lowerCamelCase  :				Optional[Any]      =		[self.numpy_to_pil(SCREAMING_SNAKE_CASE) 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=SCREAMING_SNAKE_CASE)
  
style_context: 
  
  
  """simple docstring"""
  import itertools
  from dataclasses import dataclass
  from io import StringIO
  from typing import Optional
  
  import pyarrow as pa
  
  import datasets
  from datasets.features.features import require_storage_cast
  from datasets.table import table_cast
  
  
  UpperCAmelCase   =	datasets.utils.logging.get_logger(__name__)
  
  
  
  
  @dataclass
  class   lowercase__							(				datasets.BuilderConfig							):
     __UpperCAmelCase       					=				None
     __UpperCAmelCase       					=				"utf-8"
     __UpperCAmelCase       					=				None
     __UpperCAmelCase       					=				10 << 20  # 10MB
     __UpperCAmelCase       					=				False
     __UpperCAmelCase       					=				"line"
  
  
  
  
  
  
  
  class   lowercase__							(				datasets.ArrowBasedBuilder							):
     __UpperCAmelCase       					=				TextConfig
  
  
  
  
  
     def 		UpperCamelCase_     (       self)     ->     int:
        return datasets.DatasetInfo(features=self.config.features)
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     Optional[int]:
        if not self.config.data_files:
           raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}')
        _lowerCamelCase  :				Dict      =		dl_manager.download_and_extract(self.config.data_files)
        if isinstance(SCREAMING_SNAKE_CASE			,      (str, list, tuple)):
           _lowerCamelCase  :				Optional[Any]      =		data_files
           if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
              _lowerCamelCase  :				List[Any]      =		[files]
           _lowerCamelCase  :				List[str]      =		[dl_manager.iter_files(SCREAMING_SNAKE_CASE) for file in files]
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,      gen_kwargs={"""files""": files})]
        _lowerCamelCase  :				int      =		[]
        for split_name, files in data_files.items():
           if isinstance(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE):
              _lowerCamelCase  :				Any      =		[files]
           _lowerCamelCase  :				Any      =		[dl_manager.iter_files(SCREAMING_SNAKE_CASE) for file in files]
           splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE			,      gen_kwargs={"""files""": files}))
        return splits
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     pa.Table:
        if self.config.features is not None:
           _lowerCamelCase  :				Union[str, Any]      =		self.config.features.arrow_schema
           if all(not require_storage_cast(SCREAMING_SNAKE_CASE) for feature in self.config.features.values()):
              # cheaper cast
              _lowerCamelCase  :				Any      =		pa_table.cast(SCREAMING_SNAKE_CASE)
           else:
              # more expensive cast; allows str <-> int/float or str to Audio for example
              _lowerCamelCase  :				Any      =		table_cast(SCREAMING_SNAKE_CASE			,      SCREAMING_SNAKE_CASE)
           return pa_table
        else:
           return pa_table.cast(pa.schema({"""text""": pa.string()}))
  
  
  
  
  
     def 		UpperCamelCase_     (       self			,      SCREAMING_SNAKE_CASE)     ->     Any:
        _lowerCamelCase  :				Optional[Any]      =		list(self.config.features) if self.config.features is not None else ["""text"""]
        for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE)):
           # open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n"
           with open(SCREAMING_SNAKE_CASE			,      encoding=self.config.encoding			,      errors=self.config.errors) as f:
              if self.config.sample_by == "line":
                 _lowerCamelCase  :				Union[str, Any]      =		0
                 while True:
                    _lowerCamelCase  :				int      =		f.read(self.config.chunksize)
                    if not batch:
                       break
                    batch += f.readline()  # finish current line
                    # StringIO.readlines, by default splits only on "\n" (and keeps line breaks)
                    _lowerCamelCase  :				List[str]      =		StringIO(SCREAMING_SNAKE_CASE).readlines()
                    if not self.config.keep_linebreaks:
                       _lowerCamelCase  :				Optional[Any]      =		[line.rstrip("""\n""") for line in batch]
                    _lowerCamelCase  :				Any      =		pa.Table.from_arrays([pa.array(SCREAMING_SNAKE_CASE)]			,      names=SCREAMING_SNAKE_CASE)
                    # Uncomment for debugging (will print the Arrow table size and elements)
                    # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                    # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                    yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
                    batch_idx += 1
              elif self.config.sample_by == "paragraph":
                 _lowerCamelCase  :				Optional[Any]      =		0
                 _lowerCamelCase  :				Dict      =		""""""
                 while True:
                    _lowerCamelCase  :				Union[str, Any]      =		f.read(self.config.chunksize)
                    if not new_batch:
                       break
                    batch += new_batch
                    batch += f.readline()  # finish current line
                    _lowerCamelCase  :				Any      =		batch.split("""\n\n""")
                    _lowerCamelCase  :				Dict      =		pa.Table.from_arrays(
                        [pa.array([example for example in batch[:-1] if example])]			,      names=SCREAMING_SNAKE_CASE)
                    # Uncomment for debugging (will print the Arrow table size and elements)
                    # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                    # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                    yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
                    batch_idx += 1
                    _lowerCamelCase  :				Union[str, Any]      =		batch[-1]
                 if batch:
                    _lowerCamelCase  :				Optional[int]      =		pa.Table.from_arrays([pa.array([batch])]			,      names=SCREAMING_SNAKE_CASE)
                    yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE)
              elif self.config.sample_by == "document":
                 _lowerCamelCase  :				Tuple      =		f.read()
                 _lowerCamelCase  :				List[Any]      =		pa.Table.from_arrays([pa.array([text])]			,      names=SCREAMING_SNAKE_CASE)
                 yield file_idx, self._cast_table(SCREAMING_SNAKE_CASE)
  
  