
import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate



class       a_   ( _a						):
			a  : List[Any]				      =       CONFIG_NAME






			@register_to_config
			def __init__(			self							, __UpperCamelCase = True							, __UpperCamelCase = 8							, __UpperCamelCase = "lanczos"							, __UpperCamelCase = True							, __UpperCamelCase = False							, ):
									super().__init__()






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									if images.ndim == 3:
															_lowercase									=				images[None, ...]
									_lowercase									=				(images * 255).round().astype("""uint8"""     )
									if images.shape[-1] == 1:
															# special case for grayscale (single channel) images
															_lowercase									=				[Image.fromarray(image.squeeze()							, mode="""L"""     ) for image in images]
									else:
															_lowercase									=				[Image.fromarray(__UpperCamelCase     ) for image in images]

									return pil_images






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									if not isinstance(__UpperCamelCase							, __UpperCamelCase     ):
															_lowercase									=				[images]
									_lowercase									=				[np.array(__UpperCamelCase     ).astype(np.floataa     ) / 2_55.0 for image in images]
									_lowercase									=				np.stack(__UpperCamelCase							, axis=0     )

									return images






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									if images.ndim == 3:
															_lowercase									=				images[..., None]

									_lowercase									=				torch.from_numpy(images.transpose(0							, 3							, 1							, 2     )     )
									return images






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									_lowercase									=				images.cpu().permute(0							, 2							, 3							, 1     ).float().numpy()
									return images






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									return 2.0 * images - 1.0






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									return (images / 2 + 0.5).clamp(0							, 1     )






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									_lowercase									=				image.convert("""RGB"""     )
									return image






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase = None							, __UpperCamelCase = None							, ):
									if height is None:
															_lowercase									=				image.height
									if width is None:
															_lowercase									=				image.width

									_lowercase					,	_lowercase									=				(
									    x - x % self.config.vae_scale_factor for x in (width, height)
									)  # resize to integer multiple of vae_scale_factor
									_lowercase									=				image.resize((width, height)							, resample=PIL_INTERPOLATION[self.config.resample]     )
									return image






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase = None							, __UpperCamelCase = None							, ):
									_lowercase									=				(PIL.Image.Image, np.ndarray, torch.Tensor)
									if isinstance(__UpperCamelCase							, __UpperCamelCase     ):
															_lowercase									=				[image]
									elif not (isinstance(__UpperCamelCase							, __UpperCamelCase     ) and all(isinstance(__UpperCamelCase							, __UpperCamelCase     ) for i in image     )):
															raise ValueError(
															    f"""Input is in incorrect format: {[type(__UpperCamelCase     ) for i in image]}. Currently, we only support {", ".join(__UpperCamelCase     )}"""     )

									if isinstance(image[0]							, PIL.Image.Image     ):
															if self.config.do_convert_rgb:
																					_lowercase									=				[self.convert_to_rgb(__UpperCamelCase     ) for i in image]
															if self.config.do_resize:
																					_lowercase									=				[self.resize(__UpperCamelCase							, __UpperCamelCase							, __UpperCamelCase     ) for i in image]
															_lowercase									=				self.pil_to_numpy(__UpperCamelCase     )  # to np
															_lowercase									=				self.numpy_to_pt(__UpperCamelCase     )  # to pt

									elif isinstance(image[0]							, np.ndarray     ):
															_lowercase									=				np.concatenate(__UpperCamelCase							, axis=0     ) if image[0].ndim == 4 else np.stack(__UpperCamelCase							, axis=0     )
															_lowercase									=				self.numpy_to_pt(__UpperCamelCase     )
															_lowercase					,	_lowercase					,	_lowercase					,	_lowercase									=				image.shape
															if self.config.do_resize and (
															    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
															):
																					raise ValueError(
																					    f"""Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"""
																					    f"""currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"""     )

									elif isinstance(image[0]							, torch.Tensor     ):
															_lowercase									=				torch.cat(__UpperCamelCase							, axis=0     ) if image[0].ndim == 4 else torch.stack(__UpperCamelCase							, axis=0     )
															_lowercase					,	_lowercase					,	_lowercase					,	_lowercase									=				image.shape

															# don't need any preprocess if the image is latents
															if channel == 4:
																					return image

															if self.config.do_resize and (
															    height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
															):
																					raise ValueError(
																					    f"""Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"""
																					    f"""currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"""     )

        # expected range [0,1], normalize to [-1,1]
									_lowercase									=				self.config.do_normalize
									if image.min() < 0:
															warnings.warn(
															    """Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] """
															    f"""when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]"""							, __UpperCamelCase							, )
															_lowercase									=				False

									if do_normalize:
															_lowercase									=				self.normalize(__UpperCamelCase     )

									return image






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase = "pil"							, __UpperCamelCase = None							, ):
									if not isinstance(__UpperCamelCase							, torch.Tensor     ):
															raise ValueError(
															    f"""Input for postprocessing is in incorrect format: {type(__UpperCamelCase     )}. We only support pytorch tensor"""     )
									if output_type not in ["latent", "pt", "np", "pil"]:
															_lowercase									=				(
															    f"""the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: """
															    """`pil`, `np`, `pt`, `latent`"""
															)
															deprecate("""Unsupported output_type"""							, """1.0.0"""							, __UpperCamelCase							, standard_warn=__UpperCamelCase     )
															_lowercase									=				"""np"""

									if output_type == "latent":
															return image

									if do_denormalize is None:
															_lowercase									=				[self.config.do_normalize] * image.shape[0]

									_lowercase									=				torch.stack(
									    [self.denormalize(image[i]     ) if do_denormalize[i] else image[i] for i in range(image.shape[0]     )]     )

									if output_type == "pt":
															return image

									_lowercase									=				self.pt_to_numpy(__UpperCamelCase     )

									if output_type == "np":
															return image

									if output_type == "pil":
															return self.numpy_to_pil(__UpperCamelCase     )







class       a_   ( _a						):
			a  : List[Any]				      =       CONFIG_NAME






			@register_to_config
			def __init__(			self							, __UpperCamelCase = True							, __UpperCamelCase = 8							, __UpperCamelCase = "lanczos"							, __UpperCamelCase = True							, ):
									super().__init__()






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									if images.ndim == 3:
															_lowercase									=				images[None, ...]
									_lowercase									=				(images * 255).round().astype("""uint8"""     )
									if images.shape[-1] == 1:
															# special case for grayscale (single channel) images
															_lowercase									=				[Image.fromarray(image.squeeze()							, mode="""L"""     ) for image in images]
									else:
															_lowercase									=				[Image.fromarray(image[:, :, :3]     ) for image in images]

									return pil_images






			@staticmethod
			def       UpperCamelCase_							(			__UpperCamelCase     ):
									return image[:, :, 1] * 2**8 + image[:, :, 2]






			def       UpperCamelCase_							(			self							, __UpperCamelCase     ):
									if images.ndim == 3:
															_lowercase									=				images[None, ...]
									_lowercase									=				images[:, :, :, 3:]
									if images.shape[-1] == 6:
															_lowercase									=				(images_depth * 255).round().astype("""uint8"""     )
															_lowercase									=				[
															    Image.fromarray(self.rgblike_to_depthmap(__UpperCamelCase     )							, mode="""I;16"""     ) for image_depth in images_depth
															]
									elif images.shape[-1] == 4:
															_lowercase									=				(images_depth * 6_55_35.0).astype(np.uintaa     )
															_lowercase									=				[Image.fromarray(__UpperCamelCase							, mode="""I;16"""     ) for image_depth in images_depth]
									else:
															raise Exception("""Not supported"""     )

									return pil_images






			def       UpperCamelCase_							(			self							, __UpperCamelCase							, __UpperCamelCase = "pil"							, __UpperCamelCase = None							, ):
									if not isinstance(__UpperCamelCase							, torch.Tensor     ):
															raise ValueError(
															    f"""Input for postprocessing is in incorrect format: {type(__UpperCamelCase     )}. We only support pytorch tensor"""     )
									if output_type not in ["latent", "pt", "np", "pil"]:
															_lowercase									=				(
															    f"""the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: """
															    """`pil`, `np`, `pt`, `latent`"""
															)
															deprecate("""Unsupported output_type"""							, """1.0.0"""							, __UpperCamelCase							, standard_warn=__UpperCamelCase     )
															_lowercase									=				"""np"""

									if do_denormalize is None:
															_lowercase									=				[self.config.do_normalize] * image.shape[0]

									_lowercase									=				torch.stack(
									    [self.denormalize(image[i]     ) if do_denormalize[i] else image[i] for i in range(image.shape[0]     )]     )

									_lowercase									=				self.pt_to_numpy(__UpperCamelCase     )

									if output_type == "np":
															if image.shape[-1] == 6:
																					_lowercase									=				np.stack([self.rgblike_to_depthmap(im[:, :, 3:]     ) for im in image]							, axis=0     )
															else:
																					_lowercase									=				image[:, :, :, 3:]
															return image[:, :, :, :3], image_depth

									if output_type == "pil":
															return self.numpy_to_pil(__UpperCamelCase     ), self.numpy_to_depth(__UpperCamelCase     )
									else:
															raise Exception(f"""This type {output_type} is not supported"""     )

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A		:   List[Any]         =    logging.get_logger(__name__)

A		:   str         =    {
    '''MCG-NJU/videomae-base''': '''https://huggingface.co/MCG-NJU/videomae-base/resolve/main/config.json''',
}



class       a_   ( _a						):
			a  : str				      =       '''videomae'''






			def __init__(			self							, __UpperCamelCase=224							, __UpperCamelCase=16							, __UpperCamelCase=3							, __UpperCamelCase=16							, __UpperCamelCase=2							, __UpperCamelCase=768							, __UpperCamelCase=12							, __UpperCamelCase=12							, __UpperCamelCase=3_072							, __UpperCamelCase="gelu"							, __UpperCamelCase=0.0							, __UpperCamelCase=0.0							, __UpperCamelCase=0.02							, __UpperCamelCase=1E-12							, __UpperCamelCase=True							, __UpperCamelCase=True							, __UpperCamelCase=6							, __UpperCamelCase=384							, __UpperCamelCase=4							, __UpperCamelCase=1_536							, __UpperCamelCase=True							, **__UpperCamelCase							, ):
									super().__init__(**__UpperCamelCase     )

									_lowercase									=				image_size
									_lowercase									=				patch_size
									_lowercase									=				num_channels
									_lowercase									=				num_frames
									_lowercase									=				tubelet_size

									_lowercase									=				hidden_size
									_lowercase									=				num_hidden_layers
									_lowercase									=				num_attention_heads
									_lowercase									=				intermediate_size
									_lowercase									=				hidden_act
									_lowercase									=				hidden_dropout_prob
									_lowercase									=				attention_probs_dropout_prob
									_lowercase									=				initializer_range
									_lowercase									=				layer_norm_eps
									_lowercase									=				qkv_bias
									_lowercase									=				use_mean_pooling

									_lowercase									=				decoder_num_attention_heads
									_lowercase									=				decoder_hidden_size
									_lowercase									=				decoder_num_hidden_layers
									_lowercase									=				decoder_intermediate_size
									_lowercase									=				norm_pix_loss