






def 			A__							(      _a  :					Optional[int]		,  _a  :					Tuple	):





 '''simple docstring'''







 snake_case__  :    str							       =[1]
 for i in range(2		,  _a	):
  factorials.append(factorials[-1] * i	)
 assert 0 <= k < factorials[-1] * n, "k out of bounds"

 snake_case__  :    Tuple							       =[]
 snake_case__  :    Optional[Any]							       =list(range(_a	)	)

 # Find permutation
 while factorials:
  snake_case__  :    Any							       =factorials.pop()
  snake_case__       ,   snake_case__  :    Dict							       =divmod(_a		,  _a	)
  permutation.append(elements[number]	)
  elements.remove(elements[number]	)
 permutation.append(elements[0]	)

 return permutation


if __name__ == "__main__":
       import doctest

       doctest.testmod()













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


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







def 			A__							(      _a  :					np.ndarray		,  _a  :					Union[int, Iterable[int]]		,  _a  :					bool		,  _a  :					int	):





 '''simple docstring'''







 def constraint_to_multiple_of(_a  :					Union[str, Any]		,  _a  :					List[str]		,  _a  :					str=0		,  _a  :					Any=None	):
  snake_case__  :    Any							       =round(val / multiple	) * multiple

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

  if x < min_val:
   snake_case__  :    Dict							       =math.ceil(val / multiple	) * multiple

  return x

 snake_case__  :    str							       =(output_size, output_size) if isinstance(_a		,  _a	) else output_size

 snake_case__       ,   snake_case__  :    Dict							       =get_image_size(_a	)
 snake_case__       ,   snake_case__  :    int							       =output_size

 # determine new height and width
 snake_case__  :    Tuple							       =output_height / input_height
 snake_case__  :    Optional[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__  :    Any							       =scale_height

 snake_case__  :    Optional[int]							       =constraint_to_multiple_of(scale_height * input_height		,  multiple=_a	)
 snake_case__  :    str							       =constraint_to_multiple_of(scale_width * input_width		,  multiple=_a	)

 return (new_height, new_width)







class  _lowercase   (   _A						):
      _a							:						List[Any]										=							['pixel_values']
      def __init__(     self				,			a = True				,			a = None				,			a = PILImageResampling.BILINEAR				,			a = False				,			a = 1				,			a = True				,			a = 1 / 2_5_5				,			a = True				,			a = None				,			a = None				,			**a				,			):
       super().__init__(**a   )
       snake_case__  :    Any							       =size if size is not None else {"""height""": 3_8_4, """width""": 3_8_4}
       snake_case__  :    List[Any]							       =get_size_dict(a   )
       snake_case__  :    Tuple							       =do_resize
       snake_case__  :    Tuple							       =size
       snake_case__  :    Any							       =keep_aspect_ratio
       snake_case__  :    List[Any]							       =ensure_multiple_of
       snake_case__  :    Tuple							       =resample
       snake_case__  :    str							       =do_rescale
       snake_case__  :    int							       =rescale_factor
       snake_case__  :    Tuple							       =do_normalize
       snake_case__  :    int							       =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       snake_case__  :    Any							       =image_std if image_std is not None else IMAGENET_STANDARD_STD
      def 						lowercase__					(     self				,			a				,			a				,			a = False				,			a = 1				,			a = PILImageResampling.BICUBIC				,			a = None				,			**a				,			):
       snake_case__  :    Tuple							       =get_size_dict(a   )
       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__  :    Optional[int]							       =get_resize_output_image_size(
           a				,			output_size=(size["""height"""], size["""width"""])				,			keep_aspect_ratio=a				,			multiple=a				,			)
       return resize(a				,			size=a				,			resample=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a = None				,			**a				,			):
       return rescale(a				,			scale=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a = None				,			**a				,			):
       return normalize(a				,			mean=a				,			std=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     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				,			):
       snake_case__  :    Optional[int]							       =do_resize if do_resize is not None else self.do_resize
       snake_case__  :    List[Any]							       =size if size is not None else self.size
       snake_case__  :    int							       =get_size_dict(a   )
       snake_case__  :    Optional[int]							       =keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
       snake_case__  :    int							       =ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
       snake_case__  :    Optional[Any]							       =resample if resample is not None else self.resample
       snake_case__  :    Optional[int]							       =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[Any]							       =do_normalize if do_normalize is not None else self.do_normalize
       snake_case__  :    Tuple							       =image_mean if image_mean is not None else self.image_mean
       snake_case__  :    int							       =image_std if image_std is not None else self.image_std

       snake_case__  :    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 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__  :    int							       =[to_numpy_array(a   ) for image in images]

       if do_resize:
        snake_case__  :    List[str]							       =[self.resize(image=a				,			size=a				,			resample=a   ) for image in images]

       if do_rescale:
        snake_case__  :    List[Any]							       =[self.rescale(image=a				,			scale=a   ) for image in images]

       if do_normalize:
        snake_case__  :    str							       =[self.normalize(image=a				,			mean=a				,			std=a   ) for image in images]

       snake_case__  :    List[Any]							       =[to_channel_dimension_format(a				,			a   ) for image in images]

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



      def 						lowercase__					(     self				,			a				,			a = None   ):
       snake_case__  :    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   ):
         snake_case__  :    Optional[Any]							       =target_sizes.numpy()

        snake_case__  :    Optional[Any]							       =[]

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

       return semantic_segmentation





