# 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_  (		lowercase:				str	,       lowercase:				Optional[Any]	,       lowercase:				str	,       lowercase:				Optional[Any]		)     ->					Tuple:







 '''simple docstring'''
 _UpperCamelCase:  int    						=			multiprocessing.Manager()
 _UpperCamelCase:  List[str]    						=			manager.list()

 _UpperCamelCase:  List[Any]    						=			multiprocessing.Process(target=lowercase	,       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_  (		lowercase:				Union[str, Any]	,       lowercase:				Any	,       lowercase:				Optional[int]		)     ->					Dict:







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

  _UpperCamelCase:  Optional[int]    						=			shutil.rmtree
  _UpperCamelCase:  Optional[int]    						=			os.rmdir
  _UpperCamelCase:  Optional[Any]    						=			os.chdir

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

  # Run program.
  try:
   _UpperCamelCase:  List[Any]    						=			{}
   with swallow_io():
    with time_limit(lowercase		):
     exec(lowercase	,       lowercase		)
   result.append('''passed'''		)
  except TimeoutException:
   result.append('''timed out'''		)
  except BaseException as e:
   result.append(F"""failed: {e}"""		)

  # Needed for cleaning up.
  _UpperCamelCase:  Tuple    						=			rmtree
  _UpperCamelCase:  Union[str, Any]    						=			rmdir
  _UpperCamelCase:  str    						=			chdir




@contextlib.contextmanager
def    lowerCAmelCase_  (		lowercase:				Tuple		)     ->					List[str]:







 '''simple docstring'''
 def signal_handler(lowercase:				Optional[Any]	,       lowercase:				Any		):
  raise TimeoutException('''Timed out!'''		)

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




@contextlib.contextmanager
def    lowerCAmelCase_  (		)     ->					str:







 '''simple docstring'''
 _UpperCamelCase:  List[Any]    						=			WriteOnlyStringIO()
 with contextlib.redirect_stdout(lowercase		):
  with contextlib.redirect_stderr(lowercase		):
   with redirect_stdin(lowercase		):
    yield




@contextlib.contextmanager
def    lowerCAmelCase_  (		)     ->					str:







 '''simple docstring'''
 with tempfile.TemporaryDirectory() as dirname:
  with chdir(lowercase		):
   yield dirname




class 			__magic_name__	(		__a     ):





   """simple docstring"""




   pass




class 			__magic_name__	(		io.StringIO     ):





   """simple docstring"""




   def 	lowerCAmelCase    (						self       :	int		,	*_lowercase       :	List[Any]		,	**_lowercase       :	Tuple				):



    """simple docstring"""



    raise OSError



   def 	lowerCAmelCase    (						self       :	Any		,	*_lowercase       :	Union[str, Any]		,	**_lowercase       :	Union[str, Any]				):



    """simple docstring"""



    raise OSError



   def 	lowerCAmelCase    (						self       :	List[Any]		,	*_lowercase       :	Optional[int]		,	**_lowercase       :	int				):



    """simple docstring"""



    raise OSError



   def 	lowerCAmelCase    (						self       :	Any		,	*_lowercase       :	List[Any]		,	**_lowercase       :	List[Any]				):



    """simple docstring"""



    return False




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





   """simple docstring"""




   lowerCAmelCase   :     Dict	      = '''stdin'''




@contextlib.contextmanager
def    lowerCAmelCase_  (		lowercase:				List[str]		)     ->					Optional[int]:







 '''simple docstring'''
 if root == ".":
  yield
  return
 _UpperCamelCase:  str    						=			os.getcwd()
 os.chdir(lowercase		)
 try:
  yield
 except BaseException as exc:
  raise exc
 finally:
  os.chdir(lowercase		)





def    lowerCAmelCase_  (		lowercase:				int=None		)     ->					Any:







 '''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:  Any    						=			None
 _UpperCamelCase:  Optional[int]    						=			None

 import os

 _UpperCamelCase:  Any    						=			'''1'''

 _UpperCamelCase:  Union[str, Any]    						=			None
 _UpperCamelCase:  Dict    						=			None
 _UpperCamelCase:  Union[str, Any]    						=			None
 _UpperCamelCase:  List[str]    						=			None
 _UpperCamelCase:  Tuple    						=			None
 _UpperCamelCase:  Tuple    						=			None
 _UpperCamelCase:  List[Any]    						=			None
 _UpperCamelCase:  Any    						=			None
 _UpperCamelCase:  int    						=			None
 _UpperCamelCase:  List[Any]    						=			None
 _UpperCamelCase:  Dict    						=			None
 _UpperCamelCase:  str    						=			None
 _UpperCamelCase:  Optional[int]    						=			None
 _UpperCamelCase:  List[str]    						=			None
 _UpperCamelCase:  Tuple    						=			None
 _UpperCamelCase:  Optional[int]    						=			None
 _UpperCamelCase:  Tuple    						=			None
 _UpperCamelCase:  Tuple    						=			None
 _UpperCamelCase:  Dict    						=			None
 _UpperCamelCase:  Optional[int]    						=			None
 _UpperCamelCase:  Union[str, Any]    						=			None
 _UpperCamelCase:  List[Any]    						=			None
 _UpperCamelCase:  int    						=			None
 _UpperCamelCase:  Optional[Any]    						=			None
 _UpperCamelCase:  List[Any]    						=			None
 _UpperCamelCase:  Union[str, Any]    						=			None
 _UpperCamelCase:  Any    						=			None

 import shutil

 _UpperCamelCase:  Optional[Any]    						=			None
 _UpperCamelCase:  List[str]    						=			None
 _UpperCamelCase:  Any    						=			None

 import subprocess

 _UpperCamelCase:  Optional[Any]    						=			None  # type: ignore

 _UpperCamelCase:  List[str]    						=			None

 import sys

 _UpperCamelCase:  int    						=			None
 _UpperCamelCase:  List[str]    						=			None
 _UpperCamelCase:  List[str]    						=			None
 _UpperCamelCase:  str    						=			None
 _UpperCamelCase:  int    						=			None
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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
    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


UpperCAmelCase_           =				logging.get_logger(__name__)




def    lowerCAmelCase_  (		lowercase:				str	,       lowercase:				Union[str, Any]		)     ->					Optional[int]:







 '''simple docstring'''
 _UpperCamelCase:  int    						=			b.T
 _UpperCamelCase:  Optional[Any]    						=			np.sum(np.square(lowercase		)	,       axis=1		)
 _UpperCamelCase:  List[Any]    						=			np.sum(np.square(lowercase		)	,       axis=0		)
 _UpperCamelCase:  Tuple    						=			np.matmul(lowercase	,       lowercase		)
 _UpperCamelCase:  Tuple    						=			aa[:, None] - 2 * ab + ba[None, :]
 return d




def    lowerCAmelCase_  (		lowercase:				List[str]	,       lowercase:				List[Any]		)     ->					List[Any]:







 '''simple docstring'''
 _UpperCamelCase:  Tuple    						=			x.reshape(-1	,       3		)
 _UpperCamelCase:  Dict    						=			squared_euclidean_distance(lowercase	,       lowercase		)
 return np.argmin(lowercase	,       axis=1		)





class 			__magic_name__	(		__a     ):





   """simple docstring"""




   lowerCAmelCase   :     Optional[Any]	      = ['''pixel_values''']



   def __init__(						self       :	List[str]		,	_lowercase       :	Optional[Union[List[List[int]], np.ndarray]] = None		,	_lowercase       :	bool = True		,	_lowercase       :	Dict[str, int] = None		,	_lowercase       :	PILImageResampling = PILImageResampling.BILINEAR		,	_lowercase       :	bool = True		,	_lowercase       :	bool = True		,	**_lowercase       :	Tuple		,	):



    """simple docstring"""



    super().__init__(**_lowercase				)
    _UpperCamelCase:  Tuple    						=			size if size is not None else {'''height''': 256, '''width''': 256}
    _UpperCamelCase:  List[str]    						=			get_size_dict(_lowercase				)
    _UpperCamelCase:  Dict    						=			np.array(_lowercase				) if clusters is not None else None
    _UpperCamelCase:  Optional[Any]    						=			do_resize
    _UpperCamelCase:  Union[str, Any]    						=			size
    _UpperCamelCase:  Optional[int]    						=			resample
    _UpperCamelCase:  Any    						=			do_normalize
    _UpperCamelCase:  int    						=			do_color_quantize



   def 	lowerCAmelCase    (						self       :	List[Any]		,	_lowercase       :	np.ndarray		,	_lowercase       :	Dict[str, int]		,	_lowercase       :	PILImageResampling = PILImageResampling.BILINEAR		,	_lowercase       :	Optional[Union[str, ChannelDimension]] = None		,	**_lowercase       :	Tuple		,	):



    """simple docstring"""



    _UpperCamelCase:  List[str]    						=			get_size_dict(_lowercase				)
    if "height" not in size or "width" not in size:
     raise ValueError(f"""Size dictionary must contain both height and width keys. Got {size.keys()}"""				)
    return resize(
        _lowercase		,	size=(size['''height'''], size['''width'''])		,	resample=_lowercase		,	data_format=_lowercase		,	**_lowercase				)



   def 	lowerCAmelCase    (						self       :	Optional[int]		,	_lowercase       :	np.ndarray		,	_lowercase       :	Optional[Union[str, ChannelDimension]] = None		,	):



    """simple docstring"""



    _UpperCamelCase:  Any    						=			rescale(image=_lowercase		,	scale=1 / 127.5		,	data_format=_lowercase				)
    _UpperCamelCase:  List[Any]    						=			image - 1
    return image



   def 	lowerCAmelCase    (						self       :	Optional[int]		,	_lowercase       :	ImageInput		,	_lowercase       :	bool = None		,	_lowercase       :	Dict[str, int] = None		,	_lowercase       :	PILImageResampling = None		,	_lowercase       :	bool = None		,	_lowercase       :	Optional[bool] = None		,	_lowercase       :	Optional[Union[List[List[int]], np.ndarray]] = None		,	_lowercase       :	Optional[Union[str, TensorType]] = None		,	_lowercase       :	Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST		,	**_lowercase       :	List[str]		,	):



    """simple docstring"""



    _UpperCamelCase:  Any    						=			do_resize if do_resize is not None else self.do_resize
    _UpperCamelCase:  Optional[Any]    						=			size if size is not None else self.size
    _UpperCamelCase:  Optional[Any]    						=			get_size_dict(_lowercase				)
    _UpperCamelCase:  Optional[int]    						=			resample if resample is not None else self.resample
    _UpperCamelCase:  Union[str, Any]    						=			do_normalize if do_normalize is not None else self.do_normalize
    _UpperCamelCase:  Any    						=			do_color_quantize if do_color_quantize is not None else self.do_color_quantize
    _UpperCamelCase:  Dict    						=			clusters if clusters is not None else self.clusters
    _UpperCamelCase:  Optional[Any]    						=			np.array(_lowercase				)

    _UpperCamelCase:  List[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_color_quantize and clusters is None:
     raise ValueError('''Clusters must be specified if do_color_quantize is True.'''				)

    # All transformations expect numpy arrays.
    _UpperCamelCase:  Optional[int]    						=			[to_numpy_array(_lowercase				) for image in images]

    if do_resize:
     _UpperCamelCase:  int    						=			[self.resize(image=_lowercase		,	size=_lowercase		,	resample=_lowercase				) for image in images]

    if do_normalize:
     _UpperCamelCase:  Any    						=			[self.normalize(image=_lowercase				) for image in images]

    if do_color_quantize:
     _UpperCamelCase:  Tuple    						=			[to_channel_dimension_format(_lowercase		,	ChannelDimension.LAST				) for image in images]
     # color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
     _UpperCamelCase:  Tuple    						=			np.array(_lowercase				)
     _UpperCamelCase:  List[Any]    						=			color_quantize(_lowercase		,	_lowercase				).reshape(images.shape[:-1]				)

     # flatten to (batch_size, height*width)
     _UpperCamelCase:  Any    						=			images.shape[0]
     _UpperCamelCase:  Optional[int]    						=			images.reshape(_lowercase		,	-1				)

     # We need to convert back to a list of images to keep consistent behaviour across processors.
     _UpperCamelCase:  Tuple    						=			list(_lowercase				)
    else:
     _UpperCamelCase:  List[str]    						=			[to_channel_dimension_format(_lowercase		,	_lowercase				) for image in images]

    _UpperCamelCase:  List[Any]    						=			{'''input_ids''': images}
    return BatchFeature(data=_lowercase		,	tensor_type=_lowercase				)