
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__     :		Optional[int]        = logging.get_logger(__name__)

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						Tuple[int, int]:


  '''simple docstring'''






  def constraint_to_multiple_of(lowercase_			,			lowercase_			,			lowercase_=0			,			lowercase_=None ):
    lowercase__	: Optional[int]     		=   round(val / multiple ) * multiple

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

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

    return x

  lowercase__	: Optional[int]     		=   (output_size, output_size) if isinstance(lowercase_			,			lowercase_ ) else output_size

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

  # determine new height and width
  lowercase__	: Optional[int]     		=   output_height / input_height
  lowercase__	: 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
      lowercase__	: Tuple     		=   scale_width
    else:
      # fit height
      lowercase__	: List[Any]     		=   scale_height

  lowercase__	: Optional[Any]     		=   constraint_to_multiple_of(scale_height * input_height			,			multiple=lowercase_ )
  lowercase__	: List[Any]     		=   constraint_to_multiple_of(scale_width * input_width			,			multiple=lowercase_ )

  return (new_height, new_width)



class    _snake_case (						UpperCAmelCase_				):
 __lowerCAmelCase	:  List[str]	   =      ['pixel_values']


 def __init__(       self       ,	SCREAMING_SNAKE_CASE_ = True       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR       ,	SCREAMING_SNAKE_CASE_ = False       ,	SCREAMING_SNAKE_CASE_ = 1       ,	SCREAMING_SNAKE_CASE_ = True       ,	SCREAMING_SNAKE_CASE_ = 1 / 2_55       ,	SCREAMING_SNAKE_CASE_ = True       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = False       ,	SCREAMING_SNAKE_CASE_ = 1       ,	SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




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

   lowercase__	: List[Any]     		=   make_list_of_images(SCREAMING_SNAKE_CASE_)

   if not valid_images(SCREAMING_SNAKE_CASE_):
     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.
   lowercase__	: Tuple     		=   [to_numpy_array(SCREAMING_SNAKE_CASE_) for image in images]

   if do_resize:
     lowercase__	: str     		=   [self.resize(image=SCREAMING_SNAKE_CASE_       ,	size=SCREAMING_SNAKE_CASE_       ,	resample=SCREAMING_SNAKE_CASE_) for image in images]

   if do_rescale:
     lowercase__	: Dict     		=   [self.rescale(image=SCREAMING_SNAKE_CASE_       ,	scale=SCREAMING_SNAKE_CASE_) for image in images]

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

   lowercase__	: Optional[Any]     		=   [to_channel_dimension_format(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_) for image in images]

   lowercase__	: Dict     		=   {"""pixel_values""": images}
   return BatchFeature(data=SCREAMING_SNAKE_CASE_       ,	tensor_type=SCREAMING_SNAKE_CASE_)



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   outputs.logits

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

     if is_torch_tensor(SCREAMING_SNAKE_CASE_):
       lowercase__	: List[Any]     		=   target_sizes.numpy()

     lowercase__	: List[Any]     		=   []

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

   return semantic_segmentation








# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


lowerCamelCase__     :		Optional[int]        = [
    """EAGER""",
    """AOT_EAGER""",
    """INDUCTOR""",
    """NVFUSER""",
    """AOT_NVFUSER""",
    """AOT_CUDAGRAPHS""",
    """OFI""",
    """FX2TRT""",
    """ONNXRT""",
    """IPEX""",
]

def 		UpperCamelCase						(   lowercase_			,			lowercase_=None			,			lowercase_=None			,			lowercase_=None )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   True
  while ask_again:
    lowercase__	: Tuple     		=   input(lowercase_ )
    try:
      if default is not None and len(lowercase_ ) == 0:
        return default
      return convert_value(lowercase_ ) if convert_value is not None else result
    except Exception:
      if error_message is not None:
        print(lowercase_ )

def 		UpperCamelCase						(   lowercase_			,			lowercase_=[]			,			lowercase_=None			,			lowercase_=0 )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   BulletMenu(lowercase_			,			lowercase_ )
  lowercase__	: Any     		=   menu.run(default_choice=lowercase_ )
  return convert_value(lowercase_ ) if convert_value is not None else result

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: Union[str, Any]     		=   int(lowercase_ )
  return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[str]     		=   int(lowercase_ )
  return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: str     		=   int(lowercase_ )
  return DynamoBackend(DYNAMO_BACKENDS[value] ).value

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  return {"yes": True, "no": False}[value.lower()]



class    _snake_case (						argparse.RawDescriptionHelpFormatter				):


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: int     		=   super()._format_usage(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   usage.replace("""<command> [<args>] """       ,	"""""")
   return usage






