



'''simple docstring'''
import comet  # From: unbabel-comet
import torch

import datasets


snake_case_			:     int  	=  datasets.logging.get_logger(__name__)

snake_case_			:     Optional[int]  	=  '\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = "{COMET}: A Neural Framework for {MT} Evaluation",\n   author = "Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon",\n   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n   month = nov,\n   year = "2020",\n   address = "Online",\n   publisher = "Association for Computational Linguistics",\n   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n   pages = "2685--2702",\n}\n'

snake_case_			:     str  	=  '\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

snake_case_			:     Tuple  	=  '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'






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





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							return datasets.MetricInfo(
							    description=_DESCRIPTION			,citation=_CITATION			,homepage='https://unbabel.github.io/COMET/html/index.html'			,inputs_description=_KWARGS_DESCRIPTION			,features=datasets.Features(
							        {
							            'sources': datasets.Value('string'			,id='sequence'			),
							            'predictions': datasets.Value('string'			,id='sequence'			),
							            'references': datasets.Value('string'			,id='sequence'			),
							        }			)			,codebase_urls=['https://github.com/Unbabel/COMET']			,reference_urls=[
							        'https://github.com/Unbabel/COMET',
							        'https://www.aclweb.org/anthology/2020.emnlp-main.213/',
							        'http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6',
							    ]			,)





	def      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    str			):







							'''simple docstring'''
							if self.config_name == "default":
													_UpperCamelCase :		Optional[Any]			    =       comet.load_from_checkpoint(comet.download_model('wmt20-comet-da'			)			)
							else:
													_UpperCamelCase :		Dict			    =       comet.load_from_checkpoint(comet.download_model(self.config_name			)			)





	def      UpperCamelCase_  (			self :    Optional[Any]			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Dict=None			,lowerCamelCase__ :    int=False			):







							'''simple docstring'''
							if gpus is None:
													_UpperCamelCase :		int			    =       1 if torch.cuda.is_available() else 0
							_UpperCamelCase :		int			    =       {'src': sources, 'mt': predictions, 'ref': references}
							_UpperCamelCase :		List[str]			    =       [dict(zip(lowerCamelCase__			,lowerCamelCase__			)			) for t in zip(*data.values()			)]
							_UpperCamelCase :		int			    =       self.scorer.predict(lowerCamelCase__			,gpus=lowerCamelCase__			,progress_bar=lowerCamelCase__			)
							return {"mean_score": mean_score, "scores": scores}







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


snake_case_			:     List[str]  	=  '\\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'

snake_case_			:     Tuple  	=  '\\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'


snake_case_			:     str  	=  '\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'


snake_case_			:     str  	=  '\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'

snake_case_			:     List[Any]  	=  '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 							lowercase__     (							datasets.Metric       ):





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							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 :    str			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    List[Any]=[1, 10, 100]			,lowerCamelCase__ :    int=4			,lowerCamelCase__ :    List[Any]=3.0			):







							'''simple docstring'''

							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:
													_UpperCamelCase :		Optional[int]			    =       []
													_UpperCamelCase :		Optional[int]			    =       Counter()
													_UpperCamelCase :		int			    =       0
													_UpperCamelCase :		Dict			    =       defaultdict(lowerCamelCase__			)

													for task_id, (candidates, test_case) in enumerate(zip(lowerCamelCase__			,lowerCamelCase__			)			):
																			for candidate in candidates:
																									_UpperCamelCase :		int			    =       candidate + '\n' + test_case
																									_UpperCamelCase :		Optional[Any]			    =       (test_program, timeout, task_id, completion_id[task_id])
																									_UpperCamelCase :		Dict			    =       executor.submit(lowerCamelCase__			,*lowerCamelCase__			)
																									futures.append(lowerCamelCase__			)
																									completion_id[task_id] += 1
																									n_samples += 1

													for future in as_completed(lowerCamelCase__			):
																			_UpperCamelCase :		Dict			    =       future.result()
																			results[result["task_id"]].append((result['completion_id'], result)			)

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

							_UpperCamelCase :		Tuple			    =       k
							_UpperCamelCase :		Tuple			    =       {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__   (					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_							):
												_UpperCamelCase :		int			    =       itertools.repeat(UpperCAmelCase_  ,  len(UpperCAmelCase_							)							)
						else:
												assert len(UpperCAmelCase_							) == len(UpperCAmelCase_							)
												_UpperCamelCase :		Optional[Any]			    =       iter(UpperCAmelCase_							)

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


