


'''simple docstring'''







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


A__:   Dict    =	logging.get_logger(__name__)







class A__	(						A__				):
      __UpperCamelCase	:  List[Any]     	=							["pixel_values"]






      def __init__(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :bool = True					,						SCREAMING_SNAKE_CASE      :Dict[str, int] = None					,						SCREAMING_SNAKE_CASE      :PILImageResampling = PIL.Image.NEAREST					,						SCREAMING_SNAKE_CASE      :bool = False					,						SCREAMING_SNAKE_CASE      :Dict[str, int] = None					,						SCREAMING_SNAKE_CASE      :Union[int, float] = 1 / 2_5_5					,						SCREAMING_SNAKE_CASE      :bool = False					,						SCREAMING_SNAKE_CASE      :bool = True					,						SCREAMING_SNAKE_CASE      :bool = True					,						SCREAMING_SNAKE_CASE      :Optional[Union[float, List[float]]] = None					,						SCREAMING_SNAKE_CASE      :Optional[Union[float, List[float]]] = None					,						SCREAMING_SNAKE_CASE      :bool = True					,						**SCREAMING_SNAKE_CASE      :Tuple					,						)	-> None:




             '''simple docstring'''
             super().__init__(**__snake_case     )
             _a   :			Any					 =size if size is not None else {'''height''': 3_4_6, '''width''': 3_4_6}
             _a   :			Optional[int]					 =get_size_dict(__snake_case     )
             _a   :			List[Any]					 =crop_size if crop_size is not None else {'''height''': 2_8_9, '''width''': 2_8_9}
             _a   :			str					 =get_size_dict(__snake_case					,						param_name="""crop_size"""     )

             _a   :			int					 =do_resize
             _a   :			Tuple					 =size
             _a   :			int					 =resample
             _a   :			List[str]					 =do_center_crop
             _a   :			str					 =crop_size
             _a   :			List[str]					 =do_rescale
             _a   :			List[Any]					 =rescale_factor
             _a   :			Optional[Any]					 =rescale_offset
             _a   :			int					 =do_normalize
             _a   :			Union[str, Any]					 =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
             _a   :			Any					 =image_std if image_std is not None else IMAGENET_STANDARD_STD
             _a   :			Tuple					 =include_top






      def __UpperCAmelCase	(			self      :Tuple					,						SCREAMING_SNAKE_CASE      :np.ndarray					,						SCREAMING_SNAKE_CASE      :Dict[str, int]					,						SCREAMING_SNAKE_CASE      :PILImageResampling = PIL.Image.NEAREST					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, ChannelDimension]] = None					,						**SCREAMING_SNAKE_CASE      :Union[str, Any]					,						)	-> np.ndarray:




             '''simple docstring'''
             _a   :			Optional[Any]					 =get_size_dict(__snake_case     )
             if "height" not in size or "width" not in size:
                    raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"     )
             return resize(
                 __snake_case					,						size=(size["""height"""], size["""width"""])					,						resample=__snake_case					,						data_format=__snake_case					,						**__snake_case     )






      def __UpperCAmelCase	(			self      :Dict					,						SCREAMING_SNAKE_CASE      :np.ndarray					,						SCREAMING_SNAKE_CASE      :Dict[str, int]					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, ChannelDimension]] = None					,						**SCREAMING_SNAKE_CASE      :Optional[Any]					,						)	-> np.ndarray:




             '''simple docstring'''
             _a   :			Optional[Any]					 =get_size_dict(__snake_case     )
             if "height" not in size or "width" not in size:
                    raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"     )
             return center_crop(__snake_case					,						size=(size["""height"""], size["""width"""])					,						data_format=__snake_case					,						**__snake_case     )






      def __UpperCAmelCase	(			self      :str					,						SCREAMING_SNAKE_CASE      :np.ndarray					,						SCREAMING_SNAKE_CASE      :Union[int, float]					,						SCREAMING_SNAKE_CASE      :bool = True					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, ChannelDimension]] = None					,						**SCREAMING_SNAKE_CASE      :Union[str, Any]					,						)	-> List[str]:




             '''simple docstring'''
             if offset:
                    _a   :			Optional[int]					 =(image - 1_2_7.5) * scale
                    if data_format is not None:
                           _a   :			Tuple					 =to_channel_dimension_format(__snake_case					,						__snake_case     )
                    _a   :			Tuple					 =rescaled_image.astype(np.floataa     )
             else:
                    _a   :			Dict					 =rescale(__snake_case					,						scale=__snake_case					,						data_format=__snake_case					,						**__snake_case     )
             return rescaled_image






      def __UpperCAmelCase	(			self      :Tuple					,						SCREAMING_SNAKE_CASE      :np.ndarray					,						SCREAMING_SNAKE_CASE      :Union[float, List[float]]					,						SCREAMING_SNAKE_CASE      :Union[float, List[float]]					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, ChannelDimension]] = None					,						**SCREAMING_SNAKE_CASE      :int					,						)	-> np.ndarray:




             '''simple docstring'''
             return normalize(__snake_case					,						mean=__snake_case					,						std=__snake_case					,						data_format=__snake_case					,						**__snake_case     )






      def __UpperCAmelCase	(			self      :List[str]					,						SCREAMING_SNAKE_CASE      :ImageInput					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :Dict[str, int] = None					,						SCREAMING_SNAKE_CASE      :Tuple=None					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :Dict[str, int] = None					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :float = None					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :Optional[Union[float, List[float]]] = None					,						SCREAMING_SNAKE_CASE      :Optional[Union[float, List[float]]] = None					,						SCREAMING_SNAKE_CASE      :bool = None					,						SCREAMING_SNAKE_CASE      :Optional[Union[str, TensorType]] = None					,						SCREAMING_SNAKE_CASE      :ChannelDimension = ChannelDimension.FIRST					,						**SCREAMING_SNAKE_CASE      :List[Any]					,						)	-> PIL.Image.Image:




             '''simple docstring'''
             _a   :			Any					 =do_resize if do_resize is not None else self.do_resize
             _a   :			Any					 =resample if resample is not None else self.resample
             _a   :			Union[str, Any]					 =do_center_crop if do_center_crop is not None else self.do_center_crop
             _a   :			List[str]					 =do_rescale if do_rescale is not None else self.do_rescale
             _a   :			str					 =rescale_factor if rescale_factor is not None else self.rescale_factor
             _a   :			Any					 =rescale_offset if rescale_offset is not None else self.rescale_offset
             _a   :			Tuple					 =do_normalize if do_normalize is not None else self.do_normalize
             _a   :			Optional[int]					 =image_mean if image_mean is not None else self.image_mean
             _a   :			str					 =image_std if image_std is not None else self.image_std
             _a   :			Optional[Any]					 =include_top if include_top is not None else self.include_top

             _a   :			Optional[Any]					 =size if size is not None else self.size
             _a   :			Dict					 =get_size_dict(__snake_case     )
             _a   :			Union[str, Any]					 =crop_size if crop_size is not None else self.crop_size
             _a   :			Tuple					 =get_size_dict(__snake_case					,						param_name="""crop_size"""     )

             _a   :			List[Any]					 =make_list_of_images(__snake_case     )

             if not valid_images(__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_center_crop and crop_size is None:
                    raise ValueError("""Crop size must be specified if do_center_crop 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.
             _a   :			Any					 =[to_numpy_array(__snake_case     ) for image in images]

             if do_resize:
                    _a   :			Dict					 =[self.resize(image=__snake_case					,						size=__snake_case					,						resample=__snake_case     ) for image in images]

             if do_center_crop:
                    _a   :			Optional[Any]					 =[self.center_crop(image=__snake_case					,						size=__snake_case     ) for image in images]

             if do_rescale:
                    _a   :			Union[str, Any]					 =[self.rescale(image=__snake_case					,						scale=__snake_case					,						offset=__snake_case     ) for image in images]

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

             if include_top:
                    _a   :			str					 =[self.normalize(image=__snake_case					,						mean=[0, 0, 0]					,						std=__snake_case     ) for image in images]

             _a   :			List[Any]					 =[to_channel_dimension_format(__snake_case					,						__snake_case     ) for image in images]

             _a   :			int					 ={'''pixel_values''': images}
             return BatchFeature(data=__snake_case					,						tensor_type=__snake_case     )






'''simple docstring'''







from typing import Dict, Optional, Tuple

import torch


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor  )  ->      torch.Tensor:
       _a   :			Tuple					 =boundaries[1] - boundaries[0]
       _a   :			Dict					 =boundaries + step / 2
       _a   :			List[Any]					 =torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1  )]   ,dim=0  )
       return bin_centers


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     torch.Tensor   ,)  ->      Tuple[torch.Tensor, torch.Tensor]:
       _a   :			Any					 =_calculate_bin_centers(_UpperCAmelCase  )
       return (
           torch.sum(aligned_distance_error_probs * bin_centers   ,dim=-1  ),
           bin_centers[-1],
       )


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,**_UpperCAmelCase     :     Dict   ,)  ->      Dict[str, torch.Tensor]:
       _a   :			Dict					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			int					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )
       _a ,   _a   :			List[Any]					 =_calculate_expected_aligned_error(
           alignment_confidence_breaks=_UpperCAmelCase   ,aligned_distance_error_probs=_UpperCAmelCase   ,)

       return {
           "aligned_confidence_probs": aligned_confidence_probs,
           "predicted_aligned_error": predicted_aligned_error,
           "max_predicted_aligned_error": max_predicted_aligned_error,
       }


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     Optional[torch.Tensor] = None   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,_UpperCAmelCase     :     float = 1e-8   ,**_UpperCAmelCase     :     Optional[Any]   ,)  ->      torch.Tensor:
       if residue_weights is None:
              _a   :			Dict					 =logits.new_ones(logits.shape[-2]  )

       _a   :			str					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			Optional[int]					 =_calculate_bin_centers(_UpperCAmelCase  )
       torch.sum(_UpperCAmelCase  )
       _a   :			List[str]					 =logits.shape[-2]
       _a   :			List[Any]					 =max(_UpperCAmelCase   ,19  )

       _a   :			Union[str, Any]					 =1.2_4 * (clipped_n - 15) ** (1.0 / 3) - 1.8

       _a   :			Tuple					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )

       _a   :			Dict					 =1.0 / (1 + (bin_centers**2) / (da**2))
       _a   :			int					 =torch.sum(probs * tm_per_bin   ,dim=-1  )

       _a   :			List[Any]					 =residue_weights / (eps + residue_weights.sum())
       _a   :			List[str]					 =torch.sum(predicted_tm_term * normed_residue_mask   ,dim=-1  )

       _a   :			int					 =per_alignment * residue_weights

       _a   :			List[Any]					 =(weighted == torch.max(_UpperCAmelCase  )).nonzero()[0]
       return per_alignment[tuple(_UpperCAmelCase  )]


