


"""simple docstring"""





import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
    import torch

if is_vision_available():
    import PIL


UpperCamelCase_	:				Union[str, Any]										= logging.get_logger(__name__)



def     __lowercase					(    a :				Union[str, Any]       ,		a :				Tuple       ,		a :				Optional[Any]       ,		a :				Any )					->					Dict:
      def constraint_to_multiple_of(a :				Dict       ,		a :				Tuple       ,		a :				str=0       ,		a :				Optional[Any]=None ):
            __snake_case      :    Optional[int]  			=round(val / multiple ) * multiple

            if max_val is not None and x > max_val:
                  __snake_case      :    Optional[int]  			=math.floor(val / multiple ) * multiple

            if x < min_val:
                  __snake_case      :    Union[str, Any]  			=math.ceil(val / multiple ) * multiple

            return x

      __snake_case      :    str  			=(output_size, output_size) if isinstance(__A       ,		__A ) else output_size

      __snake_case      :    Optional[int]  			=get_image_size(__A )
      __snake_case      :    int  			=output_size

      # determine new height and width
      __snake_case      :    Dict  			=output_height / input_height
      __snake_case      :    Union[str, Any]  			=output_width / input_width

      if keep_aspect_ratio:
            # scale as little as possible
            if abs(1 - scale_width ) < abs(1 - scale_height ):
                  # fit width
                  __snake_case      :    Optional[int]  			=scale_width
            else:
                  # fit height
                  __snake_case      :    List[Any]  			=scale_height

      __snake_case      :    str  			=constraint_to_multiple_of(scale_height * input_height       ,		multiple=__A )
      __snake_case      :    Tuple  			=constraint_to_multiple_of(scale_width * input_width       ,		multiple=__A )

      return (new_height, new_width)


class      _lowercase (     __lowerCAmelCase						):
      _a   :     List[str]								=   ['''pixel_values''']


      def __init__(    self				:	int							,   a				:	bool = True							,   a				:	Dict[str, int] = None							,   a				:	PILImageResampling = PILImageResampling.BILINEAR							,   a				:	bool = False							,   a				:	int = 1							,   a				:	bool = True							,   a				:	Union[int, float] = 1 / 2_5_5							,   a				:	bool = True							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[float, List[float]]] = None							,   **a				:	List[str]							,   ):





            """simple docstring"""







            super().__init__(**_UpperCamelCase						)
            __snake_case      :    Dict  			=size if size is not None else {"""height""": 3_8_4, """width""": 3_8_4}
            __snake_case      :    Any  			=get_size_dict(_UpperCamelCase						)
            __snake_case      :    Optional[int]  			=do_resize
            __snake_case      :    Any  			=size
            __snake_case      :    List[Any]  			=keep_aspect_ratio
            __snake_case      :    Optional[Any]  			=ensure_multiple_of
            __snake_case      :    Dict  			=resample
            __snake_case      :    Any  			=do_rescale
            __snake_case      :    Any  			=rescale_factor
            __snake_case      :    List[Any]  			=do_normalize
            __snake_case      :    str  			=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
            __snake_case      :    List[Any]  			=image_std if image_std is not None else IMAGENET_STANDARD_STD


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	np.ndarray							,   a				:	Dict[str, int]							,   a				:	bool = False							,   a				:	int = 1							,   a				:	PILImageResampling = PILImageResampling.BICUBIC							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	List[str]							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=get_size_dict(_UpperCamelCase						)
            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()}'''						)
            __snake_case      :    List[Any]  			=get_resize_output_image_size(
                _UpperCamelCase							,   output_size=(size['''height'''], size['''width'''])							,   keep_aspect_ratio=_UpperCamelCase							,   multiple=_UpperCamelCase							,   )
            return resize(_UpperCamelCase							,   size=_UpperCamelCase							,   resample=_UpperCamelCase							,   data_format=_UpperCamelCase							,   **_UpperCamelCase						)


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	np.ndarray							,   a				:	Union[int, float]							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	Optional[int]							,   ):





            """simple docstring"""







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


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	np.ndarray							,   a				:	Union[float, List[float]]							,   a				:	Union[float, List[float]]							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	int							,   ):





            """simple docstring"""







            return normalize(_UpperCamelCase							,   mean=_UpperCamelCase							,   std=_UpperCamelCase							,   data_format=_UpperCamelCase							,   **_UpperCamelCase						)


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	ImageInput							,   a				:	bool = None							,   a				:	int = None							,   a				:	bool = None							,   a				:	int = None							,   a				:	PILImageResampling = None							,   a				:	bool = None							,   a				:	float = None							,   a				:	bool = None							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[str, TensorType]] = None							,   a				:	ChannelDimension = ChannelDimension.FIRST							,   **a				:	Dict							,   ):





            """simple docstring"""







            __snake_case      :    Tuple  			=do_resize if do_resize is not None else self.do_resize
            __snake_case      :    Tuple  			=size if size is not None else self.size
            __snake_case      :    Any  			=get_size_dict(_UpperCamelCase						)
            __snake_case      :    List[str]  			=keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
            __snake_case      :    List[str]  			=ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
            __snake_case      :    int  			=resample if resample is not None else self.resample
            __snake_case      :    Tuple  			=do_rescale if do_rescale is not None else self.do_rescale
            __snake_case      :    str  			=rescale_factor if rescale_factor is not None else self.rescale_factor
            __snake_case      :    Optional[int]  			=do_normalize if do_normalize is not None else self.do_normalize
            __snake_case      :    Union[str, Any]  			=image_mean if image_mean is not None else self.image_mean
            __snake_case      :    Union[str, Any]  			=image_std if image_std is not None else self.image_std

            __snake_case      :    str  			=make_list_of_images(_UpperCamelCase						)

            if not valid_images(_UpperCamelCase						):
                  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 or resample is None:
                  raise ValueError('''Size and resample 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_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.
            __snake_case      :    Union[str, Any]  			=[to_numpy_array(_UpperCamelCase						) for image in images]

            if do_resize:
                  __snake_case      :    Union[str, Any]  			=[self.resize(image=_UpperCamelCase							,   size=_UpperCamelCase							,   resample=_UpperCamelCase						) for image in images]

            if do_rescale:
                  __snake_case      :    Any  			=[self.rescale(image=_UpperCamelCase							,   scale=_UpperCamelCase						) for image in images]

            if do_normalize:
                  __snake_case      :    List[str]  			=[self.normalize(image=_UpperCamelCase							,   mean=_UpperCamelCase							,   std=_UpperCamelCase						) for image in images]

            __snake_case      :    int  			=[to_channel_dimension_format(_UpperCamelCase							,   _UpperCamelCase						) for image in images]

            __snake_case      :    str  			={"""pixel_values""": images}
            return BatchFeature(data=_UpperCamelCase							,   tensor_type=_UpperCamelCase						)







      def _UpperCamelCase						(    self				:	Any							,   a				:	Tuple							,   a				:	List[Tuple] = None						):





            """simple docstring"""







            __snake_case      :    Any  			=outputs.logits

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

                  if is_torch_tensor(_UpperCamelCase						):
                        __snake_case      :    Any  			=target_sizes.numpy()

                  __snake_case      :    Optional[Any]  			=[]

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

            return semantic_segmentation










"""simple docstring"""





from __future__ import annotations



def     __lowercase					(    a :				int       ,		a :				int )					->					list[str]:
      if partitions <= 0:
            raise ValueError('''partitions must be a positive number!''' )
      if partitions > number_of_bytes:
            raise ValueError('''partitions can not > number_of_bytes!''' )
      __snake_case      :    List[str]  			=number_of_bytes // partitions
      __snake_case      :    str  			=[]
      for i in range(a ):
            __snake_case      :    Optional[Any]  			=i * bytes_per_partition + 1
            __snake_case      :    Any  			=(
                number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
            )
            allocation_list.append(f'''{start_bytes}-{end_bytes}''' )
      return allocation_list


if __name__ == "__main__":
    import doctest

    doctest.testmod()


