




"""simple docstring"""


from typing import Dict, List, Optional, Union

import numpy as np

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


if is_vision_available():
     import PIL


A_         =							logging.get_logger(__name__)






class    lowercase(	__a					):







 '''simple docstring'''





 lowercase__					   =   ["pixel_values"]


 def __init__(							self:						List[str], a_:						bool = True, a_:						Dict[str, int] = None, a_:						PILImageResampling = PIL.Image.BICUBIC, a_:						bool = True, a_:						Dict[str, int] = None, a_:						Union[int, float] = 1 / 255, a_:						bool = True, a_:						bool = True, a_:						Optional[Union[float, List[float]]] = None, a_:						Optional[Union[float, List[float]]] = None, **a_:						List[str], ):




   '''simple docstring'''



   super().__init__(**lowercase_						)
   _snake_case				:						Tuple								=    size if size is not None else {"""height""": 256, """width""": 256}
   _snake_case				:						Union[str, Any]								=    get_size_dict(lowercase_						)
   _snake_case				:						Union[str, Any]								=    crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
   _snake_case				:						Optional[Any]								=    get_size_dict(lowercase_, param_name="""crop_size"""						)

   _snake_case				:						List[str]								=    do_resize
   _snake_case				:						List[Any]								=    size
   _snake_case				:						Optional[Any]								=    resample
   _snake_case				:						Any								=    do_center_crop
   _snake_case				:						str								=    crop_size
   _snake_case				:						Any								=    do_rescale
   _snake_case				:						str								=    rescale_factor
   _snake_case				:						Any								=    do_normalize
   _snake_case				:						Any								=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
   _snake_case				:						List[Any]								=    image_std if image_std is not None else IMAGENET_STANDARD_STD


 def 					UpperCamelCase_  (							self:						List[str], a_:						np.ndarray, a_:						Dict[str, int], a_:						PILImageResampling = PIL.Image.BICUBIC, a_:						Optional[Union[str, ChannelDimension]] = None, **a_:						Tuple, ):




   '''simple docstring'''



   _snake_case				:						Dict								=    get_size_dict(lowercase_						)
   if "height" not in size or "width" not in size:
     raise ValueError(f"The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}"						)
   return resize(
       lowercase_, size=(size["""height"""], size["""width"""]), resample=lowercase_, data_format=lowercase_, **lowercase_						)


 def 					UpperCamelCase_  (							self:						Union[str, Any], a_:						np.ndarray, a_:						Dict[str, int], a_:						Optional[Union[str, ChannelDimension]] = None, **a_:						int, ):




   '''simple docstring'''



   _snake_case				:						Optional[int]								=    get_size_dict(lowercase_						)
   if "height" not in size or "width" not in size:
     raise ValueError(f"The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}"						)
   return center_crop(lowercase_, size=(size["""height"""], size["""width"""]), data_format=lowercase_, **lowercase_						)


 def 					UpperCamelCase_  (							self:						int, a_:						np.ndarray, a_:						Union[int, float], a_:						Optional[Union[str, ChannelDimension]] = None, **a_:						str, ):




   '''simple docstring'''



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


 def 					UpperCamelCase_  (							self:						Optional[int], a_:						np.ndarray, a_:						Union[float, List[float]], a_:						Union[float, List[float]], a_:						Optional[Union[str, ChannelDimension]] = None, **a_:						Union[str, Any], ):




   '''simple docstring'''



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


 def 					UpperCamelCase_  (							self:						str, a_:						ImageInput, a_:						bool = None, a_:						Dict[str, int] = None, a_:						Any=None, a_:						bool = None, a_:						Dict[str, int] = 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_:						Optional[Any], ):




   '''simple docstring'''



   _snake_case				:						List[Any]								=    do_resize if do_resize is not None else self.do_resize
   _snake_case				:						Dict								=    resample if resample is not None else self.resample
   _snake_case				:						List[str]								=    do_center_crop if do_center_crop is not None else self.do_center_crop
   _snake_case				:						List[Any]								=    do_rescale if do_rescale is not None else self.do_rescale
   _snake_case				:						Optional[int]								=    rescale_factor if rescale_factor is not None else self.rescale_factor
   _snake_case				:						Union[str, Any]								=    do_normalize if do_normalize is not None else self.do_normalize
   _snake_case				:						Optional[int]								=    image_mean if image_mean is not None else self.image_mean
   _snake_case				:						Optional[Any]								=    image_std if image_std is not None else self.image_std

   _snake_case				:						List[str]								=    size if size is not None else self.size
   _snake_case				:						List[str]								=    get_size_dict(lowercase_						)
   _snake_case				:						Optional[Any]								=    crop_size if crop_size is not None else self.crop_size
   _snake_case				:						Dict								=    get_size_dict(lowercase_, param_name="""crop_size"""						)

   _snake_case				:						str								=    make_list_of_images(lowercase_						)

   if not valid_images(lowercase_						):
     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_center_crop and crop_size is None:
     raise ValueError("""Crop size must be specified if do_center_crop 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.
   _snake_case				:						Optional[Any]								=    [to_numpy_array(lowercase_						) for image in images]

   if do_resize:
     _snake_case				:						Tuple								=    [self.resize(image=lowercase_, size=lowercase_, resample=lowercase_						) for image in images]

   if do_center_crop:
     _snake_case				:						int								=    [self.center_crop(image=lowercase_, size=lowercase_						) for image in images]

   if do_rescale:
     _snake_case				:						Dict								=    [self.rescale(image=lowercase_, scale=lowercase_						) for image in images]

   if do_normalize:
     _snake_case				:						Union[str, Any]								=    [self.normalize(image=lowercase_, mean=lowercase_, std=lowercase_						) for image in images]

   _snake_case				:						List[str]								=    [to_channel_dimension_format(lowercase_, lowercase_						) for image in images]

   _snake_case				:						Any								=    {"""pixel_values""": images}
   return BatchFeature(data=lowercase_, tensor_type=lowercase_						)



# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__    ,     a__ )      ->str:




  '''simple docstring'''

  _UpperCamelCase           =    multiprocessing.Manager()
  _UpperCamelCase           =    manager.list()

  _UpperCamelCase           =    multiprocessing.Process(target=a__    ,     args=(check_program, result, timeout) )
  p.start()
  p.join(timeout=timeout + 1 )
  if p.is_alive():
    p.kill()

  if not result:
    result.append("timed out" )

  return {
      "task_id": task_id,
      "passed": result[0] == "passed",
      "result": result[0],
      "completion_id": completion_id,
  }


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__ )      ->Union[str, Any]:




  '''simple docstring'''

  with create_tempdir():
    # These system calls are needed when cleaning up tempdir.
    import os
    import shutil

    _UpperCamelCase           =    shutil.rmtree
    _UpperCamelCase           =    os.rmdir
    _UpperCamelCase           =    os.chdir

    # Disable functionalities that can make destructive changes to the test.
    reliability_guard()

    # Run program.
    try:
      _UpperCamelCase           =    {}
      with swallow_io():
        with time_limit(a__ ):
          exec(a__    ,     a__ )
      result.append("passed" )
    except TimeoutException:
      result.append("timed out" )
    except BaseException as e:
      result.append(f'failed: {e}' )

    # Needed for cleaning up.
    _UpperCamelCase           =    rmtree
    _UpperCamelCase           =    rmdir
    _UpperCamelCase           =    chdir


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->Optional[Any]:




  '''simple docstring'''

  def signal_handler(a__    ,     a__ ):
    raise TimeoutException("Timed out!" )

  signal.setitimer(signal.ITIMER_REAL    ,     a__ )
  signal.signal(signal.SIGALRM    ,     a__ )
  try:
    yield
  finally:
    signal.setitimer(signal.ITIMER_REAL    ,     0 )


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  _UpperCamelCase           =    WriteOnlyStringIO()
  with contextlib.redirect_stdout(a__ ):
    with contextlib.redirect_stderr(a__ ):
      with redirect_stdin(a__ ):
        yield


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  with tempfile.TemporaryDirectory() as dirname:
    with chdir(a__ ):
      yield dirname




class 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 pass




class 					_UpperCAmelCase			(     io.StringIO  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[str]							, *lowercase_				:   str							, **lowercase_				:   List[str])						->	Optional[Any]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   Any							, *lowercase_				:   List[Any]							, **lowercase_				:   Optional[int])						->	Optional[int]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   int							, *lowercase_				:   int							, **lowercase_				:   str)						->	int:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   List[Any]							, *lowercase_				:   Tuple							, **lowercase_				:   Tuple)						->	Tuple:


   """simple docstring"""







   return False




class 					_UpperCAmelCase			(     contextlib._RedirectStream  ):  # type: ignore



 '''simple docstring'''




 __A			       =					'''stdin'''


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->str:




  '''simple docstring'''

  if root == ".":
    yield
    return
  _UpperCamelCase           =    os.getcwd()
  os.chdir(a__ )
  try:
    yield
  except BaseException as exc:
    raise exc
  finally:
    os.chdir(a__ )







def 				lowerCAmelCase__       (			a__=None )      ->Optional[int]:




  '''simple docstring'''

  if maximum_memory_bytes is not None:
    import resource

    resource.setrlimit(resource.RLIMIT_AS    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    resource.setrlimit(resource.RLIMIT_DATA    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    if not platform.uname().system == "Darwin":
      resource.setrlimit(resource.RLIMIT_STACK    ,     (maximum_memory_bytes, maximum_memory_bytes) )

  faulthandler.disable()

  import builtins

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import os

  _UpperCamelCase           =    "1"

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import shutil

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import subprocess

  _UpperCamelCase           =    None  # type: ignore

  _UpperCamelCase           =    None

  import sys

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None




