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


_a				:		Any	   =       logging.get_logger(__name__)
class 						__A							(			SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:      Any		 =		["pixel_values"]






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






     def    __A  (		self    ,					a__    ,					a__    ,					a__ = PILImageResampling.BICUBIC    ,					a__ = None    ,					**a__    ,					):
       _lowerCAmelCase						:	Optional[int]        =					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()}"  )
       _lowerCAmelCase						:	List[str]        =					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    __A  (		self    ,					a__    ,					a__    ,					a__ = None    ,					**a__    ,					):
       _lowerCAmelCase						:	Tuple        =					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    __A  (		self    ,					a__    ,					a__    ,					a__ = None    ,					**a__  ):
       return rescale(a__    ,					scale=a__    ,					data_format=a__    ,					**a__  )






     def    __A  (		self    ,					a__    ,					a__    ,					a__    ,					a__ = None    ,					**a__    ,					):
       return normalize(a__    ,					mean=a__    ,					std=a__    ,					data_format=a__    ,					**a__  )






     def    __A  (		self    ,					a__    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = None    ,					a__ = ChannelDimension.FIRST    ,					**a__    ,					):
       _lowerCAmelCase						:	Any        =					do_resize if do_resize is not None else self.do_resize
       _lowerCAmelCase						:	Optional[Any]        =					size if size is not None else self.size
       _lowerCAmelCase						:	Optional[int]        =					get_size_dict(a__    ,					default_to_square=a__  )
       _lowerCAmelCase						:	Dict        =					resample if resample is not None else self.resample
       _lowerCAmelCase						:	List[str]        =					do_center_crop if do_center_crop is not None else self.do_center_crop
       _lowerCAmelCase						:	Tuple        =					crop_size if crop_size is not None else self.crop_size
       _lowerCAmelCase						:	List[Any]        =					get_size_dict(a__    ,					param_name="""crop_size"""  )
       _lowerCAmelCase						:	str        =					do_rescale if do_rescale is not None else self.do_rescale
       _lowerCAmelCase						:	Union[str, Any]        =					rescale_factor if rescale_factor is not None else self.rescale_factor
       _lowerCAmelCase						:	Dict        =					do_normalize if do_normalize is not None else self.do_normalize
       _lowerCAmelCase						:	Union[str, Any]        =					image_mean if image_mean is not None else self.image_mean
       _lowerCAmelCase						:	Union[str, Any]        =					image_std if image_std is not None else self.image_std

       _lowerCAmelCase						:	Optional[int]        =					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.
       _lowerCAmelCase						:	List[str]        =					[to_numpy_array(a__  ) for image in images]

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

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

       if do_rescale:
         _lowerCAmelCase						:	str        =					[self.rescale(image=a__    ,					scale=a__  ) for image in images]

       if do_normalize:
         _lowerCAmelCase						:	int        =					[self.normalize(image=a__    ,					mean=a__    ,					std=a__  ) for image in images]

       _lowerCAmelCase						:	Dict        =					[to_channel_dimension_format(a__    ,					a__  ) for image in images]

       _lowerCAmelCase						:	Union[str, Any]        =					{"""pixel_values""": images}
       return BatchFeature(data=a__    ,					tensor_type=a__  )






     def    __A  (		self    ,					a__    ,					a__ = None  ):
       _lowerCAmelCase						:	Optional[Any]        =					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__  ):
           _lowerCAmelCase						:	str        =					target_sizes.numpy()

         _lowerCAmelCase						:	str        =					[]

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

       return semantic_segmentation





"""simple docstring"""




import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


_a				:		List[Any]	   =       logging.get_logger(__name__)
class 						__A							:
     _UpperCamelCase							:      str		 =		None







@experimental
def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	List[Any]      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Optional[int]     )	->				List[Any]:
  if ParallelBackendConfig.backend_name is None:
    return _map_with_multiprocessing_pool(
        _lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase     )

  return _map_with_joblib(_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase      ,_lowerCamelCase     )





def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	Optional[Any]      ,_lowerCamelCase						:	str      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	Optional[int]      ,_lowerCamelCase						:	Tuple     )	->				Union[str, Any]:
  _lowerCAmelCase						:	int        =					num_proc if num_proc <= len(_lowerCamelCase     ) else len(_lowerCamelCase     )
  _lowerCAmelCase						:	Union[str, Any]        =					[]  # We organize the splits ourselve (contiguous splits)
  for index in range(_lowerCamelCase     ):
    _lowerCAmelCase						:	List[str]        =					len(_lowerCamelCase     ) // num_proc
    _lowerCAmelCase						:	str        =					len(_lowerCamelCase     ) % num_proc
    _lowerCAmelCase						:	Tuple        =					div * index + min(_lowerCamelCase      ,_lowerCamelCase     )
    _lowerCAmelCase						:	int        =					start + div + (1 if index < mod else 0)
    split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)     )

  if len(_lowerCamelCase     ) != sum(len(i[1]     ) for i in split_kwds     ):
    raise ValueError(
        f"Error dividing inputs iterable among processes. "
        f"Total number of objects {len(_lowerCamelCase     )}, "
        f"length: {sum(len(i[1]     ) for i in split_kwds     )}"     )

  logger.info(
      f"Spawning {num_proc} processes for {len(_lowerCamelCase     )} objects in slices of {[len(i[1]     ) for i in split_kwds]}"     )
  _lowerCAmelCase      ,     _lowerCAmelCase						:	List[str]        =					None, None
  if not disable_tqdm:
    _lowerCAmelCase      ,     _lowerCAmelCase						:	Optional[Any]        =					(RLock(),), tqdm.set_lock
  with Pool(_lowerCamelCase      ,initargs=_lowerCamelCase      ,initializer=_lowerCamelCase     ) as pool:
    _lowerCAmelCase						:	str        =					pool.map(_lowerCamelCase      ,_lowerCamelCase     )
  logger.info(f"Finished {num_proc} processes"     )
  _lowerCAmelCase						:	int        =					[obj for proc_res in mapped for obj in proc_res]
  logger.info(f"Unpacked {len(_lowerCamelCase     )} objects"     )

  return mapped





def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	List[str]      ,_lowerCamelCase						:	Union[str, Any]      ,_lowerCamelCase						:	int      ,_lowerCamelCase						:	Dict      ,_lowerCamelCase						:	Tuple      ,_lowerCamelCase						:	Any      ,_lowerCamelCase						:	str     )	->				Optional[Any]:
  # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib,
  # and it requires monkey-patching joblib internal classes which is subject to change
  import joblib

  with joblib.parallel_backend(ParallelBackendConfig.backend_name      ,n_jobs=_lowerCamelCase     ):
    return joblib.Parallel()(
        joblib.delayed(_lowerCamelCase     )((function, obj, types, None, True, None)     ) for obj in iterable     )






@experimental
@contextlib.contextmanager
def 							SCREAMING_SNAKE_CASE					(      _lowerCamelCase						:	str     )	->				Any:
  _lowerCAmelCase						:	List[Any]        =					backend_name

  if backend_name == "spark":
    from joblibspark import register_spark

    register_spark()

    # TODO: call create_cache_and_write_probe if "download" in steps
    # TODO: raise NotImplementedError when Dataset.map etc is called

  try:
    yield
  finally:
    _lowerCAmelCase						:	Optional[Any]        =					None




