





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


lowercase_          =		"""\
@misc{chen2021evaluating,
      title={Evaluating Large Language Models Trained on Code},
      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
      year={2021},
      eprint={2107.03374},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
"""

lowercase_          =		"""\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper \"Evaluating Large Language Models Trained on Code\"
(https://arxiv.org/abs/2107.03374).
"""


lowercase_          =		"""
Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of candidates to evaluate. Each candidates should be a list
        of strings with several code candidates to solve the problem.
    references: a list with a test for each prediction. Each test should evaluate the
        correctness of a code candidate.
    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
    num_workers: number of workers used to evaluate the canidate programs (Default: 4).
    timeout:
Returns:
    pass_at_k: dict with pass rates for each k
    results: dict with granular results of each unittest
Examples:
    >>> code_eval = datasets.load_metric(\"code_eval\")
    >>> test_cases = [\"assert add(2,3)==5\"]
    >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]
    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
    >>> print(pass_at_k)
    {'pass@1': 0.5, 'pass@2': 1.0}
"""


lowercase_          =		"""
################################################################################
                                  !!!WARNING!!!
################################################################################
The \"code_eval\" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper \"Evaluating Large
Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374).

Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this
with:

>>> import os
>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"

################################################################################\
"""

lowercase_          =		"""The MIT License

Copyright (c) OpenAI (https://openai.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE."""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,     _KWARGS_DESCRIPTION				)
class     SCREAMING_SNAKE_CASE       (datasets.Metric				):


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Tuple	)->       Any:





     """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 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[int]      ,					a      :    List[str]      ,					a      :    Dict      ,					a      :    List[Any]=[1, 10, 100]      ,					a      :    Any=4      ,					a      :    Union[str, Any]=3.0	)->       int:





     """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:
       lowercase__           =  []
       lowercase__           =  Counter()
       lowercase__           =  0
       lowercase__           =  defaultdict(__lowerCAmelCase	)

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

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

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

     lowercase__           =  k
     lowercase__           =  {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       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Tuple:

  def estimator(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		) -> 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		):
    lowercase__           =  itertools.repeat(_SCREAMING_SNAKE_CASE		,						len(_SCREAMING_SNAKE_CASE		)		)
  else:
    assert len(_SCREAMING_SNAKE_CASE		) == len(_SCREAMING_SNAKE_CASE		)
    lowercase__           =  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		)]		)









import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
      import torch

if is_vision_available():
      import PIL


lowercase_          =		logging.get_logger(__name__)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Tuple[int, int]:
  def constraint_to_multiple_of(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE=0		,						_SCREAMING_SNAKE_CASE=None		):
    lowercase__           =  round(val / multiple		) * multiple

    if max_val is not None and x > max_val:
      lowercase__           =  math.floor(val / multiple		) * multiple

    if x < min_val:
      lowercase__           =  math.ceil(val / multiple		) * multiple

    return x

  lowercase__           =  (output_size, output_size) if isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		) else output_size

  lowercase__      ,   lowercase__           =  get_image_size(_SCREAMING_SNAKE_CASE		)
  lowercase__      ,   lowercase__           =  output_size

  # determine new height and width
  lowercase__           =  output_height / input_height
  lowercase__           =  output_width / input_width

  if keep_aspect_ratio:
    # scale as little as possible
    if abs(1 - scale_width		) < abs(1 - scale_height		):
      # fit width
      lowercase__           =  scale_width
    else:
      # fit height
      lowercase__           =  scale_height

  lowercase__           =  constraint_to_multiple_of(scale_height * input_height		,						multiple=_SCREAMING_SNAKE_CASE		)
  lowercase__           =  constraint_to_multiple_of(scale_width * input_width		,						multiple=_SCREAMING_SNAKE_CASE		)

  return (new_height, new_width)


class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):
   _UpperCamelCase   :		Dict			 =	['pixel_values']


   def __init__(   self      :    Any      ,					a      :    bool = True      ,					a      :    Dict[str, int] = None      ,					a      :    PILImageResampling = PILImageResampling.BILINEAR      ,					a      :    bool = False      ,					a      :    int = 1      ,					a      :    bool = True      ,					a      :    Union[int, float] = 1 / 255      ,					a      :    bool = True      ,					a      :    Optional[Union[float, List[float]]] = None      ,					a      :    Optional[Union[float, List[float]]] = None      ,					**a      :    Tuple      ,					)->       None:





     """simple docstring"""







     super().__init__(**a	)
     lowercase__           =  size if size is not None else {'height': 384, 'width': 384}
     lowercase__           =  get_size_dict(a	)
     lowercase__           =  do_resize
     lowercase__           =  size
     lowercase__           =  keep_aspect_ratio
     lowercase__           =  ensure_multiple_of
     lowercase__           =  resample
     lowercase__           =  do_rescale
     lowercase__           =  rescale_factor
     lowercase__           =  do_normalize
     lowercase__           =  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     lowercase__           =  image_std if image_std is not None else IMAGENET_STANDARD_STD


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict      ,					a      :    np.ndarray      ,					a      :    Dict[str, int]      ,					a      :    bool = False      ,					a      :    int = 1      ,					a      :    PILImageResampling = PILImageResampling.BICUBIC      ,					a      :    Optional[Union[str, ChannelDimension]] = None      ,					**a      :    Optional[Any]      ,					)->       np.ndarray:





     """simple docstring"""







     lowercase__           =  get_size_dict(a	)
     if "height" not in size or "width" not in size:
       raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}"""	)
     lowercase__           =  get_resize_output_image_size(
         a      ,					output_size=(size['height'], size['width'])      ,					keep_aspect_ratio=a      ,					multiple=a      ,					)
     return resize(a      ,					size=a      ,					resample=a      ,					data_format=a      ,					**a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[Any]      ,					a      :    np.ndarray      ,					a      :    Union[int, float]      ,					a      :    Optional[Union[str, ChannelDimension]] = None      ,					**a      :    Dict      ,					)->       str:





     """simple docstring"""







     return rescale(a      ,					scale=a      ,					data_format=a      ,					**a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]      ,					a      :    np.ndarray      ,					a      :    Union[float, List[float]]      ,					a      :    Union[float, List[float]]      ,					a      :    Optional[Union[str, ChannelDimension]] = None      ,					**a      :    Optional[int]      ,					)->       np.ndarray:





     """simple docstring"""







     return normalize(a      ,					mean=a      ,					std=a      ,					data_format=a      ,					**a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    int      ,					a      :    ImageInput      ,					a      :    bool = None      ,					a      :    int = None      ,					a      :    bool = None      ,					a      :    int = None      ,					a      :    PILImageResampling = None      ,					a      :    bool = None      ,					a      :    float = None      ,					a      :    bool = None      ,					a      :    Optional[Union[float, List[float]]] = None      ,					a      :    Optional[Union[float, List[float]]] = None      ,					a      :    Optional[Union[str, TensorType]] = None      ,					a      :    ChannelDimension = ChannelDimension.FIRST      ,					**a      :    str      ,					)->       PIL.Image.Image:





     """simple docstring"""







     lowercase__           =  do_resize if do_resize is not None else self.do_resize
     lowercase__           =  size if size is not None else self.size
     lowercase__           =  get_size_dict(a	)
     lowercase__           =  keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
     lowercase__           =  ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
     lowercase__           =  resample if resample is not None else self.resample
     lowercase__           =  do_rescale if do_rescale is not None else self.do_rescale
     lowercase__           =  rescale_factor if rescale_factor is not None else self.rescale_factor
     lowercase__           =  do_normalize if do_normalize is not None else self.do_normalize
     lowercase__           =  image_mean if image_mean is not None else self.image_mean
     lowercase__           =  image_std if image_std is not None else self.image_std

     lowercase__           =  make_list_of_images(a	)

     if not valid_images(a	):
       raise ValueError(
           'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
           'torch.Tensor, tf.Tensor or jax.ndarray.'	)

     if do_resize and size is None or resample is None:
       raise ValueError('Size and resample must be specified if do_resize is True.'	)

     if do_rescale and rescale_factor is None:
       raise ValueError('Rescale factor must be specified if do_rescale is True.'	)

     if do_normalize and (image_mean is None or image_std is None):
       raise ValueError('Image mean and std must be specified if do_normalize is True.'	)

     # All transformations expect numpy arrays.
     lowercase__           =  [to_numpy_array(a	) for image in images]

     if do_resize:
       lowercase__           =  [self.resize(image=a      ,					size=a      ,					resample=a	) for image in images]

     if do_rescale:
       lowercase__           =  [self.rescale(image=a      ,					scale=a	) for image in images]

     if do_normalize:
       lowercase__           =  [self.normalize(image=a      ,					mean=a      ,					std=a	) for image in images]

     lowercase__           =  [to_channel_dimension_format(a      ,					a	) for image in images]

     lowercase__           =  {'pixel_values': images}
     return BatchFeature(data=a      ,					tensor_type=a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict      ,					a      :    str      ,					a      :    List[Tuple] = None	)->       Optional[int]:





     """simple docstring"""







     lowercase__           =  outputs.logits

     # Resize logits and compute semantic segmentation maps
     if target_sizes is not None:
       if len(a	) != len(a	):
         raise ValueError(
             'Make sure that you pass in as many target sizes as the batch dimension of the logits'	)

       if is_torch_tensor(a	):
         lowercase__           =  target_sizes.numpy()

       lowercase__           =  []

       for idx in range(len(a	)	):
         lowercase__           =  torch.nn.functional.interpolate(
             logits[idx].unsqueeze(dim=0	)      ,					size=target_sizes[idx]      ,					mode='bilinear'      ,					align_corners=a	)
         lowercase__           =  resized_logits[0].argmax(dim=0	)
         semantic_segmentation.append(a	)
     else:
       lowercase__           =  logits.argmax(dim=1	)
       lowercase__           =  [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]	)]

     return semantic_segmentation


