



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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


A__  :  Union[str, Any]       = logging.get_logger(__name__)



class     __snake_case						(					UpperCamelCase_						):
							_a      				=			['''pixel_values''']




							def __init__(	self					:	str    ,    A_					:	bool = True    ,    A_					:	Dict[str, int] = None    ,    A_					:	bool = True    ,    A_					:	Dict[str, int] = None    ,    A_					:	PILImageResampling = PILImageResampling.BICUBIC    ,    A_					:	bool = True    ,    A_					:	Union[int, float] = 1 / 2_5_5    ,    A_					:	bool = True    ,    A_					:	Optional[Union[float, List[float]]] = None    ,    A_					:	Optional[Union[float, List[float]]] = None    ,    **A_					:	List[str]    ,    ):
									super().__init__(**A_)
									lowerCAmelCase_      :					Optional[int]     =			crop_size if crop_size is not None else {'''height''': 2_5_6, '''width''': 2_5_6}
									lowerCAmelCase_      :					Optional[int]     =			get_size_dict(A_    ,    param_name='''crop_size''')
									lowerCAmelCase_      :					int     =			size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
									lowerCAmelCase_      :					Tuple     =			get_size_dict(A_)

									lowerCAmelCase_      :					Optional[int]     =			do_center_crop
									lowerCAmelCase_      :					Optional[Any]     =			crop_size
									lowerCAmelCase_      :					List[str]     =			do_resize
									lowerCAmelCase_      :					List[Any]     =			size
									lowerCAmelCase_      :					Dict     =			resample
									lowerCAmelCase_      :					Optional[int]     =			do_rescale
									lowerCAmelCase_      :					Dict     =			rescale_factor
									lowerCAmelCase_      :					str     =			do_normalize
									lowerCAmelCase_      :					Optional[Any]     =			image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
									lowerCAmelCase_      :					str     =			image_std if image_std is not None else IMAGENET_DEFAULT_STD




							def        UpperCAmelCase__      (	self					:	Union[str, Any]    ,    A_					:	np.ndarray    ,    A_					:	Dict[str, int]    ,    A_					:	Optional[int] = None    ,    A_					:	Optional[Union[str, ChannelDimension]] = None    ,    **A_					:	int    ,    ):
									lowerCAmelCase_      :					List[Any]     =			self.size if size is None else size
									lowerCAmelCase_      :					List[Any]     =			get_size_dict(A_)
									lowerCAmelCase_      :					Any     =			get_size_dict(A_    ,    param_name='''crop_size''')

									lowerCAmelCase_ ,  lowerCAmelCase_      :					List[Any]     =			get_image_size(A_)
									lowerCAmelCase_      :					Optional[Any]     =			min(A_    ,    A_)
									lowerCAmelCase_      :					str     =			(size['''height'''] / crop_size['''height''']) * min_dim
									lowerCAmelCase_      :					int     =			(size['''width'''] / crop_size['''width''']) * min_dim
									return center_crop(A_    ,    size=(cropped_height, cropped_width)    ,    data_format=A_    ,    **A_)




							def        UpperCAmelCase__      (	self					:	Tuple    ,    A_					:	np.ndarray    ,    A_					:	Dict[str, int]    ,    A_					:	PILImageResampling = PIL.Image.BICUBIC    ,    A_					:	Optional[Union[str, ChannelDimension]] = None    ,    **A_					:	str    ,    ):
									lowerCAmelCase_      :					str     =			get_size_dict(A_)
									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()}""")
									return resize(
									    A_    ,    size=(size['''height'''], size['''width'''])    ,    resample=A_    ,    data_format=A_    ,    **A_)




							def        UpperCAmelCase__      (	self					:	Dict    ,    A_					:	np.ndarray    ,    A_					:	Union[int, float]    ,    A_					:	Optional[Union[str, ChannelDimension]] = None    ,    **A_					:	List[str]    ,    ):
									return rescale(A_    ,    scale=A_    ,    data_format=A_    ,    **A_)




							def        UpperCAmelCase__      (	self					:	Any    ,    A_					:	np.ndarray    ,    A_					:	Union[float, List[float]]    ,    A_					:	Union[float, List[float]]    ,    A_					:	Optional[Union[str, ChannelDimension]] = None    ,    **A_					:	Union[str, Any]    ,    ):
									return normalize(A_    ,    mean=A_    ,    std=A_    ,    data_format=A_    ,    **A_)







							def        UpperCAmelCase__      (	self					:	List[Any]    ,    A_					:	ImageInput    ,    A_					:	Optional[bool] = None    ,    A_					:	Optional[Dict[str, int]] = None    ,    A_					:	Optional[bool] = None    ,    A_					:	Optional[Dict[str, int]] = None    ,    A_					:	PILImageResampling = None    ,    A_					:	Optional[bool] = None    ,    A_					:	Optional[float] = None    ,    A_					:	Optional[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]    ,    ):
									lowerCAmelCase_      :					str     =			do_center_crop if do_center_crop is not None else self.do_center_crop
									lowerCAmelCase_      :					List[str]     =			crop_size if crop_size is not None else self.crop_size
									lowerCAmelCase_      :					int     =			get_size_dict(A_    ,    param_name='''crop_size''')
									lowerCAmelCase_      :					Optional[Any]     =			do_resize if do_resize is not None else self.do_resize
									lowerCAmelCase_      :					Any     =			size if size is not None else self.size
									lowerCAmelCase_      :					Dict     =			get_size_dict(A_)
									lowerCAmelCase_      :					List[Any]     =			resample if resample is not None else self.resample
									lowerCAmelCase_      :					List[Any]     =			do_rescale if do_rescale is not None else self.do_rescale
									lowerCAmelCase_      :					Optional[int]     =			rescale_factor if rescale_factor is not None else self.rescale_factor
									lowerCAmelCase_      :					List[Any]     =			do_normalize if do_normalize is not None else self.do_normalize
									lowerCAmelCase_      :					Optional[int]     =			image_mean if image_mean is not None else self.image_mean
									lowerCAmelCase_      :					Dict     =			image_std if image_std is not None else self.image_std

									lowerCAmelCase_      :					Tuple     =			make_list_of_images(A_)

									if not valid_images(A_):
											raise ValueError(
											    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
											    '''torch.Tensor, tf.Tensor or jax.ndarray.''')

									if do_center_crop and crop_size is None:
											raise ValueError('''If `do_center_crop` is set to `True`, `crop_size` must be provided.''')

									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_normalize and (image_mean is None or image_std is None):
											raise ValueError('''Image mean and image standard deviation must be specified if do_normalize is True.''')

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

									if do_center_crop:
											lowerCAmelCase_      :					Any     =			[self.center_crop(A_    ,    A_    ,    size=A_) for image in images]

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

									if do_rescale:
											lowerCAmelCase_      :					List[str]     =			[self.rescale(image=A_    ,    scale=A_) for image in images]

									if do_normalize:
											lowerCAmelCase_      :					Optional[Any]     =			[self.normalize(image=A_    ,    mean=A_    ,    std=A_) for image in images]

									lowerCAmelCase_      :					str     =			[to_channel_dimension_format(A_    ,    A_) for image in images]

									lowerCAmelCase_      :					Optional[int]     =			{'''pixel_values''': images}
									return BatchFeature(data=A_    ,    tensor_type=A_)










import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import VideoMAEImageProcessor



class     __snake_case						(					unittest.TestCase						):




							def __init__(	self					:	str    ,    A_					:	str    ,    A_					:	int=7    ,    A_					:	List[Any]=3    ,    A_					:	Dict=1_0    ,    A_					:	List[str]=1_8    ,    A_					:	List[Any]=3_0    ,    A_					:	str=4_0_0    ,    A_					:	str=True    ,    A_					:	Tuple=None    ,    A_					:	Optional[Any]=True    ,    A_					:	Tuple=[0.5, 0.5, 0.5]    ,    A_					:	Any=[0.5, 0.5, 0.5]    ,    A_					:	List[str]=None    ,    ):
									lowerCAmelCase_      :					Optional[Any]     =			size if size is not None else {'''shortest_edge''': 1_8}
									lowerCAmelCase_      :					Optional[int]     =			crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}

									lowerCAmelCase_      :					Any     =			parent
									lowerCAmelCase_      :					Optional[Any]     =			batch_size
									lowerCAmelCase_      :					List[Any]     =			num_channels
									lowerCAmelCase_      :					Optional[int]     =			num_frames
									lowerCAmelCase_      :					Optional[int]     =			image_size
									lowerCAmelCase_      :					List[Any]     =			min_resolution
									lowerCAmelCase_      :					str     =			max_resolution
									lowerCAmelCase_      :					List[str]     =			do_resize
									lowerCAmelCase_      :					int     =			size
									lowerCAmelCase_      :					Union[str, Any]     =			do_normalize
									lowerCAmelCase_      :					Union[str, Any]     =			image_mean
									lowerCAmelCase_      :					List[str]     =			image_std
									lowerCAmelCase_      :					Any     =			crop_size







							def        UpperCAmelCase__      (	self					:	Any):
									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}





@require_torch
@require_vision
class     __snake_case						(					UpperCamelCase_						,unittest.TestCase						):
							_a      				=			VideoMAEImageProcessor if is_vision_available() else None




							def        UpperCAmelCase__      (	self					:	Tuple):
									lowerCAmelCase_      :					int     =			VideoMAEImageProcessingTester(self)




							@property
							def        UpperCAmelCase__      (	self					:	Tuple):
									return self.image_processor_tester.prepare_image_processor_dict()




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									lowerCAmelCase_      :					int     =			self.image_processing_class(**self.image_processor_dict)
									self.assertTrue(hasattr(A_    ,    '''image_mean'''))
									self.assertTrue(hasattr(A_    ,    '''image_std'''))
									self.assertTrue(hasattr(A_    ,    '''do_normalize'''))
									self.assertTrue(hasattr(A_    ,    '''do_resize'''))
									self.assertTrue(hasattr(A_    ,    '''do_center_crop'''))
									self.assertTrue(hasattr(A_    ,    '''size'''))




							def        UpperCAmelCase__      (	self					:	Dict):
									lowerCAmelCase_      :					int     =			self.image_processing_class.from_dict(self.image_processor_dict)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 1_8})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 1_8, '''width''': 1_8})

									lowerCAmelCase_      :					str     =			self.image_processing_class.from_dict(self.image_processor_dict    ,    size=4_2    ,    crop_size=8_4)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 4_2})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 8_4, '''width''': 8_4})




							def        UpperCAmelCase__      (	self					:	Dict):
									pass




							def        UpperCAmelCase__      (	self					:	str):
									# Initialize image_processing
									lowerCAmelCase_      :					int     =			self.image_processing_class(**self.image_processor_dict)
									# create random PIL videos
									lowerCAmelCase_      :					Optional[int]     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    Image.Image)

									# Test not batched input
									lowerCAmelCase_      :					int     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					Tuple     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )




							def        UpperCAmelCase__      (	self					:	int):
									# Initialize image_processing
									lowerCAmelCase_      :					Dict     =			self.image_processing_class(**self.image_processor_dict)
									# create random numpy tensors
									lowerCAmelCase_      :					str     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_    ,    numpify=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    np.ndarray)

									# Test not batched input
									lowerCAmelCase_      :					Tuple     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					Union[str, Any]     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )







							def        UpperCAmelCase__      (	self					:	List[str]):
									# Initialize image_processing
									lowerCAmelCase_      :					Tuple     =			self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									lowerCAmelCase_      :					Tuple     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_    ,    torchify=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    torch.Tensor)

									# Test not batched input
									lowerCAmelCase_      :					List[str]     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					List[Any]     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )





