


'''simple docstring'''






from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
		import torch


__UpperCAmelCase       							=				logging.get_logger(__name__)




class 						a__							(				UpperCamelCase__    ):





							'''simple docstring'''






							lowercase__     :  int      		= ["pixel_values"]







							def __init__(						self   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = PILImageResampling.BILINEAR   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = 1 / 2_55   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       **lowerCamelCase_   ,       )			->				None:
														super().__init__(**lowercase_  )
														lowerCAmelCase__			  =      size if size is not None else {'''shortest_edge''': 2_56}
														lowerCAmelCase__			  =      get_size_dict(lowercase_   ,       default_to_square=lowercase_  )
														lowerCAmelCase__			  =      crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
														lowerCAmelCase__			  =      get_size_dict(lowercase_   ,       param_name='''crop_size'''  )
														lowerCAmelCase__			  =      do_resize
														lowerCAmelCase__			  =      size
														lowerCAmelCase__			  =      resample
														lowerCAmelCase__			  =      do_center_crop
														lowerCAmelCase__			  =      crop_size
														lowerCAmelCase__			  =      do_rescale
														lowerCAmelCase__			  =      rescale_factor
														lowerCAmelCase__			  =      do_normalize
														lowerCAmelCase__			  =      image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
														lowerCAmelCase__			  =      image_std if image_std is not None else IMAGENET_STANDARD_STD







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = PILImageResampling.BICUBIC   ,       lowerCamelCase_ = None   ,       **lowerCamelCase_   ,       )			->				np.ndarray:
														lowerCAmelCase__			  =      get_size_dict(lowercase_   ,       default_to_square=lowercase_  )
														if "shortest_edge" not in size:
																					raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""  )
														lowerCAmelCase__			  =      get_resize_output_image_size(lowercase_   ,       size=size['''shortest_edge''']   ,       default_to_square=lowercase_  )
														return resize(lowercase_   ,       size=lowercase_   ,       resample=lowercase_   ,       data_format=lowercase_   ,       **lowercase_  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = None   ,       **lowerCamelCase_   ,       )			->				np.ndarray:
														lowerCAmelCase__			  =      get_size_dict(lowercase_  )
														if "height" not in size or "width" not in size:
																					raise ValueError(F"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"""  )
														return center_crop(lowercase_   ,       size=(size['''height'''], size['''width'''])   ,       data_format=lowercase_   ,       **lowercase_  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = None   ,       **lowerCamelCase_  )			->				np.ndarray:
														return rescale(lowercase_   ,       scale=lowercase_   ,       data_format=lowercase_   ,       **lowercase_  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = None   ,       **lowerCamelCase_   ,       )			->				np.ndarray:
														return normalize(lowercase_   ,       mean=lowercase_   ,       std=lowercase_   ,       data_format=lowercase_   ,       **lowercase_  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = None   ,       lowerCamelCase_ = ChannelDimension.FIRST   ,       **lowerCamelCase_   ,       )			->				Any:
														lowerCAmelCase__			  =      do_resize if do_resize is not None else self.do_resize
														lowerCAmelCase__			  =      size if size is not None else self.size
														lowerCAmelCase__			  =      get_size_dict(lowercase_   ,       default_to_square=lowercase_  )
														lowerCAmelCase__			  =      resample if resample is not None else self.resample
														lowerCAmelCase__			  =      do_center_crop if do_center_crop is not None else self.do_center_crop
														lowerCAmelCase__			  =      crop_size if crop_size is not None else self.crop_size
														lowerCAmelCase__			  =      get_size_dict(lowercase_   ,       param_name='''crop_size'''  )
														lowerCAmelCase__			  =      do_rescale if do_rescale is not None else self.do_rescale
														lowerCAmelCase__			  =      rescale_factor if rescale_factor is not None else self.rescale_factor
														lowerCAmelCase__			  =      do_normalize if do_normalize is not None else self.do_normalize
														lowerCAmelCase__			  =      image_mean if image_mean is not None else self.image_mean
														lowerCAmelCase__			  =      image_std if image_std is not None else self.image_std

														lowerCAmelCase__			  =      make_list_of_images(lowercase_  )

														if not valid_images(lowercase_  ):
																					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_center_crop and crop_size is None:
																					raise ValueError('''Crop size must be specified if do_center_crop 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.
														lowerCAmelCase__			  =      [to_numpy_array(lowercase_  ) for image in images]

														if do_resize:
																					lowerCAmelCase__			  =      [self.resize(image=lowercase_   ,       size=lowercase_   ,       resample=lowercase_  ) for image in images]

														if do_center_crop:
																					lowerCAmelCase__			  =      [self.center_crop(image=lowercase_   ,       size=lowercase_  ) for image in images]

														if do_rescale:
																					lowerCAmelCase__			  =      [self.rescale(image=lowercase_   ,       scale=lowercase_  ) for image in images]

														if do_normalize:
																					lowerCAmelCase__			  =      [self.normalize(image=lowercase_   ,       mean=lowercase_   ,       std=lowercase_  ) for image in images]

														lowerCAmelCase__			  =      [to_channel_dimension_format(lowercase_   ,       lowercase_  ) for image in images]

														lowerCAmelCase__			  =      {'''pixel_values''': images}
														return BatchFeature(data=lowercase_   ,       tensor_type=lowercase_  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_ = None  )			->				Any:
														lowerCAmelCase__			  =      outputs.logits

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

																					if is_torch_tensor(lowercase_  ):
																												lowerCAmelCase__			  =      target_sizes.numpy()

																					lowerCAmelCase__			  =      []

																					for idx in range(len(lowercase_  )  ):
																												lowerCAmelCase__			  =      torch.nn.functional.interpolate(
																												    logits[idx].unsqueeze(dim=0  )   ,       size=target_sizes[idx]   ,       mode='''bilinear'''   ,       align_corners=lowercase_  )
																												lowerCAmelCase__			  =      resized_logits[0].argmax(dim=0  )
																												semantic_segmentation.append(lowercase_  )
														else:
																					lowerCAmelCase__			  =      logits.argmax(dim=1  )
																					lowerCAmelCase__			  =      [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]  )]

														return semantic_segmentation






'''simple docstring'''

from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer






@dataclass
class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							42






class   UpperCAmelCase      (			UpperCamelCase__     ,			UpperCamelCase__							):
 @register_to_config
 def __init__(							self :Tuple		,			lowercase_ :int = 3		,			lowercase_ :int = 3		,			lowercase_ :Tuple[str] = ("DownEncoderBlock2D",)		,			lowercase_ :Tuple[str] = ("UpDecoderBlock2D",)		,			lowercase_ :Tuple[int] = (64,)		,			lowercase_ :int = 1		,			lowercase_ :str = "silu"		,			lowercase_ :int = 3		,			lowercase_ :int = 32		,			lowercase_ :int = 2_56		,			lowercase_ :int = 32		,			lowercase_ :Optional[int] = None		,			lowercase_ :float = 0.1_8_2_1_5		,			lowercase_ :str = "group"		,			)->				Optional[int]:
     super().__init__()

     # pass init params to Encoder
     A__							=     Encoder(
         in_channels=lowercase_		,			out_channels=lowercase_		,			down_block_types=lowercase_		,			block_out_channels=lowercase_		,			layers_per_block=lowercase_		,			act_fn=lowercase_		,			norm_num_groups=lowercase_		,			double_z=lowercase_		,			)

     A__							=     vq_embed_dim if vq_embed_dim is not None else latent_channels

     A__							=     nn.Convad(lowercase_		,			lowercase_		,			1				)
     A__							=     VectorQuantizer(lowercase_		,			lowercase_		,			beta=0.2_5		,			remap=lowercase_		,			sane_index_shape=lowercase_				)
     A__							=     nn.Convad(lowercase_		,			lowercase_		,			1				)

     # pass init params to Decoder
     A__							=     Decoder(
         in_channels=lowercase_		,			out_channels=lowercase_		,			up_block_types=lowercase_		,			block_out_channels=lowercase_		,			layers_per_block=lowercase_		,			act_fn=lowercase_		,			norm_num_groups=lowercase_		,			norm_type=lowercase_		,			)
 @apply_forward_hook
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :torch.FloatTensor		,			lowercase_ :bool = True				)->				VQEncoderOutput:
     A__							=     self.encoder(lowercase_				)
     A__							=     self.quant_conv(lowercase_				)

     if not return_dict:
         return (h,)

     return VQEncoderOutput(latents=lowercase_				)
 @apply_forward_hook
 def 	UpperCAmelCase_				(							self :Dict		,			lowercase_ :torch.FloatTensor		,			lowercase_ :bool = False		,			lowercase_ :bool = True				)->				Union[DecoderOutput, torch.FloatTensor]:
     # also go through quantization layer
     if not force_not_quantize:
         A__,      A__,      A__							=     self.quantize(lowercase_				)
     else:
         A__							=     h
     A__							=     self.post_quant_conv(lowercase_				)
     A__							=     self.decoder(lowercase_		,			quant if self.config.norm_type == "spatial" else None				)

     if not return_dict:
         return (dec,)

     return DecoderOutput(sample=lowercase_				)



 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :torch.FloatTensor		,			lowercase_ :bool = True				)->				Union[DecoderOutput, torch.FloatTensor]:
     A__							=     sample
     A__							=     self.encode(lowercase_				).latents
     A__							=     self.decode(lowercase_				).sample

     if not return_dict:
         return (dec,)

     return DecoderOutput(sample=lowercase_				)



