
from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    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_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


__lowerCAmelCase					   =       logging.get_logger(__name__)





class     lowerCamelCase      (       __lowerCamelCase					):
	UpperCamelCase_  :					List[str]    		=	['pixel_values']







	def __init__(     self      :List[str]   ,     lowercase      :bool = True   ,     lowercase      :Optional[Dict[str, int]] = None   ,     lowercase      :PILImageResampling = PILImageResampling.BILINEAR   ,     lowercase      :bool = True   ,     lowercase      :Dict[str, int] = None   ,     lowercase      :bool = True   ,     lowercase      :Union[int, float] = 1 / 2_5_5   ,     lowercase      :bool = True   ,     lowercase      :Optional[Union[float, List[float]]] = None   ,     lowercase      :Optional[Union[float, List[float]]] = None   ,     **lowercase      :Union[str, Any]   ,     )		->      None:







				"""simple docstring"""






				super().__init__(**lowercase			)
				SCREAMING_SNAKE_CASE     						= size if size is not None else {'''shortest_edge''': 2_5_6}
				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase   ,     default_to_square=lowercase			)
				SCREAMING_SNAKE_CASE     						= crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase   ,     param_name='''crop_size'''			)
				SCREAMING_SNAKE_CASE     						= do_resize
				SCREAMING_SNAKE_CASE     						= size
				SCREAMING_SNAKE_CASE     						= resample
				SCREAMING_SNAKE_CASE     						= do_center_crop
				SCREAMING_SNAKE_CASE     						= crop_size
				SCREAMING_SNAKE_CASE     						= do_rescale
				SCREAMING_SNAKE_CASE     						= rescale_factor
				SCREAMING_SNAKE_CASE     						= do_normalize
				SCREAMING_SNAKE_CASE     						= image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
				SCREAMING_SNAKE_CASE     						= image_std if image_std is not None else IMAGENET_STANDARD_STD







	def  snake_case__     (     self      :Optional[Any]   ,     lowercase      :np.ndarray   ,     lowercase      :Dict[str, int]   ,     lowercase      :PILImageResampling = PILImageResampling.BICUBIC   ,     lowercase      :Optional[Union[str, ChannelDimension]] = None   ,     **lowercase      :Dict   ,     )		->      np.ndarray:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase   ,     default_to_square=lowercase			)
				if "shortest_edge" not in size:
							raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""			)
				SCREAMING_SNAKE_CASE     						= get_resize_output_image_size(lowercase   ,     size=size['''shortest_edge''']   ,     default_to_square=lowercase			)
				return resize(lowercase   ,     size=lowercase   ,     resample=lowercase   ,     data_format=lowercase   ,     **lowercase			)







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







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase			)
				if "height" not in size or "width" not in size:
							raise ValueError(f"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"""			)
				return center_crop(lowercase   ,     size=(size['''height'''], size['''width'''])   ,     data_format=lowercase   ,     **lowercase			)







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







				"""simple docstring"""






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







	def  snake_case__     (     self      :List[Any]   ,     lowercase      :np.ndarray   ,     lowercase      :Union[float, List[float]]   ,     lowercase      :Union[float, List[float]]   ,     lowercase      :Optional[Union[str, ChannelDimension]] = None   ,     **lowercase      :List[str]   ,     )		->      np.ndarray:







				"""simple docstring"""






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







	def  snake_case__     (     self      :List[Any]   ,     lowercase      :ImageInput   ,     lowercase      :Optional[bool] = None   ,     lowercase      :Dict[str, int] = None   ,     lowercase      :PILImageResampling = None   ,     lowercase      :bool = None   ,     lowercase      :Dict[str, int] = None   ,     lowercase      :Optional[bool] = None   ,     lowercase      :Optional[float] = None   ,     lowercase      :Optional[bool] = None   ,     lowercase      :Optional[Union[float, List[float]]] = None   ,     lowercase      :Optional[Union[float, List[float]]] = None   ,     lowercase      :Optional[Union[str, TensorType]] = None   ,     lowercase      :Union[str, ChannelDimension] = ChannelDimension.FIRST   ,     **lowercase      :Any   ,     )		->      Union[str, Any]:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= do_resize if do_resize is not None else self.do_resize
				SCREAMING_SNAKE_CASE     						= size if size is not None else self.size
				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase   ,     default_to_square=lowercase			)
				SCREAMING_SNAKE_CASE     						= resample if resample is not None else self.resample
				SCREAMING_SNAKE_CASE     						= do_center_crop if do_center_crop is not None else self.do_center_crop
				SCREAMING_SNAKE_CASE     						= crop_size if crop_size is not None else self.crop_size
				SCREAMING_SNAKE_CASE     						= get_size_dict(lowercase   ,     param_name='''crop_size'''			)
				SCREAMING_SNAKE_CASE     						= do_rescale if do_rescale is not None else self.do_rescale
				SCREAMING_SNAKE_CASE     						= rescale_factor if rescale_factor is not None else self.rescale_factor
				SCREAMING_SNAKE_CASE     						= do_normalize if do_normalize is not None else self.do_normalize
				SCREAMING_SNAKE_CASE     						= image_mean if image_mean is not None else self.image_mean
				SCREAMING_SNAKE_CASE     						= image_std if image_std is not None else self.image_std

				SCREAMING_SNAKE_CASE     						= make_list_of_images(lowercase			)

				if not valid_images(lowercase			):
							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:
							raise ValueError('''Size 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.
				SCREAMING_SNAKE_CASE     						= [to_numpy_array(lowercase			) for image in images]

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

				if do_center_crop:
							SCREAMING_SNAKE_CASE     						= [self.center_crop(image=lowercase   ,     size=lowercase			) for image in images]

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

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

				SCREAMING_SNAKE_CASE     						= [to_channel_dimension_format(lowercase   ,     lowercase			) for image in images]

				SCREAMING_SNAKE_CASE     						= {'''pixel_values''': images}
				return BatchFeature(data=lowercase   ,     tensor_type=lowercase			)







	def  snake_case__     (     self      :Optional[Any]   ,     lowercase      :List[str]   ,     lowercase      :List[Tuple] = None			)		->      List[Any]:







				"""simple docstring"""






				SCREAMING_SNAKE_CASE     						= outputs.logits

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

							if is_torch_tensor(lowercase			):
										SCREAMING_SNAKE_CASE     						= target_sizes.numpy()

							SCREAMING_SNAKE_CASE     						= []

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

				return semantic_segmentation

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase					   =       logging.get_logger(__name__)

__lowerCAmelCase					   =       {
    'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json',
}





class     lowerCamelCase      (       __lowerCamelCase					):
	UpperCamelCase_  :					Union[str, Any]    		=	'mgp-str'







	def __init__(     self      :Union[str, Any]   ,     lowercase      :Union[str, Any]=[3_2, 1_2_8]   ,     lowercase      :Tuple=4   ,     lowercase      :Optional[int]=3   ,     lowercase      :Union[str, Any]=2_7   ,     lowercase      :List[str]=3_8   ,     lowercase      :Optional[Any]=5_0_2_5_7   ,     lowercase      :str=3_0_5_2_2   ,     lowercase      :Dict=7_6_8   ,     lowercase      :List[Any]=1_2   ,     lowercase      :List[str]=1_2   ,     lowercase      :Optional[Any]=4.0   ,     lowercase      :Optional[Any]=True   ,     lowercase      :str=False   ,     lowercase      :Optional[Any]=1e-5   ,     lowercase      :List[str]=0.0   ,     lowercase      :List[Any]=0.0   ,     lowercase      :Optional[int]=0.0   ,     lowercase      :Dict=False   ,     lowercase      :Optional[Any]=0.02   ,     **lowercase      :Optional[Any]   ,     )		->      Dict:







				"""simple docstring"""






				super().__init__(**lowercase			)

				SCREAMING_SNAKE_CASE     						= image_size
				SCREAMING_SNAKE_CASE     						= patch_size
				SCREAMING_SNAKE_CASE     						= num_channels
				SCREAMING_SNAKE_CASE     						= max_token_length
				SCREAMING_SNAKE_CASE     						= num_character_labels
				SCREAMING_SNAKE_CASE     						= num_bpe_labels
				SCREAMING_SNAKE_CASE     						= num_wordpiece_labels
				SCREAMING_SNAKE_CASE     						= hidden_size
				SCREAMING_SNAKE_CASE     						= num_hidden_layers
				SCREAMING_SNAKE_CASE     						= num_attention_heads
				SCREAMING_SNAKE_CASE     						= mlp_ratio
				SCREAMING_SNAKE_CASE     						= distilled
				SCREAMING_SNAKE_CASE     						= layer_norm_eps
				SCREAMING_SNAKE_CASE     						= drop_rate
				SCREAMING_SNAKE_CASE     						= qkv_bias
				SCREAMING_SNAKE_CASE     						= attn_drop_rate
				SCREAMING_SNAKE_CASE     						= drop_path_rate
				SCREAMING_SNAKE_CASE     						= output_aa_attentions
				SCREAMING_SNAKE_CASE     						= initializer_range