

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


__lowercase				      =						logging.get_logger(__name__)

class    _lowercase				(					__lowerCamelCase			):
   _lowercase     :       Tuple  					=    ['pixel_values']

   def __init__(				self	:    Union[str, Any]			,						lowerCamelCase__	:    bool = True			,						lowerCamelCase__	:    Dict[str, int] = None			,						lowerCamelCase__	:    PILImageResampling = PILImageResampling.BILINEAR			,						lowerCamelCase__	:    bool = True			,						lowerCamelCase__	:    Union[int, float] = 1 / 2_5_5			,						lowerCamelCase__	:    bool = True			,						lowerCamelCase__	:    Dict[str, int] = None			,						lowerCamelCase__	:    bool = True			,						**lowerCamelCase__	:    Tuple			,						) ->			None:
         """simple docstring"""





         super().__init__(**lowerCamelCase__       )
         A_							       =		size if size is not None else {'''shortest_edge''': 2_2_4}
         A_							       =		get_size_dict(lowerCamelCase__			,						default_to_square=lowerCamelCase__       )
         A_							       =		crop_size if crop_size is not None else {'''height''': 2_5_6, '''width''': 2_5_6}
         A_							       =		get_size_dict(lowerCamelCase__			,						param_name='''crop_size'''       )

         A_							       =		do_resize
         A_							       =		size
         A_							       =		resample
         A_							       =		do_rescale
         A_							       =		rescale_factor
         A_							       =		do_center_crop
         A_							       =		crop_size
         A_							       =		do_flip_channel_order

   def     UpperCamelCase					(				self	:    List[Any]			,						lowerCamelCase__	:    np.ndarray			,						lowerCamelCase__	:    Dict[str, int]			,						lowerCamelCase__	:    PILImageResampling = PIL.Image.BILINEAR			,						lowerCamelCase__	:    Optional[Union[str, ChannelDimension]] = None			,						**lowerCamelCase__	:    List[str]			,						) ->			np.ndarray:
         """simple docstring"""





         A_							       =		get_size_dict(lowerCamelCase__			,						default_to_square=lowerCamelCase__       )
         if "shortest_edge" not in size:
               raise ValueError(F"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}"       )
         A_							       =		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     UpperCamelCase					(				self	:    int			,						lowerCamelCase__	:    np.ndarray			,						lowerCamelCase__	:    Dict[str, int]			,						lowerCamelCase__	:    Optional[Union[str, ChannelDimension]] = None			,						**lowerCamelCase__	:    Tuple			,						) ->			np.ndarray:
         """simple docstring"""





         A_							       =		get_size_dict(lowerCamelCase__       )
         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(lowerCamelCase__			,						size=(size['''height'''], size['''width'''])			,						data_format=lowerCamelCase__			,						**lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[Any]			,						lowerCamelCase__	:    np.ndarray			,						lowerCamelCase__	:    Union[int, float]			,						lowerCamelCase__	:    Optional[Union[str, ChannelDimension]] = None			,						**lowerCamelCase__	:    int			,						) ->			Tuple:
         """simple docstring"""





         return rescale(lowerCamelCase__			,						scale=lowerCamelCase__			,						data_format=lowerCamelCase__			,						**lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Tuple			,						lowerCamelCase__	:    np.ndarray			,						lowerCamelCase__	:    Optional[Union[str, ChannelDimension]] = None       ) ->			np.ndarray:
         """simple docstring"""





         return flip_channel_order(lowerCamelCase__			,						data_format=lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[str]			,						lowerCamelCase__	:    ImageInput			,						lowerCamelCase__	:    bool = None			,						lowerCamelCase__	:    Dict[str, int] = None			,						lowerCamelCase__	:    PILImageResampling = None			,						lowerCamelCase__	:    bool = None			,						lowerCamelCase__	:    float = None			,						lowerCamelCase__	:    bool = None			,						lowerCamelCase__	:    Dict[str, int] = None			,						lowerCamelCase__	:    bool = None			,						lowerCamelCase__	:    Optional[Union[str, TensorType]] = None			,						lowerCamelCase__	:    ChannelDimension = ChannelDimension.FIRST			,						**lowerCamelCase__	:    Any			,						) ->			PIL.Image.Image:
         """simple docstring"""





         A_							       =		do_resize if do_resize is not None else self.do_resize
         A_							       =		resample if resample is not None else self.resample
         A_							       =		do_rescale if do_rescale is not None else self.do_rescale
         A_							       =		rescale_factor if rescale_factor is not None else self.rescale_factor
         A_							       =		do_center_crop if do_center_crop is not None else self.do_center_crop
         A_							       =		(
             do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
         )

         A_							       =		size if size is not None else self.size
         A_							       =		get_size_dict(lowerCamelCase__			,						default_to_square=lowerCamelCase__       )
         A_							       =		crop_size if crop_size is not None else self.crop_size
         A_							       =		get_size_dict(lowerCamelCase__			,						param_name='''crop_size'''       )

         A_							       =		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_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.
         A_							       =		[to_numpy_array(lowerCamelCase__       ) for image in images]

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

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

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

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

         A_							       =		[to_channel_dimension_format(lowerCamelCase__			,						lowerCamelCase__       ) for image in images]

         A_							       =		{'''pixel_values''': images}
         return BatchFeature(data=lowerCamelCase__			,						tensor_type=lowerCamelCase__       )





   def     UpperCamelCase					(				self	:    Union[str, Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    List[Tuple] = None       ) ->			str:
         """simple docstring"""





         A_							       =		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__       ):
                     A_							       =		target_sizes.numpy()

               A_							       =		[]

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

         return semantic_segmentation








import logging
import os
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


__lowercase				      =						{
    """debug""": logging.DEBUG,
    """info""": logging.INFO,
    """warning""": logging.WARNING,
    """error""": logging.ERROR,
    """critical""": logging.CRITICAL,
}

__lowercase				      =						logging.WARNING







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		os.getenv('''DATASETS_VERBOSITY'''		,				SCREAMING_SNAKE_CASE   )
      if env_level_str:
            if env_level_str in log_levels:
                  return log_levels[env_level_str]
            else:
                  logging.getLogger().warning(
                      f"Unknown option DATASETS_VERBOSITY={env_level_str}, "
                      f"has to be one of: { ', '.join(log_levels.keys()   ) }"   )
      return _default_log_level







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return __name__.split('''.'''   )[0]







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return logging.getLogger(_get_library_name()   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		_get_library_root_logger()
      library_root_logger.setLevel(_get_default_logging_level()   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		_get_library_root_logger()
      library_root_logger.setLevel(logging.NOTSET   )







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE = None   ):
      '''simple docstring'''







      if name is None:
            A_							       =		_get_library_name()
      return logging.getLogger(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return _get_library_root_logger().getEffectiveLevel()







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      _get_library_root_logger().setLevel(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return set_verbosity(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return set_verbosity(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return set_verbosity(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      return set_verbosity(SCREAMING_SNAKE_CASE   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		False







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		True


# Configure the library root logger at the module level (singleton-like)
_configure_library_root_logger()

class    _lowercase				:

   def __init__(				self	:    Optional[int]			,						*lowerCamelCase__	:    int			,						**lowerCamelCase__	:    Tuple       ) ->			Dict:  # pylint: disable=unused-argument
         """simple docstring"""





         A_							       =		args[0] if args else None

   def __iter__(				self	:    Optional[int]       ) ->			List[str]:
         """simple docstring"""





         return iter(self._iterator       )

   def __getattr__(				self	:    int			,						lowerCamelCase__	:    List[str]       ) ->			List[str]:
         """simple docstring"""





         def empty_fn(*lowerCamelCase__	:    Optional[Any]			,						**lowerCamelCase__	:    str       ):  # pylint: disable=unused-argument
               return

         return empty_fn

   def __enter__(				self	:    Tuple       ) ->			Tuple:
         """simple docstring"""





         return self





   def __exit__(				self	:    Tuple			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    Optional[Any]       ) ->			Optional[int]:
         """simple docstring"""





         return



__lowercase				      =						True

class    _lowercase				:

   def __call__(				self	:    Optional[int]			,						*lowerCamelCase__	:    Optional[int]			,						lowerCamelCase__	:    List[str]=False			,						**lowerCamelCase__	:    Optional[Any]       ) ->			Optional[Any]:
         """simple docstring"""





         if _tqdm_active and not disable:
               return tqdm_lib.tqdm(*lowerCamelCase__			,						**lowerCamelCase__       )
         else:
               return EmptyTqdm(*lowerCamelCase__			,						**lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Optional[Any]			,						*lowerCamelCase__	:    Any			,						**lowerCamelCase__	:    int       ) ->			str:
         """simple docstring"""





         A_							       =		None
         if _tqdm_active:
               return tqdm_lib.tqdm.set_lock(*lowerCamelCase__			,						**lowerCamelCase__       )





   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			int:
         """simple docstring"""





         if _tqdm_active:
               return tqdm_lib.tqdm.get_lock()



__lowercase				      =						_tqdm_cls()







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      global _tqdm_active
      return bool(_tqdm_active   )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      global _tqdm_active
      A_							       =		True







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      global _tqdm_active
      A_							       =		False





