import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__UpperCamelCase	: List[str]    		=  {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}





@is_pipeline_test
class       lowercase__		(     unittest.TestCase):
						UpperCamelCase_  =	MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						UpperCamelCase_  =	TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

						if model_mapping is not None:
												UpperCamelCase_  =	{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
						if tf_model_mapping is not None:
												UpperCamelCase_  =	{
												    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
												}


						def  __A ( self			:       str					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       int					,	UpperCamelCase__			:       Tuple		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Optional[int]           =							ZeroShotClassificationPipeline(
												    model=__lowerCAmelCase					,	tokenizer=__lowerCAmelCase					,	candidate_labels=['''polics''', '''health''']		)
												return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]


						def  __A ( self			:       List[Any]					,	UpperCamelCase__			:       Any					,	UpperCamelCase__			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							classifier('''Who are you voting for in 2020?'''					,	candidate_labels='''politics'''		)
												self.assertEqual(__lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		)]}		)

												# No kwarg
												SCREAMING_SNAKE_CASE							:					Any           =							classifier('''Who are you voting for in 2020?'''					,	['''politics''']		)
												self.assertEqual(__lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		)]}		)

												SCREAMING_SNAKE_CASE							:					List[Any]           =							classifier('''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''']		)
												self.assertEqual(__lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		)]}		)

												SCREAMING_SNAKE_CASE							:					str           =							classifier('''Who are you voting for in 2020?'''					,	candidate_labels='''politics, public health'''		)
												self.assertEqual(
												    __lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)]}		)
												self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']		)		)					,	1.0		)

												SCREAMING_SNAKE_CASE							:					int           =							classifier('''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''', '''public health''']		)
												self.assertEqual(
												    __lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)]}		)
												self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']		)		)					,	1.0		)

												SCREAMING_SNAKE_CASE							:					List[Any]           =							classifier(
												    '''Who are you voting for in 2020?'''					,	candidate_labels='''politics'''					,	hypothesis_template='''This text is about {}'''		)
												self.assertEqual(__lowerCAmelCase					,	{'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		)]}		)

												# https://github.com/huggingface/transformers/issues/13846
												SCREAMING_SNAKE_CASE							:					str           =							classifier(['''I am happy''']					,	['''positive''', '''negative''']		)
												self.assertEqual(
												    __lowerCAmelCase					,	[
												        {'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)]}
												        for i in range(1		)
												    ]					,	)
												SCREAMING_SNAKE_CASE							:					Any           =							classifier(['''I am happy''', '''I am sad''']					,	['''positive''', '''negative''']		)
												self.assertEqual(
												    __lowerCAmelCase					,	[
												        {'''sequence''': ANY(__lowerCAmelCase		), '''labels''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)], '''scores''': [ANY(__lowerCAmelCase		), ANY(__lowerCAmelCase		)]}
												        for i in range(2		)
												    ]					,	)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier(''''''					,	candidate_labels='''politics'''		)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier(__lowerCAmelCase					,	candidate_labels='''politics'''		)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier('''Who are you voting for in 2020?'''					,	candidate_labels=''''''		)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier('''Who are you voting for in 2020?'''					,	candidate_labels=__lowerCAmelCase		)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier(
																		    '''Who are you voting for in 2020?'''					,	candidate_labels='''politics'''					,	hypothesis_template='''Not formatting template'''					,	)

												with self.assertRaises(__lowerCAmelCase		):
																		classifier(
																		    '''Who are you voting for in 2020?'''					,	candidate_labels='''politics'''					,	hypothesis_template=__lowerCAmelCase					,	)

												self.run_entailment_id(__lowerCAmelCase		)


						def  __A ( self			:       List[str]					,	UpperCamelCase__			:       Pipeline		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[Any]           =							zero_shot_classifier.model.config
												SCREAMING_SNAKE_CASE							:					Tuple           =							config.labelaid
												SCREAMING_SNAKE_CASE							:					List[str]           =							zero_shot_classifier.entailment_id

												SCREAMING_SNAKE_CASE							:					str           =							{'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2}
												self.assertEqual(zero_shot_classifier.entailment_id					,	-1		)

												SCREAMING_SNAKE_CASE							:					str           =							{'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2}
												self.assertEqual(zero_shot_classifier.entailment_id					,	0		)

												SCREAMING_SNAKE_CASE							:					int           =							{'''ENTAIL''': 0, '''NON-ENTAIL''': 1}
												self.assertEqual(zero_shot_classifier.entailment_id					,	0		)

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							{'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0}
												self.assertEqual(zero_shot_classifier.entailment_id					,	2		)

												SCREAMING_SNAKE_CASE							:					List[Any]           =							original_labelaid
												self.assertEqual(__lowerCAmelCase					,	zero_shot_classifier.entailment_id		)


						@require_torch
						def  __A ( self			:       Tuple		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Tuple           =							pipeline(
												    '''zero-shot-classification'''					,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''					,	framework='''pt'''					,	)
												# There was a regression in 4.10 for this
												# Adding a test so we don't make the mistake again.
												# https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
												zero_shot_classifier(
												    '''Who are you voting for in 2020?''' * 100					,	candidate_labels=['''politics''', '''public health''', '''science''']		)


						@require_torch
						def  __A ( self			:       Optional[int]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							pipeline(
												    '''zero-shot-classification'''					,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''					,	framework='''pt'''					,	)
												SCREAMING_SNAKE_CASE							:					List[Any]           =							zero_shot_classifier(
												    '''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''', '''public health''', '''science''']		)

												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': '''Who are you voting for in 2020?''',
												        '''labels''': ['''science''', '''public health''', '''politics'''],
												        '''scores''': [0.333, 0.333, 0.333],
												    }					,	)


						@require_tf
						def  __A ( self			:       int		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							pipeline(
												    '''zero-shot-classification'''					,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''					,	framework='''tf'''					,	)
												SCREAMING_SNAKE_CASE							:					List[Any]           =							zero_shot_classifier(
												    '''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''', '''public health''', '''science''']		)

												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': '''Who are you voting for in 2020?''',
												        '''labels''': ['''science''', '''public health''', '''politics'''],
												        '''scores''': [0.333, 0.333, 0.333],
												    }					,	)


						@slow
						@require_torch
						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							pipeline('''zero-shot-classification'''					,	model='''roberta-large-mnli'''					,	framework='''pt'''		)
												SCREAMING_SNAKE_CASE							:					Tuple           =							zero_shot_classifier(
												    '''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''', '''public health''', '''science''']		)

												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': '''Who are you voting for in 2020?''',
												        '''labels''': ['''politics''', '''public health''', '''science'''],
												        '''scores''': [0.976, 0.015, 0.009],
												    }					,	)
												SCREAMING_SNAKE_CASE							:					List[Any]           =							zero_shot_classifier(
												    '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
												    ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
												    ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
												    ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
												    ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
												    ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
												    ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
												    ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
												    ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
												    ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
												    ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
												    ''' large and limited training data.'''					,	candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']					,	multi_label=__lowerCAmelCase					,	)
												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': (
												            '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
												            ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
												            ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
												            ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
												            ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
												            ''' superior in quality while being more parallelizable and requiring significantly less time to'''
												            ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
												            ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
												            ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
												            ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
												            ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
												            ''' other tasks by applying it successfully to English constituency parsing both with large and'''
												            ''' limited training data.'''
												        ),
												        '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
												        '''scores''': [0.817, 0.713, 0.018, 0.018],
												    }					,	)



						@slow
						@require_tf
						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							pipeline('''zero-shot-classification'''					,	model='''roberta-large-mnli'''					,	framework='''tf'''		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							zero_shot_classifier(
												    '''Who are you voting for in 2020?'''					,	candidate_labels=['''politics''', '''public health''', '''science''']		)

												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': '''Who are you voting for in 2020?''',
												        '''labels''': ['''politics''', '''public health''', '''science'''],
												        '''scores''': [0.976, 0.015, 0.009],
												    }					,	)
												SCREAMING_SNAKE_CASE							:					List[str]           =							zero_shot_classifier(
												    '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
												    ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
												    ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
												    ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
												    ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
												    ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
												    ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
												    ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
												    ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
												    ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
												    ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
												    ''' large and limited training data.'''					,	candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']					,	multi_label=__lowerCAmelCase					,	)
												self.assertEqual(
												    nested_simplify(__lowerCAmelCase		)					,	{
												        '''sequence''': (
												            '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
												            ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
												            ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
												            ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
												            ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
												            ''' superior in quality while being more parallelizable and requiring significantly less time to'''
												            ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
												            ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
												            ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
												            ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
												            ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
												            ''' other tasks by applying it successfully to English constituency parsing both with large and'''
												            ''' limited training data.'''
												        ),
												        '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
												        '''scores''': [0.817, 0.713, 0.018, 0.018],
												    }					,	)






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


__UpperCamelCase	: int    		=  logging.get_logger(__name__)
def    A			(					_lowercase	,						_lowercase	,						_lowercase	,						_lowercase		):
						def constraint_to_multiple_of(_lowercase	,						_lowercase	,						_lowercase=0	,						_lowercase=None		):
												SCREAMING_SNAKE_CASE							:					int           =							round(val / multiple		) * multiple

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

												if x < min_val:
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							math.ceil(val / multiple		) * multiple

												return x

						SCREAMING_SNAKE_CASE							:					Optional[Any]           =							(output_size, output_size) if isinstance(_lowercase	,						_lowercase		) else output_size

						SCREAMING_SNAKE_CASE       ,						SCREAMING_SNAKE_CASE							:					Optional[int]           =							get_image_size(_lowercase		)
						SCREAMING_SNAKE_CASE       ,						SCREAMING_SNAKE_CASE							:					Optional[int]           =							output_size

						# determine new height and width
						SCREAMING_SNAKE_CASE							:					Dict           =							output_height / input_height
						SCREAMING_SNAKE_CASE							:					Optional[Any]           =							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							:					List[str]           =							constraint_to_multiple_of(scale_height * input_height	,						multiple=_lowercase		)
						SCREAMING_SNAKE_CASE							:					Optional[int]           =							constraint_to_multiple_of(scale_width * input_width	,						multiple=_lowercase		)

						return (new_height, new_width)





class       lowercase__		(     UpperCamelCase_):
						UpperCamelCase_  =	["""pixel_values"""]


						def __init__( self			:       int					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       Dict[str, int] = None					,	UpperCamelCase__			:       PILImageResampling = PILImageResampling.BILINEAR					,	UpperCamelCase__			:       bool = False					,	UpperCamelCase__			:       int = 1					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       Union[int, float] = 1 / 255					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       Optional[Union[float, List[float]]] = None					,	UpperCamelCase__			:       Optional[Union[float, List[float]]] = None					,	**UpperCamelCase__			:       Optional[int]					,	):





												'''simple docstring'''





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


						def  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       np.ndarray					,	UpperCamelCase__			:       Dict[str, int]					,	UpperCamelCase__			:       bool = False					,	UpperCamelCase__			:       int = 1					,	UpperCamelCase__			:       PILImageResampling = PILImageResampling.BICUBIC					,	UpperCamelCase__			:       Optional[Union[str, ChannelDimension]] = None					,	**UpperCamelCase__			:       Union[str, Any]					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[Any]           =							get_size_dict(UpperCamelCase__		)
												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							:					Any           =							get_resize_output_image_size(
												    UpperCamelCase__					,	output_size=(size['''height'''], size['''width'''])					,	keep_aspect_ratio=UpperCamelCase__					,	multiple=UpperCamelCase__					,	)
												return resize(UpperCamelCase__					,	size=UpperCamelCase__					,	resample=UpperCamelCase__					,	data_format=UpperCamelCase__					,	**UpperCamelCase__		)


						def  __A ( self			:       Dict					,	UpperCamelCase__			:       np.ndarray					,	UpperCamelCase__			:       Union[int, float]					,	UpperCamelCase__			:       Optional[Union[str, ChannelDimension]] = None					,	**UpperCamelCase__			:       str					,	):





												'''simple docstring'''





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


						def  __A ( self			:       Any					,	UpperCamelCase__			:       np.ndarray					,	UpperCamelCase__			:       Union[float, List[float]]					,	UpperCamelCase__			:       Union[float, List[float]]					,	UpperCamelCase__			:       Optional[Union[str, ChannelDimension]] = None					,	**UpperCamelCase__			:       List[str]					,	):





												'''simple docstring'''





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


						def  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       ImageInput					,	UpperCamelCase__			:       bool = None					,	UpperCamelCase__			:       int = None					,	UpperCamelCase__			:       bool = None					,	UpperCamelCase__			:       int = None					,	UpperCamelCase__			:       PILImageResampling = None					,	UpperCamelCase__			:       bool = None					,	UpperCamelCase__			:       float = None					,	UpperCamelCase__			:       bool = None					,	UpperCamelCase__			:       Optional[Union[float, List[float]]] = None					,	UpperCamelCase__			:       Optional[Union[float, List[float]]] = None					,	UpperCamelCase__			:       Optional[Union[str, TensorType]] = None					,	UpperCamelCase__			:       ChannelDimension = ChannelDimension.FIRST					,	**UpperCamelCase__			:       Optional[int]					,	):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:					Dict           =							make_list_of_images(UpperCamelCase__		)

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

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

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

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

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							[to_channel_dimension_format(UpperCamelCase__					,	UpperCamelCase__		) for image in images]

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



						def  __A ( self			:       Tuple					,	UpperCamelCase__			:       Union[str, Any]					,	UpperCamelCase__			:       List[Tuple] = None		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Dict           =							outputs.logits

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

																		if is_torch_tensor(UpperCamelCase__		):
																								SCREAMING_SNAKE_CASE							:					List[Any]           =							target_sizes.numpy()

																		SCREAMING_SNAKE_CASE							:					Optional[int]           =							[]

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

												return semantic_segmentation





