
"""simple docstring"""


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

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


_lowercase							   =				threading.Lock()
_lowercase							   =				None

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

_lowercase							   =				logging.WARNING

_lowercase							   =				True






def       _snake_case				(		):
	A						   =   os.getenv('TRANSFORMERS_VERBOSITY'	,      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 TRANSFORMERS_VERBOSITY={env_level_str}, '
			    F'has to be one of: { ", ".join(log_levels.keys()     ) }'     )
	return _default_log_level






def       _snake_case				(		):
	return __name__.split('.'     )[0]






def       _snake_case				(		):
	return logging.getLogger(_get_library_name()     )






def       _snake_case				(		):
	global _default_handler

	with _lock:
		if _default_handler:
			# This library has already configured the library root logger.
			return
		A						   =   logging.StreamHandler()  # Set sys.stderr as stream.
		A						   =   sys.stderr.flush

		# Apply our default configuration to the library root logger.
		A						   =   _get_library_root_logger()
		library_root_logger.addHandler(_default_handler     )
		library_root_logger.setLevel(_get_default_logging_level()     )
		A						   =   False






def       _snake_case				(		):
	global _default_handler

	with _lock:
		if not _default_handler:
			return

		A						   =   _get_library_root_logger()
		library_root_logger.removeHandler(_default_handler     )
		library_root_logger.setLevel(logging.NOTSET     )
		A						   =   None






def       _snake_case				(		):
	return log_levels






def       _snake_case				(		snake_case__   :     Optional[str] = None     ):

	if name is None:
		A						   =   _get_library_name()

	_configure_library_root_logger()
	return logging.getLogger(snake_case__     )






def       _snake_case				(		):
	_configure_library_root_logger()
	return _get_library_root_logger().getEffectiveLevel()






def       _snake_case				(		snake_case__   :     int     ):
	_configure_library_root_logger()
	_get_library_root_logger().setLevel(snake_case__     )






def       _snake_case				(		):
	return set_verbosity(snake_case__     )






def       _snake_case				(		):
	return set_verbosity(snake_case__     )






def       _snake_case				(		):
	return set_verbosity(snake_case__     )






def       _snake_case				(		):
	return set_verbosity(snake_case__     )






def       _snake_case				(		):
	_configure_library_root_logger()

	assert _default_handler is not None
	_get_library_root_logger().removeHandler(_default_handler     )






def       _snake_case				(		):
	_configure_library_root_logger()

	assert _default_handler is not None
	_get_library_root_logger().addHandler(_default_handler     )






def       _snake_case				(		snake_case__   :     logging.Handler     ):
	_configure_library_root_logger()

	assert handler is not None
	_get_library_root_logger().addHandler(snake_case__     )






def       _snake_case				(		snake_case__   :     logging.Handler     ):
	_configure_library_root_logger()

	assert handler is not None and handler not in _get_library_root_logger().handlers
	_get_library_root_logger().removeHandler(snake_case__     )






def       _snake_case				(		):
	_configure_library_root_logger()
	A						   =   False






def       _snake_case				(		):
	_configure_library_root_logger()
	A						   =   True






def       _snake_case				(		):
	A						   =   _get_library_root_logger().handlers

	for handler in handlers:
		A						   =   logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'     )
		handler.setFormatter(snake_case__     )






def       _snake_case				(		):
	A						   =   _get_library_root_logger().handlers

	for handler in handlers:
		handler.setFormatter(snake_case__     )






def       _snake_case				(		self   :     str	,      *snake_case__   :     int	,      **snake_case__   :     Tuple     ):
	A						   =   os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS'	,      snake_case__     )
	if no_advisory_warnings:
		return
	self.warning(*snake_case__	,      **snake_case__     )


_lowercase							   =				warning_advice






@functools.lru_cache(snake_case__     )
def       _snake_case				(		self   :     Optional[Any]	,      *snake_case__   :     List[Any]	,      **snake_case__   :     Union[str, Any]     ):
	self.warning(*snake_case__	,      **snake_case__     )


_lowercase							   =				warning_once







class 				lowerCAmelCase_				:



						'''simple docstring'''


						def __init__( self     :      str  ,*A_     :      List[str]  ,**A_     :      Union[str, Any]      )     ->   Dict:  # pylint: disable=unused-argument
							A						   =   args[0] if args else None


						def __iter__( self     :      List[Any]      )     ->   Union[str, Any]:
							return iter(self._iterator      )


						def __getattr__( self     :      Dict  ,A_     :      Dict      )     ->   str:

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

							return empty_fn


						def __enter__( self     :      int      )     ->   Union[str, Any]:
							return self




						def __exit__( self     :      int  ,A_     :      List[str]  ,A_     :      Optional[int]  ,A_     :      Dict      )     ->   Tuple:
							return







class 				lowerCAmelCase_				:



						'''simple docstring'''


						def __call__( self     :      Optional[int]  ,*A_     :      Any  ,**A_     :      Dict      )     ->   List[str]:
							if _tqdm_active:
								return tqdm_lib.tqdm(*A_  ,**A_      )
							else:
								return EmptyTqdm(*A_  ,**A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,*A_     :      Optional[int]  ,**A_     :      Tuple      )     ->   Any:
							A						   =   None
							if _tqdm_active:
								return tqdm_lib.tqdm.set_lock(*A_  ,**A_      )




						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict      )     ->   List[Any]:
							if _tqdm_active:
								return tqdm_lib.tqdm.get_lock()

_lowercase							   =				_tqdm_cls()






def       _snake_case				(		):
	global _tqdm_active
	return bool(_tqdm_active     )






def       _snake_case				(		):
	global _tqdm_active
	A						   =   True
	hf_hub_utils.enable_progress_bars()






def       _snake_case				(		):
	global _tqdm_active
	A						   =   False
	hf_hub_utils.disable_progress_bars()

"""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


_lowercase							   =				logging.get_logger(__name__)







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Dict      =    ['''pixel_values''']


						def __init__( self     :      Optional[Any]  ,A_     :      bool = True  ,A_     :      Optional[Dict[str, int]] = None  ,A_     :      PILImageResampling = PILImageResampling.BILINEAR  ,A_     :      bool = True  ,A_     :      Dict[str, int] = None  ,A_     :      bool = True  ,A_     :      Union[int, float] = 1 / 255  ,A_     :      bool = True  ,A_     :      Optional[Union[float, List[float]]] = None  ,A_     :      Optional[Union[float, List[float]]] = None  ,**A_     :      Optional[Any]  ,)     ->   None:
							super().__init__(**A_      )
							A						   =   size if size is not None else {'shortest_edge': 256}
							A						   =   get_size_dict(A_  ,default_to_square=A_      )
							A						   =   crop_size if crop_size is not None else {'height': 224, 'width': 224}
							A						   =   get_size_dict(A_  ,param_name='crop_size'      )
							A						   =   do_resize
							A						   =   size
							A						   =   resample
							A						   =   do_center_crop
							A						   =   crop_size
							A						   =   do_rescale
							A						   =   rescale_factor
							A						   =   do_normalize
							A						   =   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
							A						   =   image_std if image_std is not None else IMAGENET_STANDARD_STD


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]  ,A_     :      np.ndarray  ,A_     :      Dict[str, int]  ,A_     :      PILImageResampling = PILImageResampling.BICUBIC  ,A_     :      Optional[Union[str, ChannelDimension]] = None  ,**A_     :      int  ,)     ->   np.ndarray:
							A						   =   get_size_dict(A_  ,default_to_square=A_      )
							if "shortest_edge" not in size:
								raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'      )
							A						   =   get_resize_output_image_size(A_  ,size=size['shortest_edge']  ,default_to_square=A_      )
							return resize(A_  ,size=A_  ,resample=A_  ,data_format=A_  ,**A_      )


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


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


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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      ImageInput  ,A_     :      Optional[bool] = None  ,A_     :      Dict[str, int] = None  ,A_     :      PILImageResampling = None  ,A_     :      bool = None  ,A_     :      Dict[str, int] = None  ,A_     :      Optional[bool] = None  ,A_     :      Optional[float] = None  ,A_     :      Optional[bool] = None  ,A_     :      Optional[Union[float, List[float]]] = None  ,A_     :      Optional[Union[float, List[float]]] = None  ,A_     :      Optional[Union[str, TensorType]] = None  ,A_     :      Union[str, ChannelDimension] = ChannelDimension.FIRST  ,**A_     :      Tuple  ,)     ->   List[Any]:
							A						   =   do_resize if do_resize is not None else self.do_resize
							A						   =   size if size is not None else self.size
							A						   =   get_size_dict(A_  ,default_to_square=A_      )
							A						   =   resample if resample is not None else self.resample
							A						   =   do_center_crop if do_center_crop is not None else self.do_center_crop
							A						   =   crop_size if crop_size is not None else self.crop_size
							A						   =   get_size_dict(A_  ,param_name='crop_size'      )
							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_normalize if do_normalize is not None else self.do_normalize
							A						   =   image_mean if image_mean is not None else self.image_mean
							A						   =   image_std if image_std is not None else self.image_std

							A						   =   make_list_of_images(A_      )

							if not valid_images(A_      ):
								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.
							A						   =   [to_numpy_array(A_      ) for image in images]

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

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

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

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

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

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




						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      Union[str, Any]  ,A_     :      List[Tuple] = None      )     ->   str:
							A						   =   outputs.logits

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

								if is_torch_tensor(A_      ):
									A						   =   target_sizes.numpy()

								A						   =   []

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

							return semantic_segmentation