

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


a					:Optional[Any]    = logging.get_logger(__name__)




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)       ->				Tuple[int, int]:
      def constraint_to_multiple_of(__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase=0  ,					__lowerCAmelCase=None							):
            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	round(val / multiple							) * multiple

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

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

            return x

      SCREAMING_SNAKE_CASE__   :      List[str]      		=	(output_size, output_size) if isinstance(__lowerCAmelCase  ,					__lowerCAmelCase							) else output_size

      SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      int      		=	get_image_size(__lowerCAmelCase							)
      SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	output_size

      # determine new height and width
      SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	output_height / input_height
      SCREAMING_SNAKE_CASE__   :      str      		=	output_width / input_width

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

      SCREAMING_SNAKE_CASE__   :      Tuple      		=	constraint_to_multiple_of(scale_height * input_height  ,					multiple=__lowerCAmelCase							)
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	constraint_to_multiple_of(scale_width * input_width  ,					multiple=__lowerCAmelCase							)

      return (new_height, new_width)



class      __a							(UpperCamelCase_):






     '''simple docstring'''
     _SCREAMING_SNAKE_CASE						:Union[str, Any]       = ["""pixel_values"""]

     def __init__(						self	,    _a = True	,    _a = None	,    _a = PILImageResampling.BILINEAR	,    _a = False	,    _a = 1	,    _a = True	,    _a = 1 / 255	,    _a = True	,    _a = None	,    _a = None	,    **_a	,    )  ->      None:


           """simple docstring"""


           super().__init__(**_a  )
           SCREAMING_SNAKE_CASE__   :      int      		=	size if size is not None else {"""height""": 384, """width""": 384}
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	get_size_dict(_a  )
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	do_resize
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	size
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	keep_aspect_ratio
           SCREAMING_SNAKE_CASE__   :      int      		=	ensure_multiple_of
           SCREAMING_SNAKE_CASE__   :      str      		=	resample
           SCREAMING_SNAKE_CASE__   :      str      		=	do_rescale
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	rescale_factor
           SCREAMING_SNAKE_CASE__   :      Any      		=	do_normalize
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
           SCREAMING_SNAKE_CASE__   :      int      		=	image_std if image_std is not None else IMAGENET_STANDARD_STD

     def 					_a			(						self	,    _a	,    _a	,    _a = False	,    _a = 1	,    _a = PILImageResampling.BICUBIC	,    _a = None	,    **_a	,    )  ->      np.ndarray:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	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()}'''  )
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	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 					_a			(						self	,    _a	,    _a	,    _a = None	,    **_a	,    )  ->      int:


           """simple docstring"""


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

     def 					_a			(						self	,    _a	,    _a	,    _a	,    _a = None	,    **_a	,    )  ->      np.ndarray:


           """simple docstring"""


           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	,    )  ->      PIL.Image.Image:


           """simple docstring"""


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

           SCREAMING_SNAKE_CASE__   :      Tuple      		=	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.
           SCREAMING_SNAKE_CASE__   :      str      		=	[to_numpy_array(_a  ) for image in images]

           if do_resize:
                 SCREAMING_SNAKE_CASE__   :      List[Any]      		=	[self.resize(image=_a	,    size=_a	,    resample=_a  ) for image in images]

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

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

           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	[to_channel_dimension_format(_a	,    _a  ) for image in images]

           SCREAMING_SNAKE_CASE__   :      Any      		=	{"""pixel_values""": images}
           return BatchFeature(data=_a	,    tensor_type=_a  )





     def 					_a			(						self	,    _a	,    _a = None  )  ->      Tuple:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      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  ):
                       SCREAMING_SNAKE_CASE__   :      List[Any]      		=	target_sizes.numpy()

                 SCREAMING_SNAKE_CASE__   :      Tuple      		=	[]

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

           return semantic_segmentation







"""simple docstring"""


from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


a					:List[Any]    = logging.get_logger(__name__)

a					:Optional[int]    = {
    "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json",
}

class      __a							(UpperCamelCase_   ,	UpperCamelCase_):






     '''simple docstring'''
     _SCREAMING_SNAKE_CASE						:Any       = """focalnet"""

     def __init__(						self	,    _a=224	,    _a=4	,    _a=3	,    _a=96	,    _a=False	,    _a=[192, 384, 768, 768]	,    _a=[2, 2, 6, 2]	,    _a=[2, 2, 2, 2]	,    _a=[3, 3, 3, 3]	,    _a="gelu"	,    _a=4.0	,    _a=0.0	,    _a=0.1	,    _a=False	,    _a=1E-4	,    _a=False	,    _a=False	,    _a=False	,    _a=0.02	,    _a=1E-5	,    _a=32	,    _a=None	,    _a=None	,    **_a	,    )  ->      Optional[Any]:


           """simple docstring"""


           super().__init__(**_a  )

           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	image_size
           SCREAMING_SNAKE_CASE__   :      str      		=	patch_size
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	num_channels
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	embed_dim
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	use_conv_embed
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	hidden_sizes
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	depths
           SCREAMING_SNAKE_CASE__   :      Any      		=	focal_levels
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	focal_windows
           SCREAMING_SNAKE_CASE__   :      Any      		=	hidden_act
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	mlp_ratio
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	hidden_dropout_prob
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	drop_path_rate
           SCREAMING_SNAKE_CASE__   :      str      		=	use_layerscale
           SCREAMING_SNAKE_CASE__   :      int      		=	layerscale_value
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	use_post_layernorm
           SCREAMING_SNAKE_CASE__   :      Any      		=	use_post_layernorm_in_modulation
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	normalize_modulator
           SCREAMING_SNAKE_CASE__   :      str      		=	initializer_range
           SCREAMING_SNAKE_CASE__   :      Any      		=	layer_norm_eps
           SCREAMING_SNAKE_CASE__   :      Any      		=	encoder_stride
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	["""stem"""] + [f'''stage{idx}''' for idx in range(1	,    len(self.depths  ) + 1  )]
           SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      Dict      		=	get_aligned_output_features_output_indices(
               out_features=_a	,    out_indices=_a	,    stage_names=self.stage_names  )




