import sacrebleu as scb
from packaging import version

import datasets


lowerCamelCase__           =				'\\n@inproceedings{post-2018-call,\n    title = "A Call for Clarity in Reporting {BLEU} Scores",\n    author = "Post, Matt",\n    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n    month = oct,\n    year = "2018",\n    address = "Belgium, Brussels",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/W18-6319",\n    pages = "186--191",\n}\n'

lowerCamelCase__           =				'\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich\'s `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n'

lowerCamelCase__           =				'\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `\'exp\'`. Possible values are:\n        - `\'none\'`: no smoothing\n        - `\'floor\'`: increment zero counts\n        - `\'add-k\'`: increment num/denom by k for n>1\n        - `\'exp\'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method=\'floor\'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method=\'add-k\'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `\'zh\'` for Chinese, `\'ja-mecab\'` for Japanese and `\'13a\'` (mteval) otherwise. Possible values are:\n        - `\'none\'`: No tokenization.\n        - `\'zh\'`: Chinese tokenization.\n        - `\'13a\'`: mimics the `mteval-v13a` script from Moses.\n        - `\'intl\'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `\'char\'`: Language-agnostic character-level tokenization.\n        - `\'ja-mecab\'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    \'score\': BLEU score,\n    \'counts\': Counts,\n    \'totals\': Totals,\n    \'precisions\': Precisions,\n    \'bp\': Brevity penalty,\n    \'sys_len\': predictions length,\n    \'ref_len\': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = ["hello there general kenobi", "foo bar foobar"]\n        >>> references = [["hello there general kenobi", "hello there !"], ["foo bar foobar", "foo bar foobar"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = ["hello there general kenobi",\n        ...                 "on our way to ankh morpork"]\n        >>> references = [["hello there general kenobi", "hello there !"],\n        ...                 ["goodbye ankh morpork", "ankh morpork"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        39.8\n'




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




					def 							UpperCamelCase_						( self :					List[Any]						):


							"""simple docstring"""




							if version.parse(scb.__version__						) < version.parse("1.4.12"						):
									raise ImportWarning(
									    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
									    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."						)
							return datasets.MetricInfo(
							    description=_DESCRIPTION      ,citation=_CITATION      ,homepage="https://github.com/mjpost/sacreBLEU"      ,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/mjpost/sacreBLEU"]      ,reference_urls=[
							        "https://github.com/mjpost/sacreBLEU",
							        "https://en.wikipedia.org/wiki/BLEU",
							        "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
							    ]      ,)







					def 							UpperCamelCase_						( self :					Any      ,_lowerCAmelCase :					List[str]      ,_lowerCAmelCase :					Tuple      ,_lowerCAmelCase :					List[Any]="exp"      ,_lowerCAmelCase :					List[Any]=None      ,_lowerCAmelCase :					Any=False      ,_lowerCAmelCase :					Union[str, Any]=False      ,_lowerCAmelCase :					List[Any]=None      ,_lowerCAmelCase :					Tuple=False      ,):


							"""simple docstring"""




							__snake_case		       =     len(references[0]						)
							if any(len(_lowerCAmelCase						) != references_per_prediction for refs in references						):
									raise ValueError("Sacrebleu requires the same number of references for each prediction"						)
							__snake_case		       =     [[refs[i] for refs in references] for i in range(_lowerCAmelCase						)]
							__snake_case		       =     scb.corpus_bleu(
							    _lowerCAmelCase      ,_lowerCAmelCase      ,smooth_method=_lowerCAmelCase      ,smooth_value=_lowerCAmelCase      ,force=_lowerCAmelCase      ,lowercase=_lowerCAmelCase      ,use_effective_order=_lowerCAmelCase      ,**({"tokenize": tokenize} if tokenize else {})      ,)
							__snake_case		       =     {
							    "score": output.score,
							    "counts": output.counts,
							    "totals": output.totals,
							    "precisions": output.precisions,
							    "bp": output.bp,
							    "sys_len": output.sys_len,
							    "ref_len": output.ref_len,
							}
							return output_dict






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


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

lowerCamelCase__           =				'\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 					UpperCamelCase	(     snake_case__      ):
					__UpperCamelCase						=   42




class 					UpperCamelCase	(     snake_case__      ):




					def __init__( self :					int      ,_lowerCAmelCase :					PriorTransformer      ,_lowerCAmelCase :					CLIPTextModelWithProjection      ,_lowerCAmelCase :					CLIPTokenizer      ,_lowerCAmelCase :					HeunDiscreteScheduler      ,_lowerCAmelCase :					ShapERenderer      ,):


							"""simple docstring"""




							super().__init__()

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




					def 							UpperCamelCase_						( self :					Union[str, Any]      ,_lowerCAmelCase :					List[Any]      ,_lowerCAmelCase :					List[str]      ,_lowerCAmelCase :					List[str]      ,_lowerCAmelCase :					Tuple      ,_lowerCAmelCase :					Union[str, Any]      ,_lowerCAmelCase :					Optional[int]						):


							"""simple docstring"""




							if latents is None:
									__snake_case		       =     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		       =     latents.to(_lowerCAmelCase						)

							__snake_case		       =     latents * scheduler.init_noise_sigma
							return latents




					def 							UpperCamelCase_						( self :					str      ,_lowerCAmelCase :					Optional[Any]=0						):


							"""simple docstring"""




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

							__snake_case		       =     torch.device(F"""cuda:{gpu_id}"""						)

							__snake_case		       =     [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 :					Optional[int]      ,_lowerCAmelCase :					List[str]=0						):


							"""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		       =     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		       =     None
							for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									__snake_case       ,       __snake_case		       =     cpu_offload_with_hook(_lowerCAmelCase      ,_lowerCAmelCase      ,prev_module_hook=_lowerCAmelCase						)

							if self.safety_checker is not None:
									__snake_case       ,       __snake_case		       =     cpu_offload_with_hook(self.safety_checker      ,_lowerCAmelCase      ,prev_module_hook=_lowerCAmelCase						)

							# We'll offload the last model manually.
							__snake_case		       =     hook




					@property
					def 							UpperCamelCase_						( self :					Optional[int]						):


							"""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 :					Optional[Any]      ,_lowerCAmelCase :					Dict      ,_lowerCAmelCase :					int      ,_lowerCAmelCase :					int      ,_lowerCAmelCase :					List[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		       =     0
							# get prompt text embeddings
							__snake_case		       =     self.tokenizer(
							    _lowerCAmelCase      ,padding="max_length"      ,max_length=self.tokenizer.model_max_length      ,truncation=_lowerCAmelCase      ,return_tensors="pt"      ,)
							__snake_case		       =     text_inputs.input_ids
							__snake_case		       =     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		       =     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		       =     self.text_encoder(text_input_ids.to(_lowerCAmelCase						)						)
							__snake_case		       =     text_encoder_output.text_embeds

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

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

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

							return prompt_embeds







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


							"""simple docstring"""




							if isinstance(_lowerCAmelCase      ,_lowerCAmelCase						):
									__snake_case		       =     1
							elif isinstance(_lowerCAmelCase      ,_lowerCAmelCase						):
									__snake_case		       =     len(_lowerCAmelCase						)
							else:
									raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(_lowerCAmelCase						)}"""						)

							__snake_case		       =     self._execution_device

							__snake_case		       =     batch_size * num_images_per_prompt

							__snake_case		       =     guidance_scale > 1.0
							__snake_case		       =     self._encode_prompt(_lowerCAmelCase      ,_lowerCAmelCase      ,_lowerCAmelCase      ,_lowerCAmelCase						)

							# prior

							self.scheduler.set_timesteps(_lowerCAmelCase      ,device=_lowerCAmelCase						)
							__snake_case		       =     self.scheduler.timesteps

							__snake_case		       =     self.prior.config.num_embeddings
							__snake_case		       =     self.prior.config.embedding_dim

							__snake_case		       =     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		       =     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		       =     torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
									__snake_case		       =     self.scheduler.scale_model_input(_lowerCAmelCase      ,_lowerCAmelCase						)

									__snake_case		       =     self.prior(
									    _lowerCAmelCase      ,timestep=_lowerCAmelCase      ,proj_embedding=_lowerCAmelCase      ,).predicted_image_embedding

									# remove the variance
									__snake_case       ,       __snake_case		       =     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		       =     noise_pred.chunk(2						)
											__snake_case		       =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

									__snake_case		       =     self.scheduler.step(
									    _lowerCAmelCase      ,timestep=_lowerCAmelCase      ,sample=_lowerCAmelCase      ,).prev_sample

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

							__snake_case		       =     []
							for i, latent in enumerate(_lowerCAmelCase						):
									__snake_case		       =     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		       =     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		       =     images.cpu().numpy()

							if output_type == "pil":
									__snake_case		       =     [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						)





