



'''simple docstring'''
from jiwer import compute_measures

import datasets


snake_case_			:     Any  	=  '\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

snake_case_			:     int  	=  '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'

snake_case_			:     Any  	=  '\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> wer = datasets.load_metric("wer")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n'






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





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							return datasets.MetricInfo(
							    description=_DESCRIPTION			,citation=_CITATION			,inputs_description=_KWARGS_DESCRIPTION			,features=datasets.Features(
							        {
							            'predictions': datasets.Value('string'			,id='sequence'			),
							            'references': datasets.Value('string'			,id='sequence'			),
							        }			)			,codebase_urls=['https://github.com/jitsi/jiwer/']			,reference_urls=[
							        'https://en.wikipedia.org/wiki/Word_error_rate',
							    ]			,)





	def      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    Any=None			,lowerCamelCase__ :    Any=None			,lowerCamelCase__ :    List[Any]=False			):







							'''simple docstring'''
							if concatenate_texts:
													return compute_measures(lowerCamelCase__			,lowerCamelCase__			)["wer"]
							else:
													_UpperCamelCase :		Optional[int]			    =       0
													_UpperCamelCase :		Tuple			    =       0
													for prediction, reference in zip(lowerCamelCase__			,lowerCamelCase__			):
																			_UpperCamelCase :		str			    =       compute_measures(lowerCamelCase__			,lowerCamelCase__			)
																			incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
																			total += measures["substitutions"] + measures["deletions"] + measures["hits"]
													return incorrect / total







'''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_							)]							)


