


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


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

lowercase  		=			"""
    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 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							__magic_name__					:     Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]


class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	Optional[int]:







								'''simple docstring'''




								super().__init__()

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




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								if latents is None:
									snake_case__  :						str		=      randn_tensor(lowerCamelCase__	,					generator=lowerCamelCase__	,					device=lowerCamelCase__	,					dtype=lowerCamelCase__)
								else:
									if latents.shape != shape:
										raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""")
									snake_case__  :						Union[str, Any]		=      latents.to(lowerCamelCase__)

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




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	Optional[int]:







								'''simple docstring'''




								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__  :						str		=      [self.text_encoder, self.prior]
								for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
										cpu_offload(lowerCamelCase__	,					lowerCamelCase__)




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	Any:







								'''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.")

								snake_case__  :						Dict		=      torch.device(f"""cuda:{gpu_id}""")

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

								snake_case__  :						int		=      None
								for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									snake_case__,					snake_case__  :						str		=      cpu_offload_with_hook(lowerCamelCase__	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

								if self.safety_checker is not None:
									snake_case__,					snake_case__  :						Union[str, Any]		=      cpu_offload_with_hook(self.safety_checker	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

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




							@property
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								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(lowerCamelCase__	,					"_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	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	Optional[Any]:







								'''simple docstring'''




								len(lowerCamelCase__) if isinstance(lowerCamelCase__	,					lowerCamelCase__) else 1

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

								if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						int		=      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__  :						str		=      self.text_encoder(text_input_ids.to(lowerCamelCase__))
								snake_case__  :						Optional[int]		=      text_encoder_output.text_embeds

								snake_case__  :						str		=      prompt_embeds.repeat_interleave(lowerCamelCase__	,					dim=0)
								# in Shap-E it normalize the prompt_embeds and then later rescale it
								snake_case__  :						Optional[int]		=      prompt_embeds / torch.linalg.norm(lowerCamelCase__	,					dim=-1	,					keepdim=lowerCamelCase__)

								if do_classifier_free_guidance:
									snake_case__  :						List[str]		=      torch.zeros_like(lowerCamelCase__)

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

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

								return prompt_embeds







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







								'''simple docstring'''




								if isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[int]		=      1
								elif isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[Any]		=      len(lowerCamelCase__)
								else:
									raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase__)}""")

								snake_case__  :						Optional[Any]		=      self._execution_device

								snake_case__  :						int		=      batch_size * num_images_per_prompt

								snake_case__  :						int		=      guidance_scale > 1.0
								snake_case__  :						Tuple		=      self._encode_prompt(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)

								# prior

								self.scheduler.set_timesteps(lowerCamelCase__	,					device=lowerCamelCase__)
								snake_case__  :						Dict		=      self.scheduler.timesteps

								snake_case__  :						str		=      self.prior.config.num_embeddings
								snake_case__  :						Optional[Any]		=      self.prior.config.embedding_dim

								snake_case__  :						Union[str, Any]		=      self.prepare_latents(
								    (batch_size, num_embeddings * embedding_dim)	,					prompt_embeds.dtype	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					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__  :						str		=      latents.reshape(latents.shape[0]	,					lowerCamelCase__	,					lowerCamelCase__)

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

									snake_case__  :						Union[str, Any]		=      self.prior(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					proj_embedding=lowerCamelCase__	,					).predicted_image_embedding

									# remove the variance
									snake_case__,					snake_case__  :						List[str]		=      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__  :						int		=      noise_pred.chunk(2)
										snake_case__  :						Union[str, Any]		=      noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

									snake_case__  :						int		=      self.scheduler.step(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					sample=lowerCamelCase__	,					).prev_sample

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

								snake_case__  :						Dict		=      []
								for i, latent in enumerate(lowerCamelCase__):
									snake_case__  :						Any		=      self.renderer.decode(
									    latent[None, :]	,					lowerCamelCase__	,					size=lowerCamelCase__	,					ray_batch_size=4_096	,					n_coarse_samples=64	,					n_fine_samples=128	,					)
									images.append(lowerCamelCase__)

								snake_case__  :						Dict		=      torch.stack(lowerCamelCase__)

								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__  :						Dict		=      [self.numpy_to_pil(lowerCamelCase__) 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=lowerCamelCase__)











'''simple docstring'''





import functools
from contextlib import contextmanager

import bert_score
from packaging import version

import datasets





@contextmanager
def UpperCAmelCase    (       ):
    def filter_log(UpperCAmelCase_						):
        return False if "This IS expected if you are initializing" in record.msg else True

    _a				:							Optional[Any]							       =      datasets.utils.logging.get_logger("""transformers.modeling_utils"""						)
    logger.addFilter(UpperCAmelCase_						)
    try:
        yield
    finally:
        logger.removeFilter(UpperCAmelCase_						)


a		:	Tuple       =      '''\
@inproceedings{bert-score,
  title={BERTScore: Evaluating Text Generation with BERT},
  author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},
  booktitle={International Conference on Learning Representations},
  year={2020},
  url={https://openreview.net/forum?id=SkeHuCVFDr}
}
'''

a		:	List[str]       =      '''\
BERTScore leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference
sentences by cosine similarity.
It has been shown to correlate with human judgment on sentence-level and system-level evaluation.
Moreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language
generation tasks.

See the project\'s README at https://github.com/Tiiiger/bert_score#readme for more information.
'''

a		:	Dict       =      '''
BERTScore Metrics with the hashcode from a source against one or more references.

Args:
    predictions (list of str): Prediction/candidate sentences.
    references (list of str or list of list of str): Reference sentences.
    lang (str): Language of the sentences; required (e.g. \'en\').
    model_type (str): Bert specification, default using the suggested
        model for the target language; has to specify at least one of
        `model_type` or `lang`.
    num_layers (int): The layer of representation to use,
        default using the number of layers tuned on WMT16 correlation data.
    verbose (bool): Turn on intermediate status update.
    idf (bool or dict): Use idf weighting; can also be a precomputed idf_dict.
    device (str): On which the contextual embedding model will be allocated on.
        If this argument is None, the model lives on cuda:0 if cuda is available.
    nthreads (int): Number of threads.
    batch_size (int): Bert score processing batch size,
        at least one of `model_type` or `lang`. `lang` needs to be
        specified when `rescale_with_baseline` is True.
    rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline.
    baseline_path (str): Customized baseline file.
    use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. New in version 0.3.10.

Returns:
    precision: Precision.
    recall: Recall.
    f1: F1 score.
    hashcode: Hashcode of the library.

Examples:

    >>> predictions = ["hello there", "general kenobi"]
    >>> references = ["hello there", "general kenobi"]
    >>> bertscore = datasets.load_metric("bertscore")
    >>> results = bertscore.compute(predictions=predictions, references=references, lang="en")
    >>> print([round(v, 2) for v in results["f1"]])
    [1.0, 1.0]
'''





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



  def     a_							(			self ):







      '''simple docstring'''


      return datasets.MetricInfo(
          description=_DESCRIPTION		,     citation=_CITATION		,     homepage="""https://github.com/Tiiiger/bert_score"""		,     inputs_description=_KWARGS_DESCRIPTION		,     features=datasets.Features(
              {
                  """predictions""": datasets.Value("""string"""		,     id="""sequence""" ),
                  """references""": datasets.Sequence(datasets.Value("""string"""		,     id="""sequence""" )		,     id="""references""" ),
              } )		,     codebase_urls=["""https://github.com/Tiiiger/bert_score"""]		,     reference_urls=[
              """https://github.com/Tiiiger/bert_score""",
              """https://arxiv.org/abs/1904.09675""",
          ]		,     )



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase=None		,     __lowerCAmelCase=None		,     __lowerCAmelCase=None		,     __lowerCAmelCase=False		,     __lowerCAmelCase=False		,     __lowerCAmelCase=None		,     __lowerCAmelCase=64		,     __lowerCAmelCase=4		,     __lowerCAmelCase=False		,     __lowerCAmelCase=False		,     __lowerCAmelCase=None		,     __lowerCAmelCase=False		,     ):







      '''simple docstring'''


      _a				:							Any							       =      bert_score.utils.get_hash
      _a				:							int							       =      bert_score.BERTScorer

      if version.parse(bert_score.__version__ ) >= version.parse("""0.3.10""" ):
          _a				:							Union[str, Any]							       =      functools.partial(__lowerCAmelCase		,     use_fast_tokenizer=__lowerCAmelCase )
          _a				:							Dict							       =      functools.partial(__lowerCAmelCase		,     use_fast_tokenizer=__lowerCAmelCase )
      elif use_fast_tokenizer:
          raise ImportWarning(
              """To use a fast tokenizer, the module `bert-score>=0.3.10` is required, and the current version of `bert-score` doesn't match this condition.\n"""
              """You can install it with `pip install \"bert-score>=0.3.10\"`.""" )

      if model_type is None:
          assert lang is not None, "either lang or model_type should be specified"
          _a				:							List[str]							       =      bert_score.utils.langamodel[lang.lower()]

      if num_layers is None:
          _a				:							Dict							       =      bert_score.utils.modelalayers[model_type]

      _a				:							Union[str, Any]							       =      get_hash(
          model=__lowerCAmelCase		,     num_layers=__lowerCAmelCase		,     idf=__lowerCAmelCase		,     rescale_with_baseline=__lowerCAmelCase		,     use_custom_baseline=baseline_path is not None		,     )

      with filter_logging_context():
          if not hasattr(self		,     """cached_bertscorer""" ) or self.cached_bertscorer.hash != hashcode:
              _a				:							Optional[Any]							       =      scorer(
                  model_type=__lowerCAmelCase		,     num_layers=__lowerCAmelCase		,     batch_size=__lowerCAmelCase		,     nthreads=__lowerCAmelCase		,     all_layers=__lowerCAmelCase		,     idf=__lowerCAmelCase		,     device=__lowerCAmelCase		,     lang=__lowerCAmelCase		,     rescale_with_baseline=__lowerCAmelCase		,     baseline_path=__lowerCAmelCase		,     )

      ((_a)       , (_a)       , (_a))				:							Optional[Any]							       =      self.cached_bertscorer.score(
          cands=__lowerCAmelCase		,     refs=__lowerCAmelCase		,     verbose=__lowerCAmelCase		,     batch_size=__lowerCAmelCase		,     )
      _a				:							Tuple							       =      {
          """precision""": P.tolist(),
          """recall""": R.tolist(),
          """f1""": F.tolist(),
          """hashcode""": hashcode,
      }
      return output_dict



  def     a_							(			self		,     __lowerCAmelCase=None		,     __lowerCAmelCase=None		,     **__lowerCAmelCase ):







      '''simple docstring'''


      if references is not None:
          _a				:							Dict							       =      [[ref] if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else ref for ref in references]
      super().add_batch(predictions=__lowerCAmelCase		,     references=__lowerCAmelCase		,     **__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase=None		,     __lowerCAmelCase=None		,     **__lowerCAmelCase ):







      '''simple docstring'''


      if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ):
          _a				:							Optional[Any]							       =      [reference]
      super().add(prediction=__lowerCAmelCase		,     reference=__lowerCAmelCase		,     **__lowerCAmelCase )


