

'''simple docstring'''






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


__SCREAMING_SNAKE_CASE     =						logging.get_logger(__name__)



def 			__a		(       lowerCAmelCase__ :    int     ,  lowerCAmelCase__ :    Union[str, Any]     ,  lowerCAmelCase__ :    Any     ,  lowerCAmelCase__ :    Union[str, Any]      ):
     def constraint_to_multiple_of(lowerCAmelCase__ :    Union[str, Any]     ,  lowerCAmelCase__ :    List[Any]     ,  lowerCAmelCase__ :    str=0     ,  lowerCAmelCase__ :    Union[str, Any]=None      ):
          a__   :      List[str]     =						round(val / multiple      ) * multiple

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

          if x < min_val:
               a__   :      List[Any]     =						math.ceil(val / multiple      ) * multiple

          return x

     a__   :      Tuple     =						(output_size, output_size) if isinstance(snake_case__     ,  snake_case__      ) else output_size

     a__   :      Tuple     =						get_image_size(snake_case__      )
     a__   :      Optional[int]     =						output_size

     # determine new height and width
     a__   :      List[Any]     =						output_height / input_height
     a__   :      List[str]     =						output_width / input_width

     if keep_aspect_ratio:
          # scale as little as possible
          if abs(1 - scale_width      ) < abs(1 - scale_height      ):
               # fit width
               a__   :      Optional[int]     =						scale_width
          else:
               # fit height
               a__   :      str     =						scale_height

     a__   :      List[Any]     =						constraint_to_multiple_of(scale_height * input_height     ,  multiple=snake_case__      )
     a__   :      Dict     =						constraint_to_multiple_of(scale_width * input_width     ,  multiple=snake_case__      )

     return (new_height, new_width)






class 			lowerCAmelCase__     (					lowerCamelCase__						):




     """simple docstring"""





     __UpperCamelCase									= ["pixel_values"]







     def __init__(		self						:	List[Any]      ,						A__						:	str = True      ,						A__						:	Dict = None      ,						A__						:	Optional[Any] = PILImageResampling.BILINEAR      ,						A__						:	Union[str, Any] = False      ,						A__						:	List[str] = 1      ,						A__						:	Dict = True      ,						A__						:	List[str] = 1 / 2_5_5      ,						A__						:	List[str] = True      ,						A__						:	str = None      ,						A__						:	int = None      ,						**A__						:	Any      ,						)       ->			None:
          '''simple docstring'''




          super().__init__(**SCREAMING_SNAKE_CASE__	)
          a__   :      int     =						size if size is not None else {'''height''': 3_8_4, '''width''': 3_8_4}
          a__   :      Union[str, Any]     =						get_size_dict(SCREAMING_SNAKE_CASE__	)
          a__   :      Dict     =						do_resize
          a__   :      Tuple     =						size
          a__   :      Union[str, Any]     =						keep_aspect_ratio
          a__   :      Dict     =						ensure_multiple_of
          a__   :      Tuple     =						resample
          a__   :      List[str]     =						do_rescale
          a__   :      List[Any]     =						rescale_factor
          a__   :      Optional[Any]     =						do_normalize
          a__   :      List[Any]     =						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          a__   :      Any     =						image_std if image_std is not None else IMAGENET_STANDARD_STD







     def 			__lowerCAmelCase	(		self						:	Tuple      ,						A__						:	Union[str, Any]      ,						A__						:	List[Any]      ,						A__						:	Tuple = False      ,						A__						:	List[str] = 1      ,						A__						:	int = PILImageResampling.BICUBIC      ,						A__						:	Optional[int] = None      ,						**A__						:	Tuple      ,						)       ->			np.ndarray:
          '''simple docstring'''




          a__   :      List[Any]     =						get_size_dict(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__   :      Optional[int]     =						get_resize_output_image_size(
              SCREAMING_SNAKE_CASE__      ,						output_size=(size['''height'''], size['''width'''])      ,						keep_aspect_ratio=SCREAMING_SNAKE_CASE__      ,						multiple=SCREAMING_SNAKE_CASE__      ,						)
          return resize(SCREAMING_SNAKE_CASE__      ,						size=SCREAMING_SNAKE_CASE__      ,						resample=SCREAMING_SNAKE_CASE__      ,						data_format=SCREAMING_SNAKE_CASE__      ,						**SCREAMING_SNAKE_CASE__	)







     def 			__lowerCAmelCase	(		self						:	str      ,						A__						:	Union[str, Any]      ,						A__						:	Tuple      ,						A__						:	List[str] = None      ,						**A__						:	Dict      ,						)       ->			Tuple:
          '''simple docstring'''




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







     def 			__lowerCAmelCase	(		self						:	Dict      ,						A__						:	Dict      ,						A__						:	List[Any]      ,						A__						:	str      ,						A__						:	Any = None      ,						**A__						:	Any      ,						)       ->			np.ndarray:
          '''simple docstring'''




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







     def 			__lowerCAmelCase	(		self						:	Optional[Any]      ,						A__						:	Dict      ,						A__						:	Tuple = None      ,						A__						:	List[Any] = None      ,						A__						:	Tuple = None      ,						A__						:	str = None      ,						A__						:	int = None      ,						A__						:	List[Any] = None      ,						A__						:	Tuple = None      ,						A__						:	List[str] = None      ,						A__						:	str = None      ,						A__						:	Union[str, Any] = None      ,						A__						:	Optional[int] = None      ,						A__						:	Tuple = ChannelDimension.FIRST      ,						**A__						:	Union[str, Any]      ,						)       ->			PIL.Image.Image:
          '''simple docstring'''




          a__   :      List[str]     =						do_resize if do_resize is not None else self.do_resize
          a__   :      Union[str, Any]     =						size if size is not None else self.size
          a__   :      Optional[int]     =						get_size_dict(SCREAMING_SNAKE_CASE__	)
          a__   :      str     =						keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
          a__   :      Optional[int]     =						ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
          a__   :      Tuple     =						resample if resample is not None else self.resample
          a__   :      Optional[int]     =						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__   :      Optional[int]     =						do_normalize if do_normalize is not None else self.do_normalize
          a__   :      List[Any]     =						image_mean if image_mean is not None else self.image_mean
          a__   :      Tuple     =						image_std if image_std is not None else self.image_std

          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.'''	)

          # All transformations expect numpy arrays.
          a__   :      List[str]     =						[to_numpy_array(SCREAMING_SNAKE_CASE__	) for image in images]

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

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

          if do_normalize:
               a__   :      List[Any]     =						[self.normalize(image=SCREAMING_SNAKE_CASE__      ,						mean=SCREAMING_SNAKE_CASE__      ,						std=SCREAMING_SNAKE_CASE__	) for image in images]

          a__   :      Optional[int]     =						[to_channel_dimension_format(SCREAMING_SNAKE_CASE__      ,						SCREAMING_SNAKE_CASE__	) for image in images]

          a__   :      Dict     =						{'''pixel_values''': images}
          return BatchFeature(data=SCREAMING_SNAKE_CASE__      ,						tensor_type=SCREAMING_SNAKE_CASE__	)







     def 			__lowerCAmelCase	(		self						:	int      ,						A__						:	Any      ,						A__						:	Tuple = None	)       ->			List[Any]:
          '''simple docstring'''




          a__   :      int     =						outputs.logits

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

               if is_torch_tensor(SCREAMING_SNAKE_CASE__	):
                    a__   :      str     =						target_sizes.numpy()

               a__   :      List[str]     =						[]

               for idx in range(len(SCREAMING_SNAKE_CASE__	)	):
                    a__   :      Union[str, Any]     =						torch.nn.functional.interpolate(
                        logits[idx].unsqueeze(dim=0	)      ,						size=target_sizes[idx]      ,						mode='''bilinear'''      ,						align_corners=SCREAMING_SNAKE_CASE__	)
                    a__   :      List[Any]     =						resized_logits[0].argmax(dim=0	)
                    semantic_segmentation.append(SCREAMING_SNAKE_CASE__	)
          else:
               a__   :      Optional[int]     =						logits.argmax(dim=1	)
               a__   :      Union[str, Any]     =						[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]	)]

          return semantic_segmentation




"""simple docstring"""






import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate





def 				A_       ( snake_case__		)					->  Union[str, Any]:
			return x + 2






class      A(  unittest.TestCase		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	'''x = 3'''
					_UpperCamelCase					:List[str]					     =	{}
					_UpperCamelCase					:int					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3}   )

					_UpperCamelCase					:Tuple					     =	'''x = y'''
					_UpperCamelCase					:Optional[int]					     =	{'''y''': 5}
					_UpperCamelCase					:Optional[Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 5, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''y = add_two(x)'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )

					# Won't work without the tool
					with CaptureStdout() as out:
								_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result is None
					assert "tried to execute add_two" in out.out
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	'''x = 3'''
					_UpperCamelCase					:int					     =	{}
					_UpperCamelCase					:List[Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3}   )
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''test_dict = {\'x\': x, \'y\': add_two(x)}'''
					_UpperCamelCase					:str					     =	{'''x''': 3}
					_UpperCamelCase					:Dict					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	'''x = 3\ny = 5'''
					_UpperCamelCase					:int					     =	{}
					_UpperCamelCase					:Optional[int]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	'''text = f\'This is x: {x}.\''''
					_UpperCamelCase					:List[str]					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == "This is x: 3."
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''text''': '''This is x: 3.'''}   )
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[Any]					     =	'''if x <= 3:\n    y = 2\nelse:\n    y = 5'''
					_UpperCamelCase					:Dict					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 2
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 2}   )

					_UpperCamelCase					:Union[str, Any]					     =	{'''x''': 8}
					_UpperCamelCase					:Optional[int]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 8, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	'''test_list = [x, add_two(x)]'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:str					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					self.assertListEqual(SCREAMING_SNAKE_CASE__					,				[3, 5]   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_list''': [3, 5]}   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:List[Any]					     =	'''y = x'''
					_UpperCamelCase					:List[str]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 3}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	'''test_list = [x, add_two(x)]\ntest_list[1]'''
					_UpperCamelCase					:Optional[Any]					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_list''': [3, 5]}   )

					_UpperCamelCase					:str					     =	'''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}}   )





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''x = 0\nfor i in range(3):\n    x = i'''
					_UpperCamelCase					:Tuple					     =	{}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''range''': range}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 2
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 2, '''i''': 2}   )

