


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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_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


UpperCAmelCase_   :				List[str]						      = logging.get_logger(__name__)
class 				SCREAMING_SNAKE_CASE__						(       lowercase__    ):
      snake_case__       :  str       =		['''pixel_values''']
      def __init__( self       : Any  ,							SCREAMING_SNAKE_CASE__       : bool = True  ,							SCREAMING_SNAKE_CASE__       : Dict[str, int] = None  ,							SCREAMING_SNAKE_CASE__       : PILImageResampling = PILImageResampling.BICUBIC  ,							SCREAMING_SNAKE_CASE__       : bool = True  ,							SCREAMING_SNAKE_CASE__       : Union[int, float] = 1 / 2_5_5  ,							SCREAMING_SNAKE_CASE__       : bool = True  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[float, List[float]]] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[float, List[float]]] = None  ,							SCREAMING_SNAKE_CASE__       : bool = True  ,							**SCREAMING_SNAKE_CASE__       : str  ,							)	->    None:
             super().__init__(**SCREAMING_SNAKE_CASE__  )
             a_      :	int							=						size if size is not None else {'height': 3_8_4, 'width': 3_8_4}
             a_      :	List[str]							=						get_size_dict(SCREAMING_SNAKE_CASE__  ,							default_to_square=SCREAMING_SNAKE_CASE__  )

             a_      :	Union[str, Any]							=						do_resize
             a_      :	List[str]							=						size
             a_      :	Tuple							=						resample
             a_      :	Optional[Any]							=						do_rescale
             a_      :	Optional[int]							=						rescale_factor
             a_      :	Tuple							=						do_normalize
             a_      :	Optional[int]							=						image_mean if image_mean is not None else OPENAI_CLIP_MEAN
             a_      :	Optional[Any]							=						image_std if image_std is not None else OPENAI_CLIP_STD
             a_      :	Optional[Any]							=						do_convert_rgb
      def  SCREAMING_SNAKE_CASE							( self       : Tuple  ,							SCREAMING_SNAKE_CASE__       : np.ndarray  ,							SCREAMING_SNAKE_CASE__       : Dict[str, int]  ,							SCREAMING_SNAKE_CASE__       : PILImageResampling = PILImageResampling.BICUBIC  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[str, ChannelDimension]] = None  ,							**SCREAMING_SNAKE_CASE__       : Any  ,							)	->    np.ndarray:
             a_      :	int							=						get_size_dict(SCREAMING_SNAKE_CASE__  ,							default_to_square=SCREAMING_SNAKE_CASE__  )
             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()}"""  )
             a_      :	Union[str, Any]							=						(size['height'], size['width'])
             return resize(SCREAMING_SNAKE_CASE__  ,							size=SCREAMING_SNAKE_CASE__  ,							resample=SCREAMING_SNAKE_CASE__  ,							data_format=SCREAMING_SNAKE_CASE__  ,							**SCREAMING_SNAKE_CASE__  )
      def  SCREAMING_SNAKE_CASE							( self       : int  ,							SCREAMING_SNAKE_CASE__       : np.ndarray  ,							SCREAMING_SNAKE_CASE__       : Union[int, float]  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[str, ChannelDimension]] = None  ,							**SCREAMING_SNAKE_CASE__       : Dict  ,							)	->    Tuple:
             return rescale(SCREAMING_SNAKE_CASE__  ,							scale=SCREAMING_SNAKE_CASE__  ,							data_format=SCREAMING_SNAKE_CASE__  ,							**SCREAMING_SNAKE_CASE__  )
      def  SCREAMING_SNAKE_CASE							( self       : Union[str, Any]  ,							SCREAMING_SNAKE_CASE__       : np.ndarray  ,							SCREAMING_SNAKE_CASE__       : Union[float, List[float]]  ,							SCREAMING_SNAKE_CASE__       : Union[float, List[float]]  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[str, ChannelDimension]] = None  ,							**SCREAMING_SNAKE_CASE__       : Tuple  ,							)	->    np.ndarray:
             return normalize(SCREAMING_SNAKE_CASE__  ,							mean=SCREAMING_SNAKE_CASE__  ,							std=SCREAMING_SNAKE_CASE__  ,							data_format=SCREAMING_SNAKE_CASE__  ,							**SCREAMING_SNAKE_CASE__  )

      def  SCREAMING_SNAKE_CASE							( self       : Dict  ,							SCREAMING_SNAKE_CASE__       : ImageInput  ,							SCREAMING_SNAKE_CASE__       : Optional[bool] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[Dict[str, int]] = None  ,							SCREAMING_SNAKE_CASE__       : PILImageResampling = None  ,							SCREAMING_SNAKE_CASE__       : Optional[bool] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[float] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[bool] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[float, List[float]]] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[float, List[float]]] = None  ,							SCREAMING_SNAKE_CASE__       : Optional[Union[str, TensorType]] = None  ,							SCREAMING_SNAKE_CASE__       : bool = None  ,							SCREAMING_SNAKE_CASE__       : ChannelDimension = ChannelDimension.FIRST  ,							**SCREAMING_SNAKE_CASE__       : List[Any]  ,							)	->    PIL.Image.Image:
             a_      :	List[str]							=						do_resize if do_resize is not None else self.do_resize
             a_      :	Union[str, Any]							=						resample if resample is not None else self.resample
             a_      :	Union[str, Any]							=						do_rescale if do_rescale is not None else self.do_rescale
             a_      :	List[str]							=						rescale_factor if rescale_factor is not None else self.rescale_factor
             a_      :	Dict							=						do_normalize if do_normalize is not None else self.do_normalize
             a_      :	Any							=						image_mean if image_mean is not None else self.image_mean
             a_      :	List[Any]							=						image_std if image_std is not None else self.image_std
             a_      :	List[str]							=						do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

             a_      :	Dict							=						size if size is not None else self.size
             a_      :	List[Any]							=						get_size_dict(SCREAMING_SNAKE_CASE__  ,							default_to_square=SCREAMING_SNAKE_CASE__  )

             a_      :	Any							=						make_list_of_images(SCREAMING_SNAKE_CASE__  )

             if not valid_images(SCREAMING_SNAKE_CASE__  ):
                    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.'  )

             # PIL RGBA images are converted to RGB
             if do_convert_rgb:
                    a_      :	Optional[Any]							=						[convert_to_rgb(SCREAMING_SNAKE_CASE__  ) for image in images]

             # All transformations expect numpy arrays.
             a_      :	int							=						[to_numpy_array(SCREAMING_SNAKE_CASE__  ) for image in images]

             if do_resize:
                    a_      :	str							=						[self.resize(image=SCREAMING_SNAKE_CASE__  ,							size=SCREAMING_SNAKE_CASE__  ,							resample=SCREAMING_SNAKE_CASE__  ) for image in images]

             if do_rescale:
                    a_      :	Tuple							=						[self.rescale(image=SCREAMING_SNAKE_CASE__  ,							scale=SCREAMING_SNAKE_CASE__  ) for image in images]

             if do_normalize:
                    a_      :	Dict							=						[self.normalize(image=SCREAMING_SNAKE_CASE__  ,							mean=SCREAMING_SNAKE_CASE__  ,							std=SCREAMING_SNAKE_CASE__  ) for image in images]

             a_      :	Union[str, Any]							=						[to_channel_dimension_format(SCREAMING_SNAKE_CASE__  ,							SCREAMING_SNAKE_CASE__  ) for image in images]

             a_      :	Optional[Any]							=						BatchFeature(data={'pixel_values': images}  ,							tensor_type=SCREAMING_SNAKE_CASE__  )

             return encoded_outputs






# 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  SCREAMING_SNAKE_CASE_		(    __A				:    List[Any]						,					__A				:    List[Any]						,					__A				:    List[Any]						,					__A				:    Optional[int]       )			->	Dict:

       """simple docstring"""

       a_      :	Optional[Any]							=						multiprocessing.Manager()
       a_      :	Tuple							=						manager.list()

       a_      :	Optional[int]							=						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  SCREAMING_SNAKE_CASE_		(    __A				:    Tuple						,					__A				:    Optional[Any]						,					__A				:    Optional[Any]       )			->	Dict:

       """simple docstring"""

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

              a_      :	Any							=						shutil.rmtree
              a_      :	List[str]							=						os.rmdir
              a_      :	List[Any]							=						os.chdir

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

              # Run program.
              try:
                     a_      :	Any							=						{}
                     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.
              a_      :	Tuple							=						rmtree
              a_      :	Any							=						rmdir
              a_      :	Optional[int]							=						chdir







@contextlib.contextmanager
def  SCREAMING_SNAKE_CASE_		(    __A				:    List[str]       )			->	str:

       """simple docstring"""

       def signal_handler(__A				:    List[str]						,					__A				:    Dict       ):
              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  SCREAMING_SNAKE_CASE_		(    )			->	Dict:

       """simple docstring"""

       a_      :	int							=						WriteOnlyStringIO()
       with contextlib.redirect_stdout(__A       ):
              with contextlib.redirect_stderr(__A       ):
                     with redirect_stdin(__A       ):
                            yield







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

       """simple docstring"""

       with tempfile.TemporaryDirectory() as dirname:
              with chdir(__A       ):
                     yield dirname
class 				SCREAMING_SNAKE_CASE__						(       lowercase__    ):
      pass
class 				SCREAMING_SNAKE_CASE__						(       io.StringIO    ):
      def  SCREAMING_SNAKE_CASE							( self       : List[Any]  ,							*SCREAMING_SNAKE_CASE__       : List[str]  ,							**SCREAMING_SNAKE_CASE__       : List[Any]  )	->    int:
             raise OSError
      def  SCREAMING_SNAKE_CASE							( self       : Tuple  ,							*SCREAMING_SNAKE_CASE__       : Tuple  ,							**SCREAMING_SNAKE_CASE__       : Dict  )	->    List[str]:
             raise OSError
      def  SCREAMING_SNAKE_CASE							( self       : int  ,							*SCREAMING_SNAKE_CASE__       : Dict  ,							**SCREAMING_SNAKE_CASE__       : List[Any]  )	->    Optional[Any]:
             raise OSError

      def  SCREAMING_SNAKE_CASE							( self       : Any  ,							*SCREAMING_SNAKE_CASE__       : Union[str, Any]  ,							**SCREAMING_SNAKE_CASE__       : List[Any]  )	->    List[Any]:
             return False
class 				SCREAMING_SNAKE_CASE__						(       contextlib._RedirectStream    ):  # type: ignore
      snake_case__       :  Optional[int]       =		'''stdin'''







@contextlib.contextmanager
def  SCREAMING_SNAKE_CASE_		(    __A				:    Tuple       )			->	Union[str, Any]:

       """simple docstring"""

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







def  SCREAMING_SNAKE_CASE_		(    __A				:    Dict=None       )			->	Dict:

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

       a_      :	str							=						None
       a_      :	str							=						None

       import os

       a_      :	Optional[int]							=						'1'

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

       import shutil

       a_      :	Dict							=						None
       a_      :	Tuple							=						None
       a_      :	str							=						None

       import subprocess

       a_      :	str							=						None  # type: ignore

       a_      :	List[Any]							=						None

       import sys

       a_      :	Optional[int]							=						None
       a_      :	int							=						None
       a_      :	Any							=						None
       a_      :	str							=						None
       a_      :	str							=						None


