





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


_snake_case  :    Any						    =  logging.get_logger(__name__)



class 				_UpperCAmelCase    (    _UpperCamelCase    ):

  """simple docstring"""


  a_        = ["""pixel_values"""]






  def __init__(				self :		List[str]					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Optional[Dict[str, int]] = None					,  lowerCAmelCase_ :		PILImageResampling = PILImageResampling.BILINEAR					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Union[int, float] = 1 / 2_5_5					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Optional[Union[float, List[float]]] = None					,  lowerCAmelCase_ :		Optional[Union[float, List[float]]] = None					,  **lowerCAmelCase_ :		str					,  )							->						None:
     super().__init__(**lowerCAmelCase_     )
     __lowerCAmelCase								=	size if size is not None else {'shortest_edge': 2_5_6}
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     __lowerCAmelCase								=	crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  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 				lowercase		(				self :		Union[str, Any]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Dict[str, int]					,  lowerCAmelCase_ :		PILImageResampling = PILImageResampling.BICUBIC					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Any					,  )							->						np.ndarray:
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     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(lowerCAmelCase_					,  size=size['shortest_edge']					,  default_to_square=lowerCAmelCase_     )
     return resize(lowerCAmelCase_					,  size=lowerCAmelCase_					,  resample=lowerCAmelCase_					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		Optional[Any]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Dict[str, int]					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Optional[Any]					,  )							->						np.ndarray:
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_     )
     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(lowerCAmelCase_					,  size=(size['height'], size['width'])					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		List[str]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		float					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Optional[Any]     )							->						np.ndarray:
     return rescale(lowerCAmelCase_					,  scale=lowerCAmelCase_					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






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






  def 				lowercase		(				self :		Tuple					,  lowerCAmelCase_ :		ImageInput					,  lowerCAmelCase_ :		Optional[bool] = None					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		PILImageResampling = None					,  lowerCAmelCase_ :		bool = None					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		Optional[bool] = None					,  lowerCAmelCase_ :		Optional[float] = None					,  lowerCAmelCase_ :		Optional[bool] = None					,  lowerCAmelCase_ :		Optional[Union[float, List[float]]] = None					,  lowerCAmelCase_ :		Optional[Union[float, List[float]]] = None					,  lowerCAmelCase_ :		Optional[Union[str, TensorType]] = None					,  lowerCAmelCase_ :		Union[str, ChannelDimension] = ChannelDimension.FIRST					,  **lowerCAmelCase_ :		int					,  )							->						List[str]:
     __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(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     __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(lowerCAmelCase_					,  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(lowerCAmelCase_     )

     if not valid_images(lowerCAmelCase_     ):
        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(lowerCAmelCase_     ) for image in images]

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

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

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

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

     __lowerCAmelCase								=	[to_channel_dimension_format(lowerCAmelCase_					,  lowerCAmelCase_     ) for image in images]

     __lowerCAmelCase								=	{'pixel_values': images}
     return BatchFeature(data=lowerCAmelCase_					,  tensor_type=lowerCAmelCase_     )






  def 				lowercase		(				self :		Optional[int]					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		List[Tuple] = None     )							->						Union[str, Any]:
     __lowerCAmelCase								=	outputs.logits

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

        if is_torch_tensor(lowerCAmelCase_     ):
           __lowerCAmelCase								=	target_sizes.numpy()

        __lowerCAmelCase								=	[]

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

     return semantic_segmentation








# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


_snake_case  :    Dict						    =  {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _snake_case  :    Optional[int]						    =  [
         'MRA_PRETRAINED_MODEL_ARCHIVE_LIST',
         'MraForMaskedLM',
         'MraForMultipleChoice',
         'MraForQuestionAnswering',
         'MraForSequenceClassification',
         'MraForTokenClassification',
         'MraLayer',
         'MraModel',
         'MraPreTrainedModel',
     ]


if TYPE_CHECKING:
     from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_mra import (
              MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
              MraForMaskedLM,
              MraForMultipleChoice,
              MraForQuestionAnswering,
              MraForSequenceClassification,
              MraForTokenClassification,
              MraLayer,
              MraModel,
              MraPreTrainedModel,
          )
else:
     import sys

     _snake_case  :    Tuple						    =  _LazyModule(__name__, globals()['__file__'], _import_structure)

