'''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,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
 import PIL

if is_torch_available():
 import torch


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






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    snake_case__							:   int							=						["pixel_values"]






    def __init__(       self    ,							lowercase__ = True    ,							lowercase__ = None    ,							lowercase__ = PILImageResampling.BILINEAR    ,							lowercase__ = True    ,							lowercase__ = 1 / 255    ,							lowercase__ = True    ,							lowercase__ = None    ,							lowercase__ = True    ,							**lowercase__    ,							)							-> None:
         super().__init__(**lowercase__ )
         SCREAMING_SNAKE_CASE					:			Dict    	=       size if size is not None else {'shortest_edge': 224}
         SCREAMING_SNAKE_CASE					:			Dict    	=       get_size_dict(lowercase__    ,							default_to_square=lowercase__ )
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       crop_size if crop_size is not None else {'height': 256, 'width': 256}
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       get_size_dict(lowercase__    ,							param_name='crop_size' )

         SCREAMING_SNAKE_CASE					:			str    	=       do_resize
         SCREAMING_SNAKE_CASE					:			Dict    	=       size
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       resample
         SCREAMING_SNAKE_CASE					:			Any    	=       do_rescale
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       rescale_factor
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       do_center_crop
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       crop_size
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       do_flip_channel_order






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ = PIL.Image.BILINEAR    ,							lowercase__ = None    ,							**lowercase__    ,							)							-> np.ndarray:
         SCREAMING_SNAKE_CASE					:			int    	=       get_size_dict(lowercase__    ,							default_to_square=lowercase__ )
         if "shortest_edge" not in size:
              raise ValueError(F"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" )
         SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       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       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ = None    ,							**lowercase__    ,							)							-> np.ndarray:
         SCREAMING_SNAKE_CASE					:			str    	=       get_size_dict(lowercase__ )
         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 center_crop(lowercase__    ,							size=(size['height'], size['width'])    ,							data_format=lowercase__    ,							**lowercase__ )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ = None    ,							**lowercase__    ,							)							-> Any:
         return rescale(lowercase__    ,							scale=lowercase__    ,							data_format=lowercase__    ,							**lowercase__ )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__ = None )							-> np.ndarray:
         return flip_channel_order(lowercase__    ,							data_format=lowercase__ )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = None    ,							lowercase__ = ChannelDimension.FIRST    ,							**lowercase__    ,							)							-> PIL.Image.Image:
         SCREAMING_SNAKE_CASE					:			Any    	=       do_resize if do_resize is not None else self.do_resize
         SCREAMING_SNAKE_CASE					:			Dict    	=       resample if resample is not None else self.resample
         SCREAMING_SNAKE_CASE					:			int    	=       do_rescale if do_rescale is not None else self.do_rescale
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       rescale_factor if rescale_factor is not None else self.rescale_factor
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       do_center_crop if do_center_crop is not None else self.do_center_crop
         SCREAMING_SNAKE_CASE					:			List[str]    	=       (
             do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
         )

         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       size if size is not None else self.size
         SCREAMING_SNAKE_CASE					:			Any    	=       get_size_dict(lowercase__    ,							default_to_square=lowercase__ )
         SCREAMING_SNAKE_CASE					:			Any    	=       crop_size if crop_size is not None else self.crop_size
         SCREAMING_SNAKE_CASE					:			List[Any]    	=       get_size_dict(lowercase__    ,							param_name='crop_size' )

         SCREAMING_SNAKE_CASE					:			int    	=       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_rescale and rescale_factor is None:
              raise ValueError('Rescale factor must be specified if do_rescale is True.' )

         if do_center_crop and crop_size is None:
              raise ValueError('Crop size must be specified if do_center_crop is True.' )

         # All transformations expect numpy arrays.
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       [to_numpy_array(lowercase__ ) for image in images]

         if do_resize:
              SCREAMING_SNAKE_CASE					:			Dict    	=       [self.resize(image=lowercase__    ,							size=lowercase__    ,							resample=lowercase__ ) for image in images]

         if do_center_crop:
              SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       [self.center_crop(image=lowercase__    ,							size=lowercase__ ) for image in images]

         if do_rescale:
              SCREAMING_SNAKE_CASE					:			int    	=       [self.rescale(image=lowercase__    ,							scale=lowercase__ ) for image in images]

         # the pretrained checkpoints assume images are BGR, not RGB
         if do_flip_channel_order:
              SCREAMING_SNAKE_CASE					:			str    	=       [self.flip_channel_order(image=lowercase__ ) for image in images]

         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       [to_channel_dimension_format(lowercase__    ,							lowercase__ ) for image in images]

         SCREAMING_SNAKE_CASE					:			int    	=       {'pixel_values': images}
         return BatchFeature(data=lowercase__    ,							tensor_type=lowercase__ )






    def       _UpperCamelCase    (       self    ,							lowercase__    ,							lowercase__ = None )							-> str:
         SCREAMING_SNAKE_CASE					:			Dict    	=       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__ ):
                   SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       target_sizes.numpy()

              SCREAMING_SNAKE_CASE					:			int    	=       []

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

         return semantic_segmentation




'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_lowerCAmelCase  :int  				=    {
    """configuration_albert""": ["""ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AlbertConfig""", """AlbertOnnxConfig"""],
}

try:
 if not is_sentencepiece_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :str  				=    ["""AlbertTokenizer"""]

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :Optional[int]  				=    ["""AlbertTokenizerFast"""]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :List[str]  				=    [
     """ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """AlbertForMaskedLM""",
     """AlbertForMultipleChoice""",
     """AlbertForPreTraining""",
     """AlbertForQuestionAnswering""",
     """AlbertForSequenceClassification""",
     """AlbertForTokenClassification""",
     """AlbertModel""",
     """AlbertPreTrainedModel""",
     """load_tf_weights_in_albert""",
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :Any  				=    [
     """TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """TFAlbertForMaskedLM""",
     """TFAlbertForMultipleChoice""",
     """TFAlbertForPreTraining""",
     """TFAlbertForQuestionAnswering""",
     """TFAlbertForSequenceClassification""",
     """TFAlbertForTokenClassification""",
     """TFAlbertMainLayer""",
     """TFAlbertModel""",
     """TFAlbertPreTrainedModel""",
 ]

try:
 if not is_flax_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase  :Optional[int]  				=    [
     """FlaxAlbertForMaskedLM""",
     """FlaxAlbertForMultipleChoice""",
     """FlaxAlbertForPreTraining""",
     """FlaxAlbertForQuestionAnswering""",
     """FlaxAlbertForSequenceClassification""",
     """FlaxAlbertForTokenClassification""",
     """FlaxAlbertModel""",
     """FlaxAlbertPreTrainedModel""",
 ]

if TYPE_CHECKING:
 from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig

 try:
  if not is_sentencepiece_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_albert import AlbertTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_albert_fast import AlbertTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_albert import (
      ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      AlbertForMaskedLM,
      AlbertForMultipleChoice,
      AlbertForPreTraining,
      AlbertForQuestionAnswering,
      AlbertForSequenceClassification,
      AlbertForTokenClassification,
      AlbertModel,
      AlbertPreTrainedModel,
      load_tf_weights_in_albert,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_albert import (
      TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFAlbertForMaskedLM,
      TFAlbertForMultipleChoice,
      TFAlbertForPreTraining,
      TFAlbertForQuestionAnswering,
      TFAlbertForSequenceClassification,
      TFAlbertForTokenClassification,
      TFAlbertMainLayer,
      TFAlbertModel,
      TFAlbertPreTrainedModel,
  )

 try:
  if not is_flax_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_flax_albert import (
      FlaxAlbertForMaskedLM,
      FlaxAlbertForMultipleChoice,
      FlaxAlbertForPreTraining,
      FlaxAlbertForQuestionAnswering,
      FlaxAlbertForSequenceClassification,
      FlaxAlbertForTokenClassification,
      FlaxAlbertModel,
      FlaxAlbertPreTrainedModel,
  )
else:
 import sys

 _lowerCAmelCase  :Union[str, Any]  				=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



