



'''simple docstring'''
from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('3.8'):
					import importlib_metadata
else:
					import importlib.metadata as importlib_metadata


snake_case_			:     Optional[Any]  	=  ''


if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):






					class 							lowercase__     (							tr.AbstractTransform       ):





						def __init__(			self :    List[Any]			,lowerCamelCase__ :    str = " "			):







												'''simple docstring'''
												_UpperCamelCase :		Tuple			    =       sentence_delimiter





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







												'''simple docstring'''
												return list(lowerCamelCase__			)





						def      UpperCamelCase_  (			self :    Optional[Any]			,lowerCamelCase__ :    List[str]			):







												'''simple docstring'''
												_UpperCamelCase :		List[Any]			    =       []
												for sent_idx, sentence in enumerate(lowerCamelCase__			):
																		chars.extend(self.process_string(lowerCamelCase__			)			)
																		if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowerCamelCase__			) - 1:
																								chars.append(self.sentence_delimiter			)
												return chars
					snake_case_			:     str  	=  tr.Compose(
					    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
					)
else:
					snake_case_			:     Union[str, Any]  	=  tr.Compose(
					    [
					        tr.RemoveMultipleSpaces(),
					        tr.Strip(),
					        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
					        tr.ReduceToListOfListOfChars(),
					    ]
					)


snake_case_			:     Union[str, 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_			:     Tuple  	=  '\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (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 characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'

snake_case_			:     Any  	=  '\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character 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    >>> cer = datasets.load_metric("cer")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n'






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





	def      UpperCamelCase_  (			self :    Any			):







							'''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',
							        'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates',
							    ]			,)





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







							'''simple docstring'''
							if concatenate_texts:
													return jiwer.compute_measures(
													    lowerCamelCase__			,lowerCamelCase__			,truth_transform=lowerCamelCase__			,hypothesis_transform=lowerCamelCase__			,)["wer"]

							_UpperCamelCase :		Dict			    =       0
							_UpperCamelCase :		List[str]			    =       0
							for prediction, reference in zip(lowerCamelCase__			,lowerCamelCase__			):
													_UpperCamelCase :		str			    =       jiwer.compute_measures(
													    lowerCamelCase__			,lowerCamelCase__			,truth_transform=lowerCamelCase__			,hypothesis_transform=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_							)]							)


