





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


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

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


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


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

_SCREAMING_SNAKE_CASE	 =							"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    lowerCAmelCase_		(		datasets.Metric		):




 def 							_snake_case   (	self		)    ->							List[str]:
     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 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase=[1, 10, 100]			,     _lowerCAmelCase=4			,     _lowerCAmelCase=3.0		)    ->							str:

     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=_lowerCAmelCase		) as executor:
         _lowerCAmelCase				=      []
         _lowerCAmelCase				=      Counter()
         _lowerCAmelCase				=      0
         _lowerCAmelCase				=      defaultdict(_lowerCAmelCase		)

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

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

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

     _lowerCAmelCase				=      k
     _lowerCAmelCase				=      {f'''pass@{k}''': estimate_pass_at_k(_lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase		).mean() for k in ks if (total >= k).all()}

     return pass_at_k, results







def 	__a(SCREAMING_SNAKE_CASE_  :					Tuple		,       SCREAMING_SNAKE_CASE_  :					str		,       SCREAMING_SNAKE_CASE_  :					Union[str, Any]    ):



    '''simple docstring'''





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

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









'''simple docstring'''


import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_SCREAMING_SNAKE_CASE	 =							logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE	 =							"▁"

_SCREAMING_SNAKE_CASE	 =							{"vocab_file": "sentencepiece.bpe.model"}

_SCREAMING_SNAKE_CASE	 =							{
    "vocab_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
    }
}

_SCREAMING_SNAKE_CASE	 =							{
    "facebook/xglm-564M": 20_48,
}

class    lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase						:							int         =					VOCAB_FILES_NAMES
 __lowerCamelCase						:							Optional[int]         =					PRETRAINED_VOCAB_FILES_MAP
 __lowerCamelCase						:							Tuple         =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCamelCase						:							str         =					["input_ids", "attention_mask"]




 def __init__(	self			,     _lowerCAmelCase			,     _lowerCAmelCase="<s>"			,     _lowerCAmelCase="</s>"			,     _lowerCAmelCase="</s>"			,     _lowerCAmelCase="<s>"			,     _lowerCAmelCase="<unk>"			,     _lowerCAmelCase="<pad>"			,     _lowerCAmelCase = None			,     **_lowerCAmelCase			,     )    ->							None:
     _lowerCAmelCase				=      {} if sp_model_kwargs is None else sp_model_kwargs

     # Compatibility with the original tokenizer
     _lowerCAmelCase				=      7
     _lowerCAmelCase				=      [f'''<madeupword{i}>''' for i in range(self.num_madeup_words		)]

     _lowerCAmelCase				=      kwargs.get("additional_special_tokens"			,     []		)
     kwargs["additional_special_tokens"] += [
         word for word in madeup_words if word not in kwargs["additional_special_tokens"]
     ]

     super().__init__(
         bos_token=_lowerCAmelCase			,     eos_token=_lowerCAmelCase			,     unk_token=_lowerCAmelCase			,     sep_token=_lowerCAmelCase			,     cls_token=_lowerCAmelCase			,     pad_token=_lowerCAmelCase			,     sp_model_kwargs=self.sp_model_kwargs			,     **_lowerCAmelCase			,     )

     _lowerCAmelCase				=      spm.SentencePieceProcessor(**self.sp_model_kwargs		)
     self.sp_model.Load(str(_lowerCAmelCase		)		)
     _lowerCAmelCase				=      vocab_file

     # Original fairseq vocab and spm vocab must be "aligned":
     # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
     # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
     # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
     # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

     # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
     _lowerCAmelCase				=      1

     # Mimic fairseq token-to-id alignment for the first 4 token
     _lowerCAmelCase				=      {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}

     _lowerCAmelCase				=      len(self.sp_model		)
     _lowerCAmelCase				=      {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words		)}
     self.fairseq_tokens_to_ids.update(_lowerCAmelCase		)

     _lowerCAmelCase				=      {v: k for k, v in self.fairseq_tokens_to_ids.items()}




 def __getstate__(	self		)    ->							List[str]:
     _lowerCAmelCase				=      self.__dict__.copy()
     _lowerCAmelCase				=      None
     _lowerCAmelCase				=      self.sp_model.serialized_model_proto()
     return state




 def __setstate__(	self			,     _lowerCAmelCase		)    ->							Optional[int]:
     _lowerCAmelCase				=      d

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

     _lowerCAmelCase				=      spm.SentencePieceProcessor(**self.sp_model_kwargs		)
     self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase = None		)    ->							List[int]:

     if token_ids_a is None:
         return [self.sep_token_id] + token_ids_a
     _lowerCAmelCase				=      [self.sep_token_id]
     return sep + token_ids_a + sep + sep + token_ids_a




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase = None			,     _lowerCAmelCase = False		)    ->							List[int]:

     if already_has_special_tokens:
         return super().get_special_tokens_mask(
             token_ids_a=_lowerCAmelCase			,     token_ids_a=_lowerCAmelCase			,     already_has_special_tokens=_lowerCAmelCase		)

     if token_ids_a is None:
         return [1] + ([0] * len(_lowerCAmelCase		))
     return [1] + ([0] * len(_lowerCAmelCase		)) + [1, 1] + ([0] * len(_lowerCAmelCase		))




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase = None		)    ->							List[int]:
     _lowerCAmelCase				=      [self.sep_token_id]

     if token_ids_a is None:
         return len(sep + token_ids_a		) * [0]
     return len(sep + token_ids_a + sep + sep + token_ids_a		) * [0]




 @property
 def 							_snake_case   (	self		)    ->							str:
     return len(self.sp_model		) + self.fairseq_offset + self.num_madeup_words




 def 							_snake_case   (	self		)    ->							Any:
     _lowerCAmelCase				=      {self.convert_ids_to_tokens(_lowerCAmelCase		): i for i in range(self.vocab_size		)}
     vocab.update(self.added_tokens_encoder		)
     return vocab




 def 							_snake_case   (	self			,     _lowerCAmelCase		)    ->							List[str]:
     return self.sp_model.encode(_lowerCAmelCase			,     out_type=_lowerCAmelCase		)




 def 							_snake_case   (	self			,     _lowerCAmelCase		)    ->							List[str]:
     if token in self.fairseq_tokens_to_ids:
         return self.fairseq_tokens_to_ids[token]
     _lowerCAmelCase				=      self.sp_model.PieceToId(_lowerCAmelCase		)

     # Need to return unknown token if the SP model returned 0
     return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




 def 							_snake_case   (	self			,     _lowerCAmelCase		)    ->							List[Any]:
     if index in self.fairseq_ids_to_tokens:
         return self.fairseq_ids_to_tokens[index]
     return self.sp_model.IdToPiece(index - self.fairseq_offset		)




 def 							_snake_case   (	self			,     _lowerCAmelCase		)    ->							Union[str, Any]:
     _lowerCAmelCase				=      "".join(_lowerCAmelCase		).replace(_lowerCAmelCase			,     " "		).strip()
     return out_string





 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase = None		)    ->							Tuple[str]:
     if not os.path.isdir(_lowerCAmelCase		):
         logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''		)
         return
     _lowerCAmelCase				=      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:
             _lowerCAmelCase				=      self.sp_model.serialized_model_proto()
             fi.write(_lowerCAmelCase		)

     return (out_vocab_file,)


