
"""simple docstring"""







import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


lowerCamelCase__           =	"\\n@misc{chen2021evaluating,\n      title={Evaluating Large Language Models Trained on Code},\n      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n      year={2021},\n      eprint={2107.03374},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG}\n}\n"

lowerCamelCase__           =	"\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper \"Evaluating Large Language Models Trained on Code\"\n(https://arxiv.org/abs/2107.03374).\n"


lowerCamelCase__           =	"\nCalculates how good are predictions given some references, using certain scores\nArgs:\n    predictions: list of candidates to evaluate. Each candidates should be a list\n        of strings with several code candidates to solve the problem.\n    references: a list with a test for each prediction. Each test should evaluate the\n        correctness of a code candidate.\n    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n    num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n    timeout:\nReturns:\n    pass_at_k: dict with pass rates for each k\n    results: dict with granular results of each unittest\nExamples:\n    >>> code_eval = datasets.load_metric(\"code_eval\")\n    >>> test_cases = [\"assert add(2,3)==5\"]\n    >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]\n    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n    >>> print(pass_at_k)\n    {'pass@1': 0.5, 'pass@2': 1.0}\n"


lowerCamelCase__           =	"\n################################################################################\n                                  !!!WARNING!!!\n################################################################################\nThe \"code_eval\" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper \"Evaluating Large\nLanguage Models Trained on Code\" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"\n\n################################################################################\\n"

lowerCamelCase__           =	"The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."




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

		def 							__lowerCamelCase							(   self				):
			return datasets.MetricInfo(
			    # This is the description that will appear on the metrics page.
			    description=_DESCRIPTION ,	citation=_CITATION ,	inputs_description=_KWARGS_DESCRIPTION ,	features=datasets.Features(
			        {
			            'predictions': datasets.Sequence(datasets.Value('string'				)				),
			            'references': datasets.Value('string'				),
			        }				) ,	homepage='https://github.com/openai/human-eval' ,	codebase_urls=['https://github.com/openai/human-eval'] ,	reference_urls=['https://github.com/openai/human-eval'] ,	license=_LICENSE ,	)







		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=[1, 10, 1_00] ,	_SCREAMING_SNAKE_CASE=4 ,	_SCREAMING_SNAKE_CASE=3.0				):

			if os.getenv('HF_ALLOW_CODE_EVAL' ,	0				) != "1":
				raise ValueError(_WARNING				)

			if os.name == "nt":
				raise NotImplementedError('This metric is currently not supported on Windows.'				)

			with ThreadPoolExecutor(max_workers=lowercase_				) as executor:
				__lowerCAmelCase    :		Optional[Any]		    =   []
				__lowerCAmelCase    :		List[str]		    =   Counter()
				__lowerCAmelCase    :		Union[str, Any]		    =   0
				__lowerCAmelCase    :		List[str]		    =   defaultdict(lowercase_				)

				for task_id, (candidates, test_case) in enumerate(zip(lowercase_ ,	lowercase_				)				):
					for candidate in candidates:
						__lowerCAmelCase    :		Any		    =   candidate + """\n""" + test_case
						__lowerCAmelCase    :		Dict		    =   (test_program, timeout, task_id, completion_id[task_id])
						__lowerCAmelCase    :		Union[str, Any]		    =   executor.submit(lowercase_ ,	*lowercase_				)
						futures.append(lowercase_				)
						completion_id[task_id] += 1
						n_samples += 1

				for future in as_completed(lowercase_				):
					__lowerCAmelCase    :		Optional[Any]		    =   future.result()
					results[result["task_id"]].append((result['completion_id'], result)				)

			__lowerCAmelCase    :		int		    =   [], []
			for result in results.values():
				result.sort()
				__lowerCAmelCase    :		str		    =   [r[1]["""passed"""] for r in result]
				total.append(len(lowercase_				)				)
				correct.append(sum(lowercase_				)				)
			__lowerCAmelCase    :		List[str]		    =   np.array(lowercase_				)
			__lowerCAmelCase    :		List[Any]		    =   np.array(lowercase_				)

			__lowerCAmelCase    :		Optional[int]		    =   k
			__lowerCAmelCase    :		List[Any]		    =   {f"pass@{k}": estimate_pass_at_k(lowercase_ ,	lowercase_ ,	lowercase_				).mean() for k in ks if (total >= k).all()}

			return pass_at_k, results



def 					__lowerCAmelCase       (_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase	):

	def estimator(_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase	) -> float:
		if n - c < k:
			return 1.0
		return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 ,						n + 1	)	)

	if isinstance(UpperCAmelCase__ ,						UpperCAmelCase__	):
		__lowerCAmelCase    :		Any		    =   itertools.repeat(UpperCAmelCase__ ,						len(UpperCAmelCase__	)	)
	else:
		assert len(UpperCAmelCase__	) == len(UpperCAmelCase__	)
		__lowerCAmelCase    :		Union[str, Any]		    =   iter(UpperCAmelCase__	)

	return np.array([estimator(int(UpperCAmelCase__	) ,						int(UpperCAmelCase__	) ,						UpperCAmelCase__	) for n, c in zip(UpperCAmelCase__ ,						UpperCAmelCase__	)]	)

"""simple docstring"""







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

lowerCamelCase__           =	"""
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""




@dataclass
class 				A__ (			_lowerCamelCase):
		A_		: Union[PIL.Image.Image, np.ndarray]




class 				A__ (			_lowerCamelCase):

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

			self.register_modules(
			    prior=_SCREAMING_SNAKE_CASE ,	image_encoder=_SCREAMING_SNAKE_CASE ,	image_processor=_SCREAMING_SNAKE_CASE ,	scheduler=_SCREAMING_SNAKE_CASE ,	renderer=_SCREAMING_SNAKE_CASE ,	)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			if latents is None:
				__lowerCAmelCase    :		List[str]		    =   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    :		Any		    =   latents.to(_SCREAMING_SNAKE_CASE				)

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

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE=0				):
			if is_accelerate_available():
				from accelerate import cpu_offload
			else:
				raise ImportError('Please install accelerate via `pip install accelerate`'				)

			__lowerCAmelCase    :		Tuple		    =   torch.device(f"cuda:{gpu_id}"				)

			__lowerCAmelCase    :		Union[str, Any]		    =   [self.image_encoder, self.prior]
			for cpu_offloaded_model in models:
				if cpu_offloaded_model is not None:
					cpu_offload(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				)

		@property
		def 							__lowerCamelCase							(   self				):
			if self.device != torch.device('meta'				) or not hasattr(self.image_encoder ,	'_hf_hook'				):
				return self.device
			for module in self.image_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 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	):
			if isinstance(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				) and isinstance(image[0] ,	torch.Tensor				):
				__lowerCAmelCase    :		str		    =   torch.cat(_SCREAMING_SNAKE_CASE ,	axis=0				) if image[0].ndim == 4 else torch.stack(_SCREAMING_SNAKE_CASE ,	axis=0				)

			if not isinstance(_SCREAMING_SNAKE_CASE ,	torch.Tensor				):
				__lowerCAmelCase    :		Optional[int]		    =   self.image_processor(_SCREAMING_SNAKE_CASE ,	return_tensors='pt'				).pixel_values[0].unsqueeze(0				)

			__lowerCAmelCase    :		Dict		    =   image.to(dtype=self.image_encoder.dtype ,	device=_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		List[str]		    =   self.image_encoder(_SCREAMING_SNAKE_CASE				)['last_hidden_state']
			__lowerCAmelCase    :		Optional[int]		    =   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

			__lowerCAmelCase    :		Tuple		    =   image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,	dim=0				)

			if do_classifier_free_guidance:
				__lowerCAmelCase    :		List[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    :		Any		    =   torch.cat([negative_image_embeds, image_embeds]				)

			return image_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 ,	):

			if isinstance(_SCREAMING_SNAKE_CASE ,	PIL.Image.Image				):
				__lowerCAmelCase    :		Union[str, Any]		    =   1
			elif isinstance(_SCREAMING_SNAKE_CASE ,	torch.Tensor				):
				__lowerCAmelCase    :		Tuple		    =   image.shape[0]
			elif isinstance(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				) and isinstance(image[0] ,	(torch.Tensor, PIL.Image.Image)				):
				__lowerCAmelCase    :		Any		    =   len(_SCREAMING_SNAKE_CASE				)
			else:
				raise ValueError(
				    f"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_SCREAMING_SNAKE_CASE				)}"				)

			__lowerCAmelCase    :		Optional[Any]		    =   self._execution_device

			__lowerCAmelCase    :		Optional[Any]		    =   batch_size * num_images_per_prompt

			__lowerCAmelCase    :		Any		    =   guidance_scale > 1.0
			__lowerCAmelCase    :		List[Any]		    =   self._encode_image(_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    :		List[str]		    =   self.scheduler.timesteps

			__lowerCAmelCase    :		Optional[int]		    =   self.prior.config.num_embeddings
			__lowerCAmelCase    :		List[str]		    =   self.prior.config.embedding_dim

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

				__lowerCAmelCase    :		Tuple		    =   self.prior(
				    _SCREAMING_SNAKE_CASE ,	timestep=_SCREAMING_SNAKE_CASE ,	proj_embedding=_SCREAMING_SNAKE_CASE ,	).predicted_image_embedding

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

				__lowerCAmelCase    :		Dict		    =   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    :		List[Any]		    =   []
			for i, latent in enumerate(_SCREAMING_SNAKE_CASE				):
				print()
				__lowerCAmelCase    :		int		    =   self.renderer.decode(
				    latent[None, :] ,	_SCREAMING_SNAKE_CASE ,	size=_SCREAMING_SNAKE_CASE ,	ray_batch_size=40_96 ,	n_coarse_samples=64 ,	n_fine_samples=1_28 ,	)

				images.append(_SCREAMING_SNAKE_CASE				)

			__lowerCAmelCase    :		List[Any]		    =   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    :		int		    =   images.cpu().numpy()

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