'''simple docstring'''
from collections import defaultdict







class lowerCamelCase							:




  '''simple docstring'''



  def __init__(      self			:       List[Any]  ,							UpperCAmelCase__			:       Optional[Any]  ,							UpperCAmelCase__			:       Union[str, Any]  )				->Tuple:
        UpperCAmelCase_            =  total  # total no of tasks (N)

        # DP table will have a dimension of (2^M)*N
        # initially all values are set to -1
        UpperCAmelCase_            =  [
            [-1 for i in range(total + 1  )] for j in range(2 ** len(UpperCAmelCase__  )  )
        ]

        UpperCAmelCase_            =  defaultdict(UpperCAmelCase__  )  # stores the list of persons for each task

        # final_mask is used to check if all persons are included by setting all bits
        # to 1
        UpperCAmelCase_            =  (1 << len(UpperCAmelCase__  )) - 1






  def  lowerCAmelCase__ (      self			:       Optional[int]  ,							UpperCAmelCase__			:       int  ,							UpperCAmelCase__			:       Tuple  )				->List[Any]:
        # if mask == self.finalmask all persons are distributed tasks, return 1
        if mask == self.final_mask:
              return 1

        # if not everyone gets the task and no more tasks are available, return 0
        if task_no > self.total_tasks:
              return 0

        # if case already considered
        if self.dp[mask][task_no] != -1:
              return self.dp[mask][task_no]

        # Number of ways when we don't this task in the arrangement
        UpperCAmelCase_            =  self.count_ways_until(UpperCAmelCase__  ,							task_no + 1  )

        # now assign the tasks one by one to all possible persons and recursively
        # assign for the remaining tasks.
        if task_no in self.task:
              for p in self.task[task_no]:
                    # if p is already given a task
                    if mask & (1 << p):
                          continue

                    # assign this task to p and change the mask value. And recursively
                    # assign tasks with the new mask value.
                    total_ways_util += self.count_ways_until(mask | (1 << p)  ,							task_no + 1  )

        # save the value.
        UpperCAmelCase_            =  total_ways_util

        return self.dp[mask][task_no]






  def  lowerCAmelCase__ (      self			:       List[str]  ,							UpperCAmelCase__			:       List[Any]  )				->Any:
        # Store the list of persons for each task
        for i in range(len(UpperCAmelCase__  )  ):
              for j in task_performed[i]:
                    self.task[j].append(UpperCAmelCase__  )

        # call the function to fill the DP table, final answer is stored in dp[0][1]
        return self.count_ways_until(0  ,							1  )


if __name__ == "__main__":
      lowercase__  :      int        =					5  # total no of tasks (the value of N)

      # the list of tasks that can be done by M persons.
      lowercase__  :      List[str]        =					[[1, 3, 4], [1, 2, 5], [3, 4]]
      print(
          AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways(
              task_performed
          )
      )






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


lowercase__  :      Optional[int]        =					logging.get_logger(__name__)



def  __lowerCamelCase       (      _UpperCamelCase  :  np.ndarray							,    _UpperCamelCase  :  Union[int, Iterable[int]]							,    _UpperCamelCase  :  bool							,    _UpperCamelCase  :  int					):


      '''simple docstring'''


      def constraint_to_multiple_of(_UpperCamelCase  :  int							,    _UpperCamelCase  :  Tuple							,    _UpperCamelCase  :  Optional[int]=0							,    _UpperCamelCase  :  str=None					):
            UpperCAmelCase_            =  round(val / multiple					) * multiple

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

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

            return x

      UpperCAmelCase_            =  (output_size, output_size) if isinstance(_UpperCamelCase							,    _UpperCamelCase					) else output_size

      UpperCAmelCase_      ,		UpperCAmelCase_            =  get_image_size(_UpperCamelCase					)
      UpperCAmelCase_      ,		UpperCAmelCase_            =  output_size

      # determine new height and width
      UpperCAmelCase_            =  output_height / input_height
      UpperCAmelCase_            =  output_width / input_width

      if keep_aspect_ratio:
            # scale as little as possible
            if abs(1 - scale_width					) < abs(1 - scale_height					):
                  # fit width
                  UpperCAmelCase_            =  scale_width
            else:
                  # fit height
                  UpperCAmelCase_            =  scale_height

      UpperCAmelCase_            =  constraint_to_multiple_of(scale_height * input_height							,    multiple=_UpperCamelCase					)
      UpperCAmelCase_            =  constraint_to_multiple_of(scale_width * input_width							,    multiple=_UpperCamelCase					)

      return (new_height, new_width)







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	['''pixel_values''']






  def __init__(      self			:       Any  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Dict[str, int] = None  ,							UpperCAmelCase__			:       PILImageResampling = PILImageResampling.BILINEAR  ,							UpperCAmelCase__			:       bool = False  ,							UpperCAmelCase__			:       int = 1  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Union[int, float] = 1 / 255  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							**UpperCAmelCase__			:       str  ,							)				->None:
        super().__init__(**UpperCAmelCase__  )
        UpperCAmelCase_            =  size if size is not None else {'''height''': 384, '''width''': 384}
        UpperCAmelCase_            =  get_size_dict(UpperCAmelCase__  )
        UpperCAmelCase_            =  do_resize
        UpperCAmelCase_            =  size
        UpperCAmelCase_            =  keep_aspect_ratio
        UpperCAmelCase_            =  ensure_multiple_of
        UpperCAmelCase_            =  resample
        UpperCAmelCase_            =  do_rescale
        UpperCAmelCase_            =  rescale_factor
        UpperCAmelCase_            =  do_normalize
        UpperCAmelCase_            =  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        UpperCAmelCase_            =  image_std if image_std is not None else IMAGENET_STANDARD_STD






  def  lowerCAmelCase__ (      self			:       Union[str, Any]  ,							UpperCAmelCase__			:       np.ndarray  ,							UpperCAmelCase__			:       Dict[str, int]  ,							UpperCAmelCase__			:       bool = False  ,							UpperCAmelCase__			:       int = 1  ,							UpperCAmelCase__			:       PILImageResampling = PILImageResampling.BICUBIC  ,							UpperCAmelCase__			:       Optional[Union[str, ChannelDimension]] = None  ,							**UpperCAmelCase__			:       List[str]  ,							)				->np.ndarray:
        UpperCAmelCase_            =  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()}"""  )
        UpperCAmelCase_            =  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  lowerCAmelCase__ (      self			:       int  ,							UpperCAmelCase__			:       np.ndarray  ,							UpperCAmelCase__			:       Union[int, float]  ,							UpperCAmelCase__			:       Optional[Union[str, ChannelDimension]] = None  ,							**UpperCAmelCase__			:       Optional[Any]  ,							)				->Any:
        return rescale(UpperCAmelCase__  ,							scale=UpperCAmelCase__  ,							data_format=UpperCAmelCase__  ,							**UpperCAmelCase__  )






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






  def  lowerCAmelCase__ (      self			:       str  ,							UpperCAmelCase__			:       ImageInput  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       int = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       int = None  ,							UpperCAmelCase__			:       PILImageResampling = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       float = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[str, TensorType]] = None  ,							UpperCAmelCase__			:       ChannelDimension = ChannelDimension.FIRST  ,							**UpperCAmelCase__			:       Any  ,							)				->PIL.Image.Image:
        UpperCAmelCase_            =  do_resize if do_resize is not None else self.do_resize
        UpperCAmelCase_            =  size if size is not None else self.size
        UpperCAmelCase_            =  get_size_dict(UpperCAmelCase__  )
        UpperCAmelCase_            =  keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
        UpperCAmelCase_            =  ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
        UpperCAmelCase_            =  resample if resample is not None else self.resample
        UpperCAmelCase_            =  do_rescale if do_rescale is not None else self.do_rescale
        UpperCAmelCase_            =  rescale_factor if rescale_factor is not None else self.rescale_factor
        UpperCAmelCase_            =  do_normalize if do_normalize is not None else self.do_normalize
        UpperCAmelCase_            =  image_mean if image_mean is not None else self.image_mean
        UpperCAmelCase_            =  image_std if image_std is not None else self.image_std

        UpperCAmelCase_            =  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.
        UpperCAmelCase_            =  [to_numpy_array(UpperCAmelCase__  ) for image in images]

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

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

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

        UpperCAmelCase_            =  [to_channel_dimension_format(UpperCAmelCase__  ,							UpperCAmelCase__  ) for image in images]

        UpperCAmelCase_            =  {'''pixel_values''': images}
        return BatchFeature(data=UpperCAmelCase__  ,							tensor_type=UpperCAmelCase__  )






  def  lowerCAmelCase__ (      self			:       List[str]  ,							UpperCAmelCase__			:       List[Any]  ,							UpperCAmelCase__			:       List[Tuple] = None  )				->Optional[Any]:
        UpperCAmelCase_            =  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__  ):
                    UpperCAmelCase_            =  target_sizes.numpy()

              UpperCAmelCase_            =  []

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

        return semantic_segmentation





