




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


a													=			"\\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"

a													=			"\\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"


a													=			"\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"


a													=			"\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"

a													=			"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 				UpperCAmelCase (    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 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=[1, 10, 100]						,		_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=_SCREAMING_SNAKE_CASE			) as executor:
														_UpperCAmelCase      =			[]
														_UpperCAmelCase      =			Counter()
														_UpperCAmelCase      =			0
														_UpperCAmelCase      =			defaultdict(_SCREAMING_SNAKE_CASE			)

														for task_id, (candidates, test_case) in enumerate(zip(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)			):
																				for candidate in candidates:
																										_UpperCAmelCase      =			candidate + """\n""" + test_case
																										_UpperCAmelCase      =			(test_program, timeout, task_id, completion_id[task_id])
																										_UpperCAmelCase      =			executor.submit(_SCREAMING_SNAKE_CASE						,		*_SCREAMING_SNAKE_CASE			)
																										futures.append(_SCREAMING_SNAKE_CASE			)
																										completion_id[task_id] += 1
																										n_samples += 1

														for future in as_completed(_SCREAMING_SNAKE_CASE			):
																				_UpperCAmelCase      =			future.result()
																				results[result["task_id"]].append((result["""completion_id"""], result)			)

								_UpperCAmelCase    ,					_UpperCAmelCase      =			[], []
								for result in results.values():
														result.sort()
														_UpperCAmelCase      =			[r[1]["""passed"""] for r in result]
														total.append(len(_SCREAMING_SNAKE_CASE			)			)
														correct.append(sum(_SCREAMING_SNAKE_CASE			)			)
								_UpperCAmelCase      =			np.array(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			np.array(_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			k
								_UpperCAmelCase      =			{F"pass@{k}": estimate_pass_at_k(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			).mean() for k in ks if (total >= k).all()}

								return pass_at_k, results




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case       )						->				Any:

						def estimator(snake_case			,     snake_case			,     snake_case       ) -> 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(snake_case			,     snake_case       ):
												_UpperCAmelCase      =			itertools.repeat(snake_case			,     len(snake_case       )       )
						else:
												assert len(snake_case       ) == len(snake_case       )
												_UpperCAmelCase      =			iter(snake_case       )

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





import os
import string
import sys


a													=			1 << 8

a													=			{
    "tab": ord("\t"),
    "newline": ord("\r"),
    "esc": 27,
    "up": 65 + ARROW_KEY_FLAG,
    "down": 66 + ARROW_KEY_FLAG,
    "right": 67 + ARROW_KEY_FLAG,
    "left": 68 + ARROW_KEY_FLAG,
    "mod_int": 91,
    "undefined": sys.maxsize,
    "interrupt": 3,
    "insert": 50,
    "delete": 51,
    "pg_up": 53,
    "pg_down": 54,
}

a													=			KEYMAP["up"]
a													=			KEYMAP["left"]

if sys.platform == "win32":
				a													=			[]
				a													=			{
				    b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG,
				    b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG,
				    b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG,
				    b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG,
				    b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG,
				    b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG,
				    b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG,
				    b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG,
				}

for i in range(10):
				a													=			ord(str(i))




def        _SCREAMING_SNAKE_CASE      (		)						->				Optional[int]:
						if os.name == "nt":
												import msvcrt

												_UpperCAmelCase      =			"""mbcs"""
												# Flush the keyboard buffer
												while msvcrt.kbhit():
																		msvcrt.getch()
												if len(snake_case       ) == 0:
																		# Read the keystroke
																		_UpperCAmelCase      =			msvcrt.getch()

																		# If it is a prefix char, get second part
																		if ch in (b"\x00", b"\xe0"):
																								_UpperCAmelCase      =			ch + msvcrt.getch()
																								# Translate actual Win chars to bullet char types
																								try:
																														_UpperCAmelCase      =			chr(WIN_KEYMAP[cha]       )
																														WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""]       )       )
																														WIN_CH_BUFFER.append(snake_case       )
																														if ord(snake_case       ) in (
																														    KEYMAP["insert"] - 1 << 9,
																														    KEYMAP["delete"] - 1 << 9,
																														    KEYMAP["pg_up"] - 1 << 9,
																														    KEYMAP["pg_down"] - 1 << 9,
																														):
																																				WIN_CH_BUFFER.append(chr(1_2_6       )       )
																														_UpperCAmelCase      =			chr(KEYMAP["""esc"""]       )
																								except KeyError:
																														_UpperCAmelCase      =			cha[1]
																		else:
																								_UpperCAmelCase      =			ch.decode(snake_case       )
												else:
																		_UpperCAmelCase      =			WIN_CH_BUFFER.pop(0       )
						elif os.name == "posix":
												import termios
												import tty

												_UpperCAmelCase      =			sys.stdin.fileno()
												_UpperCAmelCase      =			termios.tcgetattr(snake_case       )
												try:
																		tty.setraw(snake_case       )
																		_UpperCAmelCase      =			sys.stdin.read(1       )
												finally:
																		termios.tcsetattr(snake_case			,     termios.TCSADRAIN			,     snake_case       )
						return ch




def        _SCREAMING_SNAKE_CASE      (		)						->				Dict:
						_UpperCAmelCase      =			get_raw_chars()
						if ord(snake_case       ) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
												return char

						elif ord(snake_case       ) == KEYMAP["esc"]:
												_UpperCAmelCase      =			get_raw_chars()
												if ord(snake_case       ) == KEYMAP["mod_int"]:
																		_UpperCAmelCase      =			get_raw_chars()
																		if ord(snake_case       ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(snake_case       ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
																								return chr(ord(snake_case       ) + ARROW_KEY_FLAG       )
																		else:
																								return KEYMAP["undefined"]
												else:
																		return get_raw_chars()

						else:
												if char in string.printable:
																		return char
												else:
																		return KEYMAP["undefined"]