






import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    XLMForMultipleChoice,
	    XLMForQuestionAnswering,
	    XLMForQuestionAnsweringSimple,
	    XLMForSequenceClassification,
	    XLMForTokenClassification,
	    XLMModel,
	    XLMWithLMHeadModel,
	)
	from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST


class 					_snake_case						:






	def __init__(		self					,UpperCamelCase					,UpperCamelCase=13					,UpperCamelCase=7					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=False					,UpperCamelCase=False					,UpperCamelCase=False					,UpperCamelCase=2					,UpperCamelCase=99					,UpperCamelCase=0					,UpperCamelCase=32					,UpperCamelCase=5					,UpperCamelCase=4					,UpperCamelCase=0.1					,UpperCamelCase=0.1					,UpperCamelCase=512					,UpperCamelCase=2					,UpperCamelCase=0.02					,UpperCamelCase=2					,UpperCamelCase=4					,UpperCamelCase="last"					,UpperCamelCase=True					,UpperCamelCase=None					,UpperCamelCase=0					,)						->    int:
					snake_case__      :int         =   parent
					snake_case__      :Optional[Any]         =   batch_size
					snake_case__      :Union[str, Any]         =   seq_length
					snake_case__      :Optional[int]         =   is_training
					snake_case__      :Any         =   use_input_lengths
					snake_case__      :Any         =   use_token_type_ids
					snake_case__      :List[Any]         =   use_labels
					snake_case__      :List[Any]         =   gelu_activation
					snake_case__      :Union[str, Any]         =   sinusoidal_embeddings
					snake_case__      :List[str]         =   causal
					snake_case__      :str         =   asm
					snake_case__      :Union[str, Any]         =   n_langs
					snake_case__      :Union[str, Any]         =   vocab_size
					snake_case__      :Optional[Any]         =   n_special
					snake_case__      :List[str]         =   hidden_size
					snake_case__      :Dict         =   num_hidden_layers
					snake_case__      :Tuple         =   num_attention_heads
					snake_case__      :Dict         =   hidden_dropout_prob
					snake_case__      :List[Any]         =   attention_probs_dropout_prob
					snake_case__      :List[Any]         =   max_position_embeddings
					snake_case__      :Optional[Any]         =   type_sequence_label_size
					snake_case__      :Optional[int]         =   initializer_range
					snake_case__      :List[str]         =   num_labels
					snake_case__      :str         =   num_choices
					snake_case__      :Optional[Any]         =   summary_type
					snake_case__      :List[Any]         =   use_proj
					snake_case__      :Optional[int]         =   scope
					snake_case__      :Any         =   bos_token_id






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Any         =   ids_tensor([self.batch_size, self.seq_length]					,self.vocab_size       )
					snake_case__      :Dict         =   random_attention_mask([self.batch_size, self.seq_length]       )

					snake_case__      :str         =   None
					if self.use_input_lengths:
									snake_case__      :Dict         =   (
									    ids_tensor([self.batch_size]					,vocab_size=2       ) + self.seq_length - 2
									)  # small variation of seq_length

					snake_case__      :Union[str, Any]         =   None
					if self.use_token_type_ids:
									snake_case__      :Any         =   ids_tensor([self.batch_size, self.seq_length]					,self.n_langs       )

					snake_case__      :Optional[int]         =   None
					snake_case__      :Optional[Any]         =   None
					snake_case__      :List[str]         =   None
					if self.use_labels:
									snake_case__      :List[str]         =   ids_tensor([self.batch_size]					,self.type_sequence_label_size       )
									snake_case__      :Optional[int]         =   ids_tensor([self.batch_size, self.seq_length]					,self.num_labels       )
									snake_case__      :Union[str, Any]         =   ids_tensor([self.batch_size]					,2       ).float()
									snake_case__      :Union[str, Any]         =   ids_tensor([self.batch_size]					,self.num_choices       )

					snake_case__      :Tuple         =   self.get_config()

					return (
					    config,
					    input_ids,
					    token_type_ids,
					    input_lengths,
					    sequence_labels,
					    token_labels,
					    is_impossible_labels,
					    choice_labels,
					    input_mask,
					)






	def    lowerCAmelCase_							(		self       )						->    Union[str, Any]:
					return XLMConfig(
					    vocab_size=self.vocab_size					,n_special=self.n_special					,emb_dim=self.hidden_size					,n_layers=self.num_hidden_layers					,n_heads=self.num_attention_heads					,dropout=self.hidden_dropout_prob					,attention_dropout=self.attention_probs_dropout_prob					,gelu_activation=self.gelu_activation					,sinusoidal_embeddings=self.sinusoidal_embeddings					,asm=self.asm					,causal=self.causal					,n_langs=self.n_langs					,max_position_embeddings=self.max_position_embeddings					,initializer_range=self.initializer_range					,summary_type=self.summary_type					,use_proj=self.use_proj					,num_labels=self.num_labels					,bos_token_id=self.bos_token_id					,)






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    Any:
					snake_case__      :Dict         =   XLMModel(config=UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()
					snake_case__      :Optional[int]         =   model(UpperCamelCase					,lengths=UpperCamelCase					,langs=UpperCamelCase       )
					snake_case__      :Any         =   model(UpperCamelCase					,langs=UpperCamelCase       )
					snake_case__      :str         =   model(UpperCamelCase       )
					self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, self.seq_length, self.hidden_size)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    int:
					snake_case__      :Dict         =   XLMWithLMHeadModel(UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()

					snake_case__      :List[Any]         =   model(UpperCamelCase					,token_type_ids=UpperCamelCase					,labels=UpperCamelCase       )
					self.parent.assertEqual(result.loss.shape					,()       )
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.seq_length, self.vocab_size)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    Tuple:
					snake_case__      :Any         =   XLMForQuestionAnsweringSimple(UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()

					snake_case__      :List[Any]         =   model(UpperCamelCase       )

					snake_case__      :Any         =   model(UpperCamelCase					,start_positions=UpperCamelCase					,end_positions=UpperCamelCase       )
					snake_case__      :List[str]         =   outputs
					self.parent.assertEqual(result.start_logits.shape					,(self.batch_size, self.seq_length)       )
					self.parent.assertEqual(result.end_logits.shape					,(self.batch_size, self.seq_length)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    Any:
					snake_case__      :List[str]         =   XLMForQuestionAnswering(UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()

					snake_case__      :str         =   model(UpperCamelCase       )

					snake_case__      :Union[str, Any]         =   model(
					    UpperCamelCase					,start_positions=UpperCamelCase					,end_positions=UpperCamelCase					,cls_index=UpperCamelCase					,is_impossible=UpperCamelCase					,p_mask=UpperCamelCase					,)

					snake_case__      :Any         =   model(
					    UpperCamelCase					,start_positions=UpperCamelCase					,end_positions=UpperCamelCase					,cls_index=UpperCamelCase					,is_impossible=UpperCamelCase					,)

					((snake_case__)    ,						)      :str         =   result_with_labels.to_tuple()

					snake_case__      :Any         =   model(UpperCamelCase					,start_positions=UpperCamelCase					,end_positions=UpperCamelCase       )

					((snake_case__)    ,						)      :List[str]         =   result_with_labels.to_tuple()

					self.parent.assertEqual(result_with_labels.loss.shape					,()       )
					self.parent.assertEqual(result.start_top_log_probs.shape					,(self.batch_size, model.config.start_n_top)       )
					self.parent.assertEqual(result.start_top_index.shape					,(self.batch_size, model.config.start_n_top)       )
					self.parent.assertEqual(
					    result.end_top_log_probs.shape					,(self.batch_size, model.config.start_n_top * model.config.end_n_top)       )
					self.parent.assertEqual(
					    result.end_top_index.shape					,(self.batch_size, model.config.start_n_top * model.config.end_n_top)       )
					self.parent.assertEqual(result.cls_logits.shape					,(self.batch_size,)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    Union[str, Any]:
					snake_case__      :List[str]         =   XLMForSequenceClassification(UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()

					snake_case__      :str         =   model(UpperCamelCase       )
					snake_case__      :int         =   model(UpperCamelCase					,labels=UpperCamelCase       )
					self.parent.assertEqual(result.loss.shape					,()       )
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.type_sequence_label_size)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    Optional[int]:
					snake_case__      :Optional[int]         =   self.num_labels
					snake_case__      :List[str]         =   XLMForTokenClassification(UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()

					snake_case__      :int         =   model(UpperCamelCase					,attention_mask=UpperCamelCase					,labels=UpperCamelCase       )
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.seq_length, self.num_labels)       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,)						->    int:
					snake_case__      :str         =   self.num_choices
					snake_case__      :Union[str, Any]         =   XLMForMultipleChoice(config=UpperCamelCase       )
					model.to(UpperCamelCase       )
					model.eval()
					snake_case__      :List[Any]         =   input_ids.unsqueeze(1       ).expand(-1					,self.num_choices					,-1       ).contiguous()
					snake_case__      :List[str]         =   token_type_ids.unsqueeze(1       ).expand(-1					,self.num_choices					,-1       ).contiguous()
					snake_case__      :List[str]         =   input_mask.unsqueeze(1       ).expand(-1					,self.num_choices					,-1       ).contiguous()
					snake_case__      :Optional[int]         =   model(
					    UpperCamelCase					,attention_mask=UpperCamelCase					,token_type_ids=UpperCamelCase					,labels=UpperCamelCase					,)
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.num_choices)       )






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					snake_case__      :List[str]         =   self.prepare_config_and_inputs()
					(
					    (
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						(
					    snake_case__
					)    ,						
					)      :int         =   config_and_inputs
					snake_case__      :Any         =   {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths}
					return config, inputs_dict




@require_torch
class 					_snake_case						(			_A       ,    _A       ,    _A       ,    unittest.TestCase ):
	_A          =   (
	    (
	        XLMModel,
	        XLMWithLMHeadModel,
	        XLMForQuestionAnswering,
	        XLMForSequenceClassification,
	        XLMForQuestionAnsweringSimple,
	        XLMForTokenClassification,
	        XLMForMultipleChoice,
	    )
	    if is_torch_available()
	    else ()
	)
	_A          =   (
	    (XLMWithLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Check other models whether language generation is also applicable
	_A          =   (
	    {
	        'feature-extraction': XLMModel,
	        'fill-mask': XLMWithLMHeadModel,
	        'question-answering': XLMForQuestionAnsweringSimple,
	        'text-classification': XLMForSequenceClassification,
	        'text-generation': XLMWithLMHeadModel,
	        'token-classification': XLMForTokenClassification,
	        'zero-shot': XLMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    int:
					if (
					    pipeline_test_casse_name == "QAPipelineTests"
					    and tokenizer_name is not None
					    and not tokenizer_name.endswith("Fast"       )
					):
									# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
									# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
									# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
									return True

					return False






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=False       )						->    int:
					snake_case__      :Tuple         =   super()._prepare_for_class(UpperCamelCase					,UpperCamelCase					,return_labels=UpperCamelCase       )

					if return_labels:
									if model_class.__name__ == "XLMForQuestionAnswering":
													snake_case__      :Optional[Any]         =   torch.zeros(
													    self.model_tester.batch_size					,dtype=torch.long					,device=UpperCamelCase       )
													snake_case__      :List[str]         =   torch.zeros(
													    self.model_tester.batch_size					,dtype=torch.long					,device=UpperCamelCase       )

					return inputs_dict






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :Any         =   XLMModelTester(self       )
					snake_case__      :Union[str, Any]         =   ConfigTester(self					,config_class=UpperCamelCase					,emb_dim=37       )






	def    lowerCAmelCase_							(		self       )						->    Tuple:
					self.config_tester.run_common_tests()






	def    lowerCAmelCase_							(		self       )						->    str:
					snake_case__      :Tuple         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_model(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Optional[int]:
					snake_case__      :Optional[Any]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_lm_head(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					snake_case__      :Any         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_simple_qa(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :List[Any]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_qa(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :List[str]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_sequence_classif(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Optional[int]:
					snake_case__      :Tuple         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_token_classif(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :str         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCamelCase       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=False					,UpperCamelCase=1       )						->    Tuple:
					self.assertIsInstance(UpperCamelCase					,UpperCamelCase       )
					self.assertListEqual(
					    [isinstance(UpperCamelCase					,UpperCamelCase       ) for iter_attentions in attentions]					,[True] * len(UpperCamelCase       )       )
					self.assertEqual(len(UpperCamelCase       )					,(max_length - min_length) * num_beam_groups       )

					for idx, iter_attentions in enumerate(UpperCamelCase       ):
									# adds PAD dummy token
									snake_case__      :List[str]         =   min_length + idx + 1
									snake_case__      :Dict         =   min_length + idx + 1

									snake_case__      :List[str]         =   (
									    batch_size * num_beam_groups,
									    config.num_attention_heads,
									    tgt_len,
									    src_len,
									)
									# check attn size
									self.assertListEqual(
									    [layer_attention.shape for layer_attention in iter_attentions]					,[expected_shape] * len(UpperCamelCase       )       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=False					,UpperCamelCase=1       )						->    Any:
					self.assertIsInstance(UpperCamelCase					,UpperCamelCase       )
					self.assertListEqual(
					    [isinstance(UpperCamelCase					,UpperCamelCase       ) for iter_hidden_states in hidden_states]					,[True] * len(UpperCamelCase       )					,)
					self.assertEqual(len(UpperCamelCase       )					,(max_length - min_length) * num_beam_groups       )

					for idx, iter_hidden_states in enumerate(UpperCamelCase       ):
									# adds PAD dummy token
									snake_case__      :Dict         =   min_length + idx + 1
									snake_case__      :str         =   (batch_size * num_beam_groups, seq_len, config.hidden_size)
									# check hidden size
									self.assertListEqual(
									    [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]					,[expected_shape] * len(UpperCamelCase       )					,)
					pass






	@slow
	def    lowerCAmelCase_							(		self       )						->    str:
					for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__      :str         =   XLMModel.from_pretrained(UpperCamelCase       )
									self.assertIsNotNone(UpperCamelCase       )




@require_torch
class 					_snake_case						(			unittest.TestCase ):






	@slow
	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :Optional[int]         =   XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048"       )
					model.to(UpperCamelCase       )
					snake_case__      :Optional[int]         =   torch.tensor([[14, 447]]					,dtype=torch.long					,device=UpperCamelCase       )  # the president
					snake_case__      :str         =   [
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					    14,
					    447,
					]  # the president the president the president the president the president the president the president the president the president the president
					# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
					snake_case__      :Optional[Any]         =   model.generate(UpperCamelCase					,do_sample=UpperCamelCase       )
					self.assertListEqual(output_ids[0].cpu().numpy().tolist()					,UpperCamelCase       )







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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
    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


__UpperCAmelCase							:   Optional[Any]							=  logging.get_logger(__name__)





def 					lowercase_ (    __snake_case     :							Any	,	__snake_case     :							Any      )     -> Any:





				'''simple docstring'''


				snake_case__      :Optional[Any]         =   b.T
				snake_case__      :Optional[Any]         =   np.sum(np.square(__snake_case      )	,	axis=1      )
				snake_case__      :Tuple         =   np.sum(np.square(__snake_case      )	,	axis=0      )
				snake_case__      :Union[str, Any]         =   np.matmul(__snake_case	,	__snake_case      )
				snake_case__      :Union[str, Any]         =   aa[:, None] - 2 * ab + ba[None, :]
				return d





def 					lowercase_ (    __snake_case     :							Optional[Any]	,	__snake_case     :							int      )     -> Any:





				'''simple docstring'''


				snake_case__      :Optional[Any]         =   x.reshape(-1	,	3      )
				snake_case__      :List[str]         =   squared_euclidean_distance(__snake_case	,	__snake_case      )
				return np.argmin(__snake_case	,	axis=1      )


class 					_snake_case						(			_A ):
	_A          =   ['pixel_values']






	def __init__(		self					,UpperCamelCase = None					,UpperCamelCase = True					,UpperCamelCase = None					,UpperCamelCase = PILImageResampling.BILINEAR					,UpperCamelCase = True					,UpperCamelCase = True					,**UpperCamelCase					,)						->    None:
					super().__init__(**UpperCamelCase       )
					snake_case__      :List[Any]         =   size if size is not None else {"height": 256, "width": 256}
					snake_case__      :str         =   get_size_dict(UpperCamelCase       )
					snake_case__      :Dict         =   np.array(UpperCamelCase       ) if clusters is not None else None
					snake_case__      :str         =   do_resize
					snake_case__      :List[str]         =   size
					snake_case__      :List[Any]         =   resample
					snake_case__      :Union[str, Any]         =   do_normalize
					snake_case__      :int         =   do_color_quantize






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase = PILImageResampling.BILINEAR					,UpperCamelCase = None					,**UpperCamelCase					,)						->    np.ndarray:
					snake_case__      :List[str]         =   get_size_dict(UpperCamelCase       )
					if "height" not in size or "width" not in size:
									raise ValueError(f'Size dictionary must contain both height and width keys. Got {size.keys()}'       )
					return resize(
					    UpperCamelCase					,size=(size["height"], size["width"])					,resample=UpperCamelCase					,data_format=UpperCamelCase					,**UpperCamelCase       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None					,)						->    np.ndarray:
					snake_case__      :Tuple         =   rescale(image=UpperCamelCase					,scale=1 / 127.5					,data_format=UpperCamelCase       )
					snake_case__      :List[Any]         =   image - 1
					return image






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = None					,UpperCamelCase = ChannelDimension.FIRST					,**UpperCamelCase					,)						->    PIL.Image.Image:
					snake_case__      :Optional[int]         =   do_resize if do_resize is not None else self.do_resize
					snake_case__      :int         =   size if size is not None else self.size
					snake_case__      :Tuple         =   get_size_dict(UpperCamelCase       )
					snake_case__      :str         =   resample if resample is not None else self.resample
					snake_case__      :Dict         =   do_normalize if do_normalize is not None else self.do_normalize
					snake_case__      :Tuple         =   do_color_quantize if do_color_quantize is not None else self.do_color_quantize
					snake_case__      :List[Any]         =   clusters if clusters is not None else self.clusters
					snake_case__      :str         =   np.array(UpperCamelCase       )

					snake_case__      :int         =   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_color_quantize and clusters is None:
									raise ValueError("Clusters must be specified if do_color_quantize is True."       )

					# All transformations expect numpy arrays.
					snake_case__      :Union[str, Any]         =   [to_numpy_array(UpperCamelCase       ) for image in images]

					if do_resize:
									snake_case__      :int         =   [self.resize(image=UpperCamelCase					,size=UpperCamelCase					,resample=UpperCamelCase       ) for image in images]

					if do_normalize:
									snake_case__      :Any         =   [self.normalize(image=UpperCamelCase       ) for image in images]

					if do_color_quantize:
									snake_case__      :Optional[Any]         =   [to_channel_dimension_format(UpperCamelCase					,ChannelDimension.LAST       ) for image in images]
									# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
									snake_case__      :Union[str, Any]         =   np.array(UpperCamelCase       )
									snake_case__      :Optional[int]         =   color_quantize(UpperCamelCase					,UpperCamelCase       ).reshape(images.shape[:-1]       )

									# flatten to (batch_size, height*width)
									snake_case__      :List[Any]         =   images.shape[0]
									snake_case__      :str         =   images.reshape(UpperCamelCase					,-1       )

									# We need to convert back to a list of images to keep consistent behaviour across processors.
									snake_case__      :Any         =   list(UpperCamelCase       )
					else:
									snake_case__      :List[str]         =   [to_channel_dimension_format(UpperCamelCase					,UpperCamelCase       ) for image in images]

					snake_case__      :List[str]         =   {"input_ids": images}
					return BatchFeature(data=UpperCamelCase					,tensor_type=UpperCamelCase       )