




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  ):






    """simple docstring"""





    def 				a__ ( self    )					->						Optional[Any]:
         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 				a__ ( self  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE=[1, 10, 100]  ,_SCREAMING_SNAKE_CASE=4  ,_SCREAMING_SNAKE_CASE=3.0    )					->						int:

         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_     :				Union[str, Any]  =     []
              UpperCAmelCase_     :				List[Any]  =     Counter()
              UpperCAmelCase_     :				Any  =     0
              UpperCAmelCase_     :				Union[str, Any]  =     defaultdict(_SCREAMING_SNAKE_CASE    )

              for task_id, (candidates, test_case) in enumerate(zip(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )    ):
                   for candidate in candidates:
                        UpperCAmelCase_     :				Union[str, Any]  =     candidate + '''\n''' + test_case
                        UpperCAmelCase_     :				Any  =     (test_program, timeout, task_id, completion_id[task_id])
                        UpperCAmelCase_     :				List[str]  =     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_     :				Tuple  =     future.result()
                   results[result["task_id"]].append((result['''completion_id'''], result)    )

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

         UpperCAmelCase_     :				Optional[Any]  =     k
         UpperCAmelCase_     :				str  =     {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 lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase ):

     '''simple docstring'''


     def estimator(_lowercase					,		_lowercase					,		_lowercase ) -> 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(_lowercase					,		_lowercase ):
          UpperCAmelCase_     :				Union[str, Any]  =     itertools.repeat(_lowercase					,		len(_lowercase ) )
     else:
          assert len(_lowercase ) == len(_lowercase )
          UpperCAmelCase_     :				Optional[Any]  =     iter(_lowercase )

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



'''simple docstring'''





import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
					import torch


if TYPE_CHECKING:
					from transformers.pipelines.conversational import Conversation


UpperCAmelCase__  			=				logging.get_logger(__name__)
UpperCAmelCase__  			=				{'''vocab_file''': '''spiece.model'''}

UpperCAmelCase__  			=				{
    '''vocab_file''': {
        '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''',
    }
}

UpperCAmelCase__  			=				{
    '''AI-Sweden/gpt-sw3-126m''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-350m''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-1.6b''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-6.7b''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-20b''': 2_0_4_8,
}
class 						a__					(					a_   ):





			'''simple docstring'''

			A						:				int					      =			VOCAB_FILES_NAMES
			A						:				Optional[int]					      =			PRETRAINED_VOCAB_FILES_MAP
			A						:				Tuple					      =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			A						:				int					      =			['''input_ids''', '''attention_mask''']
			def __init__(  self							:			int			,    lowerCAmelCase_							:			List[str]			,    lowerCAmelCase_							:			Union[str, Any]=False			,    lowerCAmelCase_							:			List[str]=False			,    lowerCAmelCase_							:			List[Any]=False			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			List[Any]=None			,    lowerCAmelCase_							:			Optional[Dict[str, Any]] = None			,    **lowerCAmelCase_							:			Optional[Any]			,    )      ->		None:
						__A=	{} if sp_model_kwargs is None else sp_model_kwargs

						__A=	kwargs.get('name_or_path'	)
						if name_or_path is None:
									logger.warning(
									    'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,'
									    ' you are testing the model, this can safely be ignored'	)
									__A=	'None'

						# Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
						__A=	'<|endoftext|>' if eos_token is None else eos_token
						__A=	'<unk>' if unk_token is None else unk_token
						if "gpt-sw3-7b" in name_or_path:
									__A=	unk_token if pad_token is None else pad_token
									__A=	eos_token if bos_token is None else bos_token
						else:
									__A=	'<pad>' if pad_token is None else pad_token
									__A=	'<s>' if bos_token is None else bos_token

						super().__init__(
						    do_lower_case=lowerCAmelCase_			,    remove_space=lowerCAmelCase_			,    keep_accents=lowerCAmelCase_			,    bos_token=lowerCAmelCase_			,    eos_token=lowerCAmelCase_			,    unk_token=lowerCAmelCase_			,    pad_token=lowerCAmelCase_			,    sp_model_kwargs=self.sp_model_kwargs			,    **lowerCAmelCase_			,    )

						__A=	do_lower_case
						__A=	remove_space
						__A=	keep_accents
						__A=	vocab_file

						__A=	spm.SentencePieceProcessor(**self.sp_model_kwargs	)
						self.sp_model.Load(lowerCAmelCase_	)

						# Used for whitespace normalization in input texts
						# fmt : off
						__A=	{' ', ' ', ' ', ' ', ' ', '　', ' ', ' ', ' ', ' ', '￼', ''}
						# fmt : on

						# Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
						__A=	re.compile(
						    F"""[{"".join(map(lowerCAmelCase_			,    list(range(0			,    9	)	) + list(range(11			,    32	)	) + list(range(127			,    160	)	) + [160, 173, 8_203]	)	)}]"""	)
			def __getstate__(  self							:			Optional[int]	)      ->		Tuple:
						__A=	self.__dict__.copy()
						__A=	None
						return state
			def __setstate__(  self							:			int			,    lowerCAmelCase_							:			int	)      ->		Tuple:
						__A=	d

						# for backward compatibility
						if not hasattr(self			,    'sp_model_kwargs'	):
									__A=	{}

						__A=	spm.SentencePieceProcessor(**self.sp_model_kwargs	)
						self.sp_model.Load(self.vocab_file	)
			@property
			# Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
			def 					lowerCAmelCase     (  self							:			Tuple	)      ->		int:
						return len(self.sp_model	)
			def 					lowerCAmelCase     (  self							:			int			,    lowerCAmelCase_							:			str	)      ->		str:
						__A=	self.non_printing_characters_re.sub(''			,    lowerCAmelCase_	)

						# Normalize whitespaces
						__A=	''.join([char if char not in self.whitespaces else ' ' for char in text]	)

						# NFC Unicode normalization
						__A=	unicodedata.normalize('NFC'			,    lowerCAmelCase_	)
						return text
			def 					lowerCAmelCase     (  self							:			Tuple			,    lowerCAmelCase_							:			str			,    **lowerCAmelCase_							:			Optional[Any]	)      ->		List[str]:
						__A=	self.preprocess_text(lowerCAmelCase_	)
						return self.sp_model.encode(lowerCAmelCase_			,    out_type=lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Any			,    lowerCAmelCase_							:			str	)      ->		int:
						return self.sp_model.PieceToId(lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			int	)      ->		str:
						return self.sp_model.IdToPiece(lowerCAmelCase_	)
			@staticmethod
			def 					lowerCAmelCase     (  lowerCAmelCase_							:			str	)      ->		str:
						return out_string
			def 					lowerCAmelCase     (  self							:			Union[str, Any]			,    lowerCAmelCase_							:			List[str]	)      ->		str:
						__A=	[]
						__A=	''
						__A=	False
						for token in tokens:
									# make sure that special tokens are not decoded using sentencepiece model
									if token in self.all_special_tokens:
												# TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
												if not prev_is_special:
															out_string += " "

												out_string += self.sp_model.decode(lowerCAmelCase_	) + token
												__A=	True
												__A=	[]
									else:
												current_sub_tokens.append(lowerCAmelCase_	)
												__A=	False
						out_string += self.sp_model.decode(lowerCAmelCase_	)

						return out_string
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Dict[str, int]:
						__A=	{self.convert_ids_to_tokens(lowerCAmelCase_	): i for i in range(self.vocab_size	)}
						vocab.update(self.added_tokens_encoder	)
						return vocab
			def 					lowerCAmelCase     (  self							:			Dict			,    lowerCAmelCase_							:			str			,    lowerCAmelCase_							:			Optional[str] = None	)      ->		Tuple[str]:
						if not os.path.isdir(lowerCAmelCase_	):
									logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""	)
									return
						__A=	os.path.join(
						    lowerCAmelCase_			,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']	)

						if os.path.abspath(self.vocab_file	) != os.path.abspath(lowerCAmelCase_	) and os.path.isfile(self.vocab_file	):
									copyfile(self.vocab_file			,    lowerCAmelCase_	)
						elif not os.path.isfile(self.vocab_file	):
									with open(lowerCAmelCase_			,    'wb'	) as fi:
												__A=	self.sp_model.serialized_model_proto()
												fi.write(lowerCAmelCase_	)

						return (out_vocab_file,)
			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			Union[str, List[str]]			,    lowerCAmelCase_							:			Union[str, bool] = False	)      ->		Union[List[int], List[List[int]], "torch.Tensor"]:

						if isinstance(lowerCAmelCase_			,    lowerCAmelCase_	):
									__A=	self.preprocess_text(lowerCAmelCase_	)
									__A=	self.sp_model.encode(lowerCAmelCase_	)
						else:
									__A=	[self.preprocess_text(lowerCAmelCase_	) for t in text]
									__A=	self.sp_model.encode(lowerCAmelCase_	)

						if return_tensors is True or return_tensors == "pt":
									__A=	torch.tensor(lowerCAmelCase_	)

						return token_ids
			def 					lowerCAmelCase     (  self							:			Tuple			,    lowerCAmelCase_							:			Union[int, List[int]]	)      ->		str:
						return self.sp_model.decode(lowerCAmelCase_	)

			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			"Conversation"	)      ->		List[int]:
						__A=	[F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
						__A=	(
						    F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(lowerCAmelCase_	) + F"""{self.bos_token}Bot:"""
						)
						return self.encode(text=lowerCAmelCase_	)



