



'''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 (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


A			:   Any			=      logging.get_logger(__name__)


if is_vision_available():
						import PIL





class 							lowerCAmelCase_		(	a_						):
				__UpperCAmelCase							=	['pixel_values']





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



							'''simple docstring'''







							super().__init__(**_snake_case     )

							snake_case   :							str						  =size if size is not None else {'''height''': 2_560, '''width''': 1_920}
							if isinstance(_snake_case,    (tuple, list)     ):
										# The previous feature extractor size parameter was in (width, height) format
										snake_case   :							Any						  =size[::-1]
							snake_case   :							Optional[int]						  =get_size_dict(_snake_case     )

							snake_case   :							List[Any]						  =do_resize
							snake_case   :							Any						  =size
							snake_case   :							Any						  =resample
							snake_case   :							List[str]						  =do_thumbnail
							snake_case   :							int						  =do_align_long_axis
							snake_case   :							Tuple						  =do_pad
							snake_case   :							Optional[Any]						  =do_rescale
							snake_case   :							Dict						  =rescale_factor
							snake_case   :							List[Any]						  =do_normalize
							snake_case   :							Tuple						  =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
							snake_case   :							Union[str, Any]						  =image_std if image_std is not None else IMAGENET_STANDARD_STD





				def 					__snake_case       (    self    :    str,    _snake_case    :    np.ndarray,    _snake_case    :    Dict[str, int],    _snake_case    :    Optional[Union[str, ChannelDimension]] = None     ):



							'''simple docstring'''







							snake_case   :							Optional[int]						  =get_image_size(_snake_case     )
							snake_case   :							Optional[int]						  =size['''height'''], size['''width''']

							if (output_width < output_height and input_width > input_height) or (
							    output_width > output_height and input_width < input_height
							):
										snake_case   :							Tuple						  =np.rotaa(_snake_case,    3     )

							if data_format is not None:
										snake_case   :							str						  =to_channel_dimension_format(_snake_case,    _snake_case     )

							return image





				def 					__snake_case       (    self    :    int,    _snake_case    :    np.ndarray,    _snake_case    :    Dict[str, int],    _snake_case    :    bool = False,    _snake_case    :    Optional[Union[str, ChannelDimension]] = None,    ):



							'''simple docstring'''







							snake_case   :							Optional[Any]						  =size['''height'''], size['''width''']
							snake_case   :							List[str]						  =get_image_size(_snake_case     )

							snake_case   :							Optional[int]						  =output_width - input_width
							snake_case   :							Dict						  =output_height - input_height

							if random_padding:
										snake_case   :							Optional[int]						  =np.random.randint(low=0,    high=delta_height + 1     )
										snake_case   :							Dict						  =np.random.randint(low=0,    high=delta_width + 1     )
							else:
										snake_case   :							str						  =delta_height // 2
										snake_case   :							Any						  =delta_width // 2

							snake_case   :							Any						  =delta_height - pad_top
							snake_case   :							int						  =delta_width - pad_left

							snake_case   :							Tuple						  =((pad_top, pad_bottom), (pad_left, pad_right))
							return pad(_snake_case,    _snake_case,    data_format=_snake_case     )





				def 					__snake_case       (    self    :    Any,    *_snake_case    :    Optional[int],    **_snake_case    :    Optional[int]     ):



							'''simple docstring'''







							logger.info('''pad is deprecated and will be removed in version 4.27. Please use pad_image instead.'''     )
							return self.pad_image(*_snake_case,    **_snake_case     )





				def 					__snake_case       (    self    :    Tuple,    _snake_case    :    np.ndarray,    _snake_case    :    Dict[str, int],    _snake_case    :    PILImageResampling = PILImageResampling.BICUBIC,    _snake_case    :    Optional[Union[str, ChannelDimension]] = None,    **_snake_case    :    Union[str, Any],    ):



							'''simple docstring'''







							snake_case   :							List[Any]						  =get_image_size(_snake_case     )
							snake_case   :							Union[str, Any]						  =size['''height'''], size['''width''']

							# We always resize to the smallest of either the input or output size.
							snake_case   :							List[str]						  =min(_snake_case,    _snake_case     )
							snake_case   :							Optional[Any]						  =min(_snake_case,    _snake_case     )

							if height == input_height and width == input_width:
										return image

							if input_height > input_width:
										snake_case   :							Optional[int]						  =int(input_width * height / input_height     )
							elif input_width > input_height:
										snake_case   :							Union[str, Any]						  =int(input_height * width / input_width     )

							return resize(
							    _snake_case,    size=(height, width),    resample=_snake_case,    reducing_gap=2.0,    data_format=_snake_case,    **_snake_case     )





				def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    np.ndarray,    _snake_case    :    Dict[str, int],    _snake_case    :    PILImageResampling = PILImageResampling.BICUBIC,    _snake_case    :    Optional[Union[str, ChannelDimension]] = None,    **_snake_case    :    Dict,    ):



							'''simple docstring'''







							snake_case   :							Union[str, Any]						  =get_size_dict(_snake_case     )
							snake_case   :							Any						  =min(size['''height'''],    size['''width''']     )
							snake_case   :							List[str]						  =get_resize_output_image_size(_snake_case,    size=_snake_case,    default_to_square=_snake_case     )
							snake_case   :							List[Any]						  =resize(_snake_case,    size=_snake_case,    resample=_snake_case,    data_format=_snake_case,    **_snake_case     )
							return resized_image





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



							'''simple docstring'''







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





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



							'''simple docstring'''







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






				def 					__snake_case       (    self    :    List[str],    _snake_case    :    ImageInput,    _snake_case    :    bool = None,    _snake_case    :    Dict[str, int] = None,    _snake_case    :    PILImageResampling = None,    _snake_case    :    bool = None,    _snake_case    :    bool = None,    _snake_case    :    bool = None,    _snake_case    :    bool = False,    _snake_case    :    bool = None,    _snake_case    :    float = None,    _snake_case    :    bool = None,    _snake_case    :    Optional[Union[float, List[float]]] = None,    _snake_case    :    Optional[Union[float, List[float]]] = None,    _snake_case    :    Optional[Union[str, TensorType]] = None,    _snake_case    :    Optional[ChannelDimension] = ChannelDimension.FIRST,    **_snake_case    :    List[Any],    ):



							'''simple docstring'''







							snake_case   :							Optional[Any]						  =do_resize if do_resize is not None else self.do_resize
							snake_case   :							Tuple						  =size if size is not None else self.size
							if isinstance(_snake_case,    (tuple, list)     ):
										# Previous feature extractor had size in (width, height) format
										snake_case   :							Dict						  =size[::-1]
							snake_case   :							int						  =get_size_dict(_snake_case     )
							snake_case   :							Dict						  =resample if resample is not None else self.resample
							snake_case   :							List[Any]						  =do_thumbnail if do_thumbnail is not None else self.do_thumbnail
							snake_case   :							Optional[int]						  =do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
							snake_case   :							Optional[int]						  =do_pad if do_pad is not None else self.do_pad
							snake_case   :							str						  =do_rescale if do_rescale is not None else self.do_rescale
							snake_case   :							str						  =rescale_factor if rescale_factor is not None else self.rescale_factor
							snake_case   :							Tuple						  =do_normalize if do_normalize is not None else self.do_normalize
							snake_case   :							Optional[Any]						  =image_mean if image_mean is not None else self.image_mean
							snake_case   :							str						  =image_std if image_std is not None else self.image_std

							snake_case   :							str						  =make_list_of_images(_snake_case     )

							if not valid_images(_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:
										raise ValueError('''Size 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_pad and size is None:
										raise ValueError('''Size must be specified if do_pad 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   :							List[str]						  =[to_numpy_array(_snake_case     ) for image in images]

							if do_align_long_axis:
										snake_case   :							Any						  =[self.align_long_axis(_snake_case,    size=_snake_case     ) for image in images]

							if do_resize:
										snake_case   :							List[str]						  =[self.resize(image=_snake_case,    size=_snake_case,    resample=_snake_case     ) for image in images]

							if do_thumbnail:
										snake_case   :							List[str]						  =[self.thumbnail(image=_snake_case,    size=_snake_case     ) for image in images]

							if do_pad:
										snake_case   :							Tuple						  =[self.pad_image(image=_snake_case,    size=_snake_case,    random_padding=_snake_case     ) for image in images]

							if do_rescale:
										snake_case   :							Union[str, Any]						  =[self.rescale(image=_snake_case,    scale=_snake_case     ) for image in images]

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

							snake_case   :							Tuple						  =[to_channel_dimension_format(_snake_case,    _snake_case     ) for image in images]

							snake_case   :							List[Any]						  ={'''pixel_values''': images}
							return BatchFeature(data=_snake_case,    tensor_type=_snake_case     )










'''simple docstring'''





import os
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
      import torch

      from transformers import GPTaLMHeadModel





@require_torch
@require_sentencepiece
@require_tokenizers
class 							lowerCAmelCase_		(	unittest.TestCase						):





    @slow
    @unittest.skip('''Model is not available.'''     )
    def 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







       snake_case   :							Any						  ='''nvidia/megatron-gpt2-345m/'''
       if "MYDIR" in os.environ:
          snake_case   :							Any						  =os.path.join(os.environ['''MYDIR'''],    _snake_case     )
       snake_case   :							Optional[Any]						  =GPTaLMHeadModel.from_pretrained(_snake_case     )
       model.to(_snake_case     )
       model.half()

       snake_case   :							int						  =torch.tensor(
           [[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]],    device=_snake_case,    dtype=torch.long,    )

       with torch.no_grad():
          snake_case   :							Dict						  =model(_snake_case     ).logits

       snake_case   :							Dict						  =torch.Size((1, 9, 50_257)     )
       self.assertEqual(output.shape,    _snake_case     )

       snake_case   :							str						  =torch.tensor(
           [
               4.9414,
               -0.2920,
               -1.2148,
               -4.0273,
               -0.5161,
               -5.2109,
               -1.2412,
               -1.8301,
               -1.7734,
               -4.7148,
               -0.2317,
               -1.0811,
               -2.1777,
               0.4141,
               -3.7969,
               -4.0586,
               -2.5332,
               -3.3809,
               4.3867,
           ],    device=_snake_case,    dtype=torch.half,    )

       for i in range(19     ):
          snake_case  ,    snake_case   :							Tuple						  =8 * i // 17, 2_792 * i  # along the diagonal
          snake_case  ,    snake_case   :							List[str]						  =output[0, r, c], expected_diag[i]
          snake_case   :							Optional[int]						  =f'''row={r} col={c} computed={computed} expected={expected}'''
          self.assertAlmostEqual(_snake_case,    _snake_case,    delta=1E-4,    msg=_snake_case     )





