



"""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


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

A    =	'\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 			_a     (   SCREAMING_SNAKE_CASE__):
			__magic_name__    				=    42



class 			_a     (   SCREAMING_SNAKE_CASE__):



			def __init__( self       :							Any      ,  _lowercase       :							PriorTransformer      ,  _lowercase       :							CLIPTextModelWithProjection      ,  _lowercase       :							CLIPTokenizer      ,  _lowercase       :							HeunDiscreteScheduler      ,  _lowercase       :							ShapERenderer      ,  )       ->				Optional[Any]:
									super().__init__()

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



			def 							__lowercase				( self       :							Tuple      ,  _lowercase       :							int      ,  _lowercase       :							Any      ,  _lowercase       :							Union[str, Any]      ,  _lowercase       :							Dict      ,  _lowercase       :							Optional[Any]      ,  _lowercase       :							Any		)       ->				List[str]:
									if latents is None:
															snake_case      : List[Any]							=   randn_tensor(_lowercase      ,  generator=_lowercase      ,  device=_lowercase      ,  dtype=_lowercase		)
									else:
															if latents.shape != shape:
																					raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''		)
															snake_case      : Optional[Any]							=   latents.to(_lowercase		)

									snake_case      : Tuple							=   latents * scheduler.init_noise_sigma
									return latents



			def 							__lowercase				( self       :							Union[str, Any]      ,  _lowercase       :							List[Any]=0		)       ->				int:
									if is_accelerate_available():
															from accelerate import cpu_offload
									else:
															raise ImportError("Please install accelerate via `pip install accelerate`"		)

									snake_case      : str							=   torch.device(F'''cuda:{gpu_id}'''		)

									snake_case      : Union[str, Any]							=   [self.text_encoder, self.prior]
									for cpu_offloaded_model in models:
															if cpu_offloaded_model is not None:
																					cpu_offload(_lowercase      ,  _lowercase		)



			def 							__lowercase				( self       :							List[Any]      ,  _lowercase       :							Optional[Any]=0		)       ->				List[str]:
									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."		)

									snake_case      : Optional[Any]							=   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)

									snake_case      : List[Any]							=   None
									for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
															snake_case						, snake_case      : Optional[int]							=   cpu_offload_with_hook(_lowercase      ,  _lowercase      ,  prev_module_hook=_lowercase		)

									if self.safety_checker is not None:
															snake_case						, snake_case      : Optional[int]							=   cpu_offload_with_hook(self.safety_checker      ,  _lowercase      ,  prev_module_hook=_lowercase		)

									# We'll offload the last model manually.
									snake_case      : Union[str, Any]							=   hook



			@property
			def 							__lowercase				( self       :							List[Any]		)       ->				Tuple:
									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(_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



			def 							__lowercase				( self       :							Optional[int]      ,  _lowercase       :							Union[str, Any]      ,  _lowercase       :							Union[str, Any]      ,  _lowercase       :							List[Any]      ,  _lowercase       :							str      ,  )       ->				List[str]:
									len(_lowercase		) if isinstance(_lowercase      ,  _lowercase		) else 1

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

									if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_lowercase      ,  _lowercase		):
															snake_case      : 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}'''		)

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

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

									if do_classifier_free_guidance:
															snake_case      : List[Any]							=   torch.zeros_like(_lowercase		)

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

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

									return prompt_embeds



			@torch.no_grad()
			@replace_example_docstring(_lowercase		)
			def __call__( self       :							List[str]      ,  _lowercase       :							str      ,  _lowercase       :							int = 1      ,  _lowercase       :							int = 25      ,  _lowercase       :							Optional[Union[torch.Generator, List[torch.Generator]]] = None      ,  _lowercase       :							Optional[torch.FloatTensor] = None      ,  _lowercase       :							float = 4.0      ,  _lowercase       :							int = 64      ,  _lowercase       :							Optional[str] = "pil"      ,  _lowercase       :							bool = True      ,  )       ->				Any:

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

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

									snake_case      : Tuple							=   batch_size * num_images_per_prompt

									snake_case      : Any							=   guidance_scale > 1.0
									snake_case      : Optional[int]							=   self._encode_prompt(_lowercase      ,  _lowercase      ,  _lowercase      ,  _lowercase		)

									# prior

									self.scheduler.set_timesteps(_lowercase      ,  device=_lowercase		)
									snake_case      : Tuple							=   self.scheduler.timesteps

									snake_case      : int							=   self.prior.config.num_embeddings
									snake_case      : int							=   self.prior.config.embedding_dim

									snake_case      : Any							=   self.prepare_latents(
									    (batch_size, num_embeddings * embedding_dim)      ,  prompt_embeds.dtype      ,  _lowercase      ,  _lowercase      ,  _lowercase      ,  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
									snake_case      : Dict							=   latents.reshape(latents.shape[0]      ,  _lowercase      ,  _lowercase		)

									for i, t in enumerate(self.progress_bar(_lowercase		)		):
															# expand the latents if we are doing classifier free guidance
															snake_case      : Optional[int]							=   torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
															snake_case      : str							=   self.scheduler.scale_model_input(_lowercase      ,  _lowercase		)

															snake_case      : Dict							=   self.prior(
															    _lowercase      ,  timestep=_lowercase      ,  proj_embedding=_lowercase      ,  ).predicted_image_embedding

															# remove the variance
															snake_case						, snake_case      : 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:
																					snake_case						, snake_case      : Dict							=   noise_pred.chunk(2		)
																					snake_case      : Optional[int]							=   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

															snake_case      : Any							=   self.scheduler.step(
															    _lowercase      ,  timestep=_lowercase      ,  sample=_lowercase      ,  ).prev_sample

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

									snake_case      : List[Any]							=   []
									for i, latent in enumerate(_lowercase		):
															snake_case      : str							=   self.renderer.decode(
															    latent[None, :]      ,  _lowercase      ,  size=_lowercase      ,  ray_batch_size=4096      ,  n_coarse_samples=64      ,  n_fine_samples=128      ,  )
															images.append(_lowercase		)

									snake_case      : Union[str, Any]							=   torch.stack(_lowercase		)

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

									snake_case      : Any							=   images.cpu().numpy()

									if output_type == "pil":
															snake_case      : Optional[int]							=   [self.numpy_to_pil(_lowercase		) 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=_lowercase		)








"""simple docstring"""







from sklearn.metrics import accuracy_score

import datasets


A    =	'\nAccuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:\nAccuracy = (TP + TN) / (TP + TN + FP + FN)\n Where:\nTP: True positive\nTN: True negative\nFP: False positive\nFN: False negative\n'


A    =	'\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.\n\nExamples:\n\n    Example 1-A simple example\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])\n        >>> print(results)\n        {\'accuracy\': 0.5}\n\n    Example 2-The same as Example 1, except with `normalize` set to `False`.\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)\n        >>> print(results)\n        {\'accuracy\': 3.0}\n\n    Example 3-The same as Example 1, except with `sample_weight` set.\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])\n        >>> print(results)\n        {\'accuracy\': 0.8778625954198473}\n'


A    =	'\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n'

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,  _KWARGS_DESCRIPTION)
class 			_a     (   datasets.Metric):



			def 							__lowercase				( self       :							List[Any]		)       ->				List[str]:
									return datasets.MetricInfo(
									    description=_DESCRIPTION      ,  citation=_CITATION      ,  inputs_description=_KWARGS_DESCRIPTION      ,  features=datasets.Features(
									        {
									            "predictions": datasets.Sequence(datasets.Value("int32"		)		),
									            "references": datasets.Sequence(datasets.Value("int32"		)		),
									        }
									        if self.config_name == "multilabel"
									        else {
									            "predictions": datasets.Value("int32"		),
									            "references": datasets.Value("int32"		),
									        }		)      ,  reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"]      ,  )



			def 							__lowercase				( self       :							str      ,  _lowercase       :							Optional[int]      ,  _lowercase       :							Tuple      ,  _lowercase       :							Union[str, Any]=True      ,  _lowercase       :							int=None		)       ->				Any:
									return {
									    "accuracy": float(
									        accuracy_score(_lowercase      ,  _lowercase      ,  normalize=_lowercase      ,  sample_weight=_lowercase		)		)
									}



