


import csv
import os

import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.csv import CsvDatasetReader, CsvDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases




def       a__						(		snake_case__				:       Optional[int]	,      snake_case__				:       List[Any]    ):
  assert isinstance(snake_case__	,      snake_case__    )
  assert dataset.num_rows == 4
  assert dataset.num_columns == 3
  assert dataset.column_names == ["col_1", "col_2", "col_3"]
  for feature, expected_dtype in expected_features.items():
    assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""	,      [False, True]    )
def       a__						(		snake_case__				:       Dict	,      snake_case__				:       Union[str, Any]	,      snake_case__				:       Union[str, Any]    ):
  _UpperCAmelCase		:       Dict       =    tmp_path / """cache"""
  _UpperCAmelCase		:       List[Any]       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
    _UpperCAmelCase		:       Tuple       =    CsvDatasetReader(snake_case__	,      cache_dir=snake_case__	,      keep_in_memory=snake_case__    ).read()
  _check_csv_dataset(snake_case__	,      snake_case__    )




@pytest.mark.parametrize(
    """features"""	,      [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]	,      )
def       a__						(		snake_case__				:       Optional[Any]	,      snake_case__				:       int	,      snake_case__				:       Optional[Any]    ):
  _UpperCAmelCase		:       Optional[Any]       =    tmp_path / """cache"""
  # CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
  _UpperCAmelCase		:       Union[str, Any]       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  _UpperCAmelCase		:       Any       =    features.copy() if features else default_expected_features
  _UpperCAmelCase		:       Union[str, Any]       =    (
      Features({feature: Value(snake_case__    ) for feature, dtype in features.items()}    ) if features is not None else None
  )
  _UpperCAmelCase		:       Dict       =    CsvDatasetReader(snake_case__	,      features=snake_case__	,      cache_dir=snake_case__    ).read()
  _check_csv_dataset(snake_case__	,      snake_case__    )




@pytest.mark.parametrize("""split"""	,      [None, NamedSplit("""train"""    ), """train""", """test"""]    )
def       a__						(		snake_case__				:       Dict	,      snake_case__				:       int	,      snake_case__				:       Dict    ):
  _UpperCAmelCase		:       List[Any]       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Optional[Any]       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  _UpperCAmelCase		:       List[str]       =    CsvDatasetReader(snake_case__	,      cache_dir=snake_case__	,      split=snake_case__    ).read()
  _check_csv_dataset(snake_case__	,      snake_case__    )
  assert dataset.split == split if split else "train"




@pytest.mark.parametrize("""path_type"""	,      [str, list]    )
def       a__						(		snake_case__				:       Optional[Any]	,      snake_case__				:       Tuple	,      snake_case__				:       Dict    ):
  if issubclass(snake_case__	,      snake_case__    ):
    _UpperCAmelCase		:       str       =    csv_path
  elif issubclass(snake_case__	,      snake_case__    ):
    _UpperCAmelCase		:       List[Any]       =    [csv_path]
  _UpperCAmelCase		:       str       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Dict       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  _UpperCAmelCase		:       Optional[Any]       =    CsvDatasetReader(snake_case__	,      cache_dir=snake_case__    ).read()
  _check_csv_dataset(snake_case__	,      snake_case__    )




def       a__						(		snake_case__				:       Tuple	,      snake_case__				:       Optional[Any]	,      snake_case__				:       int=("train",)    ):
  assert isinstance(snake_case__	,      snake_case__    )
  for split in splits:
    _UpperCAmelCase		:       Dict       =    dataset_dict[split]
    assert dataset.num_rows == 4
    assert dataset.num_columns == 3
    assert dataset.column_names == ["col_1", "col_2", "col_3"]
    for feature, expected_dtype in expected_features.items():
      assert dataset.features[feature].dtype == expected_dtype




@pytest.mark.parametrize("""keep_in_memory"""	,      [False, True]    )
def       a__						(		snake_case__				:       Optional[Any]	,      snake_case__				:       Any	,      snake_case__				:       Tuple    ):
  _UpperCAmelCase		:       Dict       =    tmp_path / """cache"""
  _UpperCAmelCase		:       int       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
    _UpperCAmelCase		:       Any       =    CsvDatasetReader({"""train""": csv_path}	,      cache_dir=snake_case__	,      keep_in_memory=snake_case__    ).read()
  _check_csv_datasetdict(snake_case__	,      snake_case__    )




@pytest.mark.parametrize(
    """features"""	,      [
        None,
        {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""},
        {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""},
        {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""},
        {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""},
    ]	,      )
def       a__						(		snake_case__				:       Optional[int]	,      snake_case__				:       List[Any]	,      snake_case__				:       List[Any]    ):
  _UpperCAmelCase		:       Tuple       =    tmp_path / """cache"""
  # CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
  _UpperCAmelCase		:       Any       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  _UpperCAmelCase		:       Dict       =    features.copy() if features else default_expected_features
  _UpperCAmelCase		:       Optional[int]       =    (
      Features({feature: Value(snake_case__    ) for feature, dtype in features.items()}    ) if features is not None else None
  )
  _UpperCAmelCase		:       Optional[Any]       =    CsvDatasetReader({"""train""": csv_path}	,      features=snake_case__	,      cache_dir=snake_case__    ).read()
  _check_csv_datasetdict(snake_case__	,      snake_case__    )




@pytest.mark.parametrize("""split"""	,      [None, NamedSplit("""train"""    ), """train""", """test"""]    )
def       a__						(		snake_case__				:       Union[str, Any]	,      snake_case__				:       Any	,      snake_case__				:       List[Any]    ):
  if split:
    _UpperCAmelCase		:       Dict       =    {split: csv_path}
  else:
    _UpperCAmelCase		:       Any       =    {"""train""": csv_path, """test""": csv_path}
  _UpperCAmelCase		:       List[str]       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Optional[int]       =    {"""col_1""": """int64""", """col_2""": """int64""", """col_3""": """float64"""}
  _UpperCAmelCase		:       Union[str, Any]       =    CsvDatasetReader(snake_case__	,      cache_dir=snake_case__    ).read()
  _check_csv_datasetdict(snake_case__	,      snake_case__	,      splits=list(path.keys()    )    )
  assert all(dataset[split].split == split for split in path.keys()    )




def       a__						(		snake_case__				:       int    ):
  with open(snake_case__	,      encoding="""utf-8"""    ) as csvfile:
    yield from csv.reader(snake_case__    )




def       a__						(		snake_case__				:       Any	,      snake_case__				:       Optional[int]    ):
  _UpperCAmelCase		:       str       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Union[str, Any]       =    os.path.join(snake_case__	,      """tmp.csv"""    )
  _UpperCAmelCase		:       Optional[Any]       =    CsvDatasetReader({"""train""": csv_path}	,      cache_dir=snake_case__    ).read()
  CsvDatasetWriter(dataset["""train"""]	,      snake_case__	,      num_proc=1    ).write()

  _UpperCAmelCase		:       Union[str, Any]       =    iter_csv_file(snake_case__    )
  _UpperCAmelCase		:       Union[str, Any]       =    iter_csv_file(snake_case__    )

  for rowa, rowa in zip(snake_case__	,      snake_case__    ):
    assert rowa == rowa




def       a__						(		snake_case__				:       List[str]	,      snake_case__				:       Optional[Any]    ):
  _UpperCAmelCase		:       Any       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Any       =    os.path.join(snake_case__	,      """tmp.csv"""    )
  _UpperCAmelCase		:       str       =    CsvDatasetReader({"""train""": csv_path}	,      cache_dir=snake_case__    ).read()
  CsvDatasetWriter(dataset["""train"""]	,      snake_case__	,      num_proc=2    ).write()

  _UpperCAmelCase		:       List[str]       =    iter_csv_file(snake_case__    )
  _UpperCAmelCase		:       Dict       =    iter_csv_file(snake_case__    )

  for rowa, rowa in zip(snake_case__	,      snake_case__    ):
    assert rowa == rowa





def       a__						(		snake_case__				:       Tuple	,      snake_case__				:       Dict    ):
  _UpperCAmelCase		:       Tuple       =    tmp_path / """cache"""
  _UpperCAmelCase		:       Tuple       =    os.path.join(snake_case__	,      """tmp.csv"""    )
  _UpperCAmelCase		:       List[Any]       =    CsvDatasetReader({"""train""": csv_path}	,      cache_dir=snake_case__    ).read()
  with pytest.raises(snake_case__    ):
    CsvDatasetWriter(dataset["""train"""]	,      snake_case__	,      num_proc=0    )









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


SCREAMING_SNAKE_CASE__				:    Optional[int]         =    logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE__				:    Tuple         =    '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\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], "shark_3d.gif")\n        ```\n'


@dataclass
class 		_SCREAMING_SNAKE_CASE    (	A    ):
     __SCREAMING_SNAKE_CASE    				=						42


class 		_SCREAMING_SNAKE_CASE    (	A    ):


     def __init__(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				):
       super().__init__()

       self.register_modules(
           prior=A_       ,				text_encoder=A_       ,				tokenizer=A_       ,				scheduler=A_       ,				renderer=A_       ,				)


     def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_						):
       if latents is None:
         _UpperCAmelCase		:       List[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}'''						)
         _UpperCAmelCase		:       Optional[int]       =    latents.to(A_						)

       _UpperCAmelCase		:       str       =    latents * scheduler.init_noise_sigma
       return latents


     def 					__snake_case(     self       ,				A_=0						):
       if is_accelerate_available():
         from accelerate import cpu_offload
       else:
         raise ImportError("""Please install accelerate via `pip install accelerate`"""						)

       _UpperCAmelCase		:       Any       =    torch.device(F'''cuda:{gpu_id}'''						)

       _UpperCAmelCase		:       Dict       =    [self.text_encoder, self.prior]
       for cpu_offloaded_model in models:
         if cpu_offloaded_model is not None:
           cpu_offload(A_       ,				A_						)


     def 					__snake_case(     self       ,				A_=0						):
       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."""						)

       _UpperCAmelCase		:       int       =    torch.device(F'''cuda:{gpu_id}'''						)

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

       _UpperCAmelCase		:       List[str]       =    None
       for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
         _UpperCAmelCase,_UpperCAmelCase		:       List[Any]       =    cpu_offload_with_hook(A_       ,				A_       ,				prev_module_hook=A_						)

       if self.safety_checker is not None:
         _UpperCAmelCase,_UpperCAmelCase		:       int       =    cpu_offload_with_hook(self.safety_checker       ,				A_       ,				prev_module_hook=A_						)

       # We'll offload the last model manually.
       _UpperCAmelCase		:       Optional[Any]       =    hook


     @property
     def 					__snake_case(     self						):
       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(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 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				):
       len(A_						) if isinstance(A_       ,				A_						) else 1

       # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
       _UpperCAmelCase		:       str       =    0
       # get prompt text embeddings
       _UpperCAmelCase		:       List[str]       =    self.tokenizer(
           A_       ,				padding="""max_length"""       ,				max_length=self.tokenizer.model_max_length       ,				truncation=A_       ,				return_tensors="""pt"""       ,				)
       _UpperCAmelCase		:       Any       =    text_inputs.input_ids
       _UpperCAmelCase		:       Dict       =    self.tokenizer(A_       ,				padding="""longest"""       ,				return_tensors="""pt"""						).input_ids

       if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(A_       ,				A_						):
         _UpperCAmelCase		:       Union[str, Any]       =    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}'''						)

       _UpperCAmelCase		:       List[Any]       =    self.text_encoder(text_input_ids.to(A_						)						)
       _UpperCAmelCase		:       Union[str, Any]       =    text_encoder_output.text_embeds

       _UpperCAmelCase		:       Tuple       =    prompt_embeds.repeat_interleave(A_       ,				dim=0						)
       # in Shap-E it normalize the prompt_embeds and then later rescale it
       _UpperCAmelCase		:       Any       =    prompt_embeds / torch.linalg.norm(A_       ,				dim=-1       ,				keepdim=A_						)

       if do_classifier_free_guidance:
         _UpperCAmelCase		:       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
         _UpperCAmelCase		:       Optional[Any]       =    torch.cat([negative_prompt_embeds, prompt_embeds]						)

       # Rescale the features to have unit variance
       _UpperCAmelCase		:       List[Any]       =    math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds

       return prompt_embeds




     @torch.no_grad()
     @replace_example_docstring(A_						)
     def __call__(     self       ,				A_       ,				A_ = 1       ,				A_ = 25       ,				A_ = None       ,				A_ = None       ,				A_ = 4.0       ,				A_ = 64       ,				A_ = "pil"       ,				A_ = True       ,				):

       if isinstance(A_       ,				A_						):
         _UpperCAmelCase		:       Optional[int]       =    1
       elif isinstance(A_       ,				A_						):
         _UpperCAmelCase		:       Union[str, Any]       =    len(A_						)
       else:
         raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A_						)}'''						)

       _UpperCAmelCase		:       Tuple       =    self._execution_device

       _UpperCAmelCase		:       List[str]       =    batch_size * num_images_per_prompt

       _UpperCAmelCase		:       str       =    guidance_scale > 1.0
       _UpperCAmelCase		:       Tuple       =    self._encode_prompt(A_       ,				A_       ,				A_       ,				A_						)

       # prior

       self.scheduler.set_timesteps(A_       ,				device=A_						)
       _UpperCAmelCase		:       Any       =    self.scheduler.timesteps

       _UpperCAmelCase		:       List[str]       =    self.prior.config.num_embeddings
       _UpperCAmelCase		:       Union[str, Any]       =    self.prior.config.embedding_dim

       _UpperCAmelCase		:       Optional[Any]       =    self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)       ,				prompt_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
       _UpperCAmelCase		:       Optional[Any]       =    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
         _UpperCAmelCase		:       Optional[int]       =    torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
         _UpperCAmelCase		:       Union[str, Any]       =    self.scheduler.scale_model_input(A_       ,				A_						)

         _UpperCAmelCase		:       Any       =    self.prior(
             A_       ,				timestep=A_       ,				proj_embedding=A_       ,				).predicted_image_embedding

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

         if do_classifier_free_guidance is not None:
           _UpperCAmelCase,_UpperCAmelCase		:       Union[str, Any]       =    noise_pred.chunk(2						)
           _UpperCAmelCase		:       List[Any]       =    noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

         _UpperCAmelCase		:       Tuple       =    self.scheduler.step(
             A_       ,				timestep=A_       ,				sample=A_       ,				).prev_sample

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

       _UpperCAmelCase		:       Dict       =    []
       for i, latent in enumerate(A_						):
         _UpperCAmelCase		:       int       =    self.renderer.decode(
             latent[None, :]       ,				A_       ,				size=A_       ,				ray_batch_size=40_96       ,				n_coarse_samples=64       ,				n_fine_samples=1_28       ,				)
         images.append(A_						)

       _UpperCAmelCase		:       List[Any]       =    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}'''						)

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

       if output_type == "pil":
         _UpperCAmelCase		:       List[str]       =    [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_						)





