






"""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 			_snake_case    (					lowerCamelCase__     :   np.ndarray    ,						lowerCamelCase__     :   Union[int, Iterable[int]]    ,						lowerCamelCase__     :   bool    ,						lowerCamelCase__     :   int  )    ->     Tuple[int, int]:
							def constraint_to_multiple_of(lowerCamelCase__     :   List[str]    ,						lowerCamelCase__     :   Tuple    ,						lowerCamelCase__     :   Union[str, Any]=0    ,						lowerCamelCase__     :   List[Any]=None  ):
														lowerCamelCase_	:							Optional[int]									=round(val / multiple  ) * multiple

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

														if x < min_val:
																					lowerCamelCase_	:							List[str]									=math.ceil(val / multiple  ) * multiple

														return x

							lowerCamelCase_	:							Tuple									=(output_size, output_size) if isinstance(lowercase_    ,						lowercase_  ) else output_size

							lowerCamelCase_							,						lowerCamelCase_	:							Any									=get_image_size(lowercase_  )
							lowerCamelCase_							,						lowerCamelCase_	:							List[str]									=output_size

							# determine new height and width
							lowerCamelCase_	:							Optional[int]									=output_height / input_height
							lowerCamelCase_	:							Optional[int]									=output_width / input_width

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

							lowerCamelCase_	:							Union[str, Any]									=constraint_to_multiple_of(scale_height * input_height    ,						multiple=lowercase_  )
							lowerCamelCase_	:							Union[str, Any]									=constraint_to_multiple_of(scale_width * input_width    ,						multiple=lowercase_  )

							return (new_height, new_width)







class        lowercase__      (							A__       ):
			_UpperCAmelCase		:Optional[int]             =			['pixel_values']


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


			def      UpperCAmelCase__						(				self					:  Optional[Any]       ,	snake_case__					:  Dict       ,	snake_case__					:  Any       ,	snake_case__					:  Any = False       ,	snake_case__					:  Tuple = 1       ,	snake_case__					:  Tuple = PILImageResampling.BICUBIC       ,	snake_case__					:  str = None       ,	**snake_case__					:  Dict       ,	):
										lowerCamelCase_	:							List[Any]									=get_size_dict(lowerCamelCase__ )
										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()}""" )
										lowerCamelCase_	:							Any									=get_resize_output_image_size(
										    lowerCamelCase__       ,	output_size=(size["height"], size["width"])       ,	keep_aspect_ratio=lowerCamelCase__       ,	multiple=lowerCamelCase__       ,	)
										return resize(lowerCamelCase__       ,	size=lowerCamelCase__       ,	resample=lowerCamelCase__       ,	data_format=lowerCamelCase__       ,	**lowerCamelCase__ )


			def      UpperCAmelCase__						(				self					:  Optional[Any]       ,	snake_case__					:  Dict       ,	snake_case__					:  Optional[int]       ,	snake_case__					:  Optional[Any] = None       ,	**snake_case__					:  Any       ,	):
										return rescale(lowerCamelCase__       ,	scale=lowerCamelCase__       ,	data_format=lowerCamelCase__       ,	**lowerCamelCase__ )


			def      UpperCAmelCase__						(				self					:  Optional[int]       ,	snake_case__					:  str       ,	snake_case__					:  List[Any]       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  Tuple = None       ,	**snake_case__					:  Any       ,	):
										return normalize(lowerCamelCase__       ,	mean=lowerCamelCase__       ,	std=lowerCamelCase__       ,	data_format=lowerCamelCase__       ,	**lowerCamelCase__ )


			def      UpperCAmelCase__						(				self					:  Optional[Any]       ,	snake_case__					:  Union[str, Any]       ,	snake_case__					:  Optional[Any] = None       ,	snake_case__					:  Dict = None       ,	snake_case__					:  Any = None       ,	snake_case__					:  List[Any] = None       ,	snake_case__					:  List[Any] = None       ,	snake_case__					:  str = None       ,	snake_case__					:  Optional[Any] = None       ,	snake_case__					:  Tuple = None       ,	snake_case__					:  Optional[Any] = None       ,	snake_case__					:  List[str] = None       ,	snake_case__					:  Dict = None       ,	snake_case__					:  Dict = ChannelDimension.FIRST       ,	**snake_case__					:  Dict       ,	):
										lowerCamelCase_	:							Optional[int]									=do_resize if do_resize is not None else self.do_resize
										lowerCamelCase_	:							Dict									=size if size is not None else self.size
										lowerCamelCase_	:							Dict									=get_size_dict(lowerCamelCase__ )
										lowerCamelCase_	:							Any									=keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
										lowerCamelCase_	:							Optional[Any]									=ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
										lowerCamelCase_	:							Tuple									=resample if resample is not None else self.resample
										lowerCamelCase_	:							str									=do_rescale if do_rescale is not None else self.do_rescale
										lowerCamelCase_	:							Optional[Any]									=rescale_factor if rescale_factor is not None else self.rescale_factor
										lowerCamelCase_	:							List[str]									=do_normalize if do_normalize is not None else self.do_normalize
										lowerCamelCase_	:							int									=image_mean if image_mean is not None else self.image_mean
										lowerCamelCase_	:							List[Any]									=image_std if image_std is not None else self.image_std

										lowerCamelCase_	:							Optional[Any]									=make_list_of_images(lowerCamelCase__ )

										if not valid_images(lowerCamelCase__ ):
																	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.
										lowerCamelCase_	:							Optional[Any]									=[to_numpy_array(lowerCamelCase__ ) for image in images]

										if do_resize:
																	lowerCamelCase_	:							Any									=[self.resize(image=lowerCamelCase__       ,	size=lowerCamelCase__       ,	resample=lowerCamelCase__ ) for image in images]

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

										if do_normalize:
																	lowerCamelCase_	:							Dict									=[self.normalize(image=lowerCamelCase__       ,	mean=lowerCamelCase__       ,	std=lowerCamelCase__ ) for image in images]

										lowerCamelCase_	:							List[Any]									=[to_channel_dimension_format(lowerCamelCase__       ,	lowerCamelCase__ ) for image in images]

										lowerCamelCase_	:							str									={"pixel_values": images}
										return BatchFeature(data=lowerCamelCase__       ,	tensor_type=lowerCamelCase__ )


			def      UpperCAmelCase__						(				self					:  Optional[int]       ,	snake_case__					:  Optional[int]       ,	snake_case__					:  List[Any] = None ):
										lowerCamelCase_	:							List[str]									=outputs.logits

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

																	if is_torch_tensor(lowerCamelCase__ ):
																								lowerCamelCase_	:							Optional[int]									=target_sizes.numpy()

																	lowerCamelCase_	:							List[Any]									=[]

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

										return semantic_segmentation











"""simple docstring"""



from typing import TYPE_CHECKING

from ..utils import _LazyModule


A__	:    List[str]			 = {
    'config': [
        'EXTERNAL_DATA_FORMAT_SIZE_LIMIT',
        'OnnxConfig',
        'OnnxConfigWithPast',
        'OnnxSeq2SeqConfigWithPast',
        'PatchingSpec',
    ],
    'convert': ['export', 'validate_model_outputs'],
    'features': ['FeaturesManager'],
    'utils': ['ParameterFormat', 'compute_serialized_parameters_size'],
}


if TYPE_CHECKING:
						from .config import (
						    EXTERNAL_DATA_FORMAT_SIZE_LIMIT,
						    OnnxConfig,
						    OnnxConfigWithPast,
						    OnnxSeqaSeqConfigWithPast,
						    PatchingSpec,
						)
						from .convert import export, validate_model_outputs
						from .features import FeaturesManager
						from .utils import ParameterFormat, compute_serialized_parameters_size

else:
						import sys

						A__	:    List[str]			 = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



