




'''simple docstring'''


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      A       :







							def __init__(    self			:    List[str]				,     lowerCAmelCase_			:    Tuple				,     lowerCAmelCase_			:    Dict=13				,     lowerCAmelCase_			:    int=7				,     lowerCAmelCase_			:    Any=True				,     lowerCAmelCase_			:    Any=True				,     lowerCAmelCase_			:    Any=True				,     lowerCAmelCase_			:    List[str]=True				,     lowerCAmelCase_			:    List[str]=True				,     lowerCAmelCase_			:    Union[str, Any]=False				,     lowerCAmelCase_			:    Optional[Any]=False				,     lowerCAmelCase_			:    int=False				,     lowerCAmelCase_			:    Tuple=2				,     lowerCAmelCase_			:    Optional[Any]=99				,     lowerCAmelCase_			:    Tuple=0				,     lowerCAmelCase_			:    List[Any]=32				,     lowerCAmelCase_			:    List[Any]=5				,     lowerCAmelCase_			:    str=4				,     lowerCAmelCase_			:    List[Any]=0.1				,     lowerCAmelCase_			:    Optional[int]=0.1				,     lowerCAmelCase_			:    Tuple=5_12				,     lowerCAmelCase_			:    Union[str, Any]=2				,     lowerCAmelCase_			:    List[Any]=0.0_2				,     lowerCAmelCase_			:    Optional[Any]=2				,     lowerCAmelCase_			:    Tuple=4				,     lowerCAmelCase_			:    str="last"				,     lowerCAmelCase_			:    List[str]=True				,     lowerCAmelCase_			:    int=None				,     lowerCAmelCase_			:    Tuple=0				,     )     ->				List[Any]:


														"""simple docstring"""


														_a      	=							parent
														_a      	=							batch_size
														_a      	=							seq_length
														_a      	=							is_training
														_a      	=							use_input_lengths
														_a      	=							use_token_type_ids
														_a      	=							use_labels
														_a      	=							gelu_activation
														_a      	=							sinusoidal_embeddings
														_a      	=							causal
														_a      	=							asm
														_a      	=							n_langs
														_a      	=							vocab_size
														_a      	=							n_special
														_a      	=							hidden_size
														_a      	=							num_hidden_layers
														_a      	=							num_attention_heads
														_a      	=							hidden_dropout_prob
														_a      	=							attention_probs_dropout_prob
														_a      	=							max_position_embeddings
														_a      	=							type_sequence_label_size
														_a      	=							initializer_range
														_a      	=							num_labels
														_a      	=							num_choices
														_a      	=							summary_type
														_a      	=							use_proj
														_a      	=							scope
														_a      	=							bos_token_id







							def   __lowerCAmelCase     (    self			:    Tuple   )     ->				Union[str, Any]:


														"""simple docstring"""


														_a      	=							ids_tensor([self.batch_size, self.seq_length]				,     self.vocab_size   )
														_a      	=							random_attention_mask([self.batch_size, self.seq_length]   )

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

														_a      	=							None
														if self.use_token_type_ids:
																					_a      	=							ids_tensor([self.batch_size, self.seq_length]				,     self.n_langs   )

														_a      	=							None
														_a      	=							None
														_a      	=							None
														if self.use_labels:
																					_a      	=							ids_tensor([self.batch_size]				,     self.type_sequence_label_size   )
																					_a      	=							ids_tensor([self.batch_size, self.seq_length]				,     self.num_labels   )
																					_a      	=							ids_tensor([self.batch_size]				,     2   ).float()
																					_a      	=							ids_tensor([self.batch_size]				,     self.num_choices   )

														_a      	=							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			:    List[str]   )     ->				Dict:


														"""simple docstring"""


														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			:    Union[str, Any]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    int				,     )     ->				str:


														"""simple docstring"""


														_a      	=							XLMModel(config=lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()
														_a      	=							model(lowerCAmelCase_				,     lengths=lowerCAmelCase_				,     langs=lowerCAmelCase_   )
														_a      	=							model(lowerCAmelCase_				,     langs=lowerCAmelCase_   )
														_a      	=							model(lowerCAmelCase_   )
														self.parent.assertEqual(result.last_hidden_state.shape				,     (self.batch_size, self.seq_length, self.hidden_size)   )







							def   __lowerCAmelCase     (    self			:    int				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    str				,     )     ->				int:


														"""simple docstring"""


														_a      	=							XLMWithLMHeadModel(lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()

														_a      	=							model(lowerCAmelCase_				,     token_type_ids=lowerCAmelCase_				,     labels=lowerCAmelCase_   )
														self.parent.assertEqual(result.loss.shape				,     ()   )
														self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.vocab_size)   )







							def   __lowerCAmelCase     (    self			:    Union[str, Any]				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Tuple				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    Dict				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    Optional[int]				,     )     ->				int:


														"""simple docstring"""


														_a      	=							XLMForQuestionAnsweringSimple(lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()

														_a      	=							model(lowerCAmelCase_   )

														_a      	=							model(lowerCAmelCase_				,     start_positions=lowerCAmelCase_				,     end_positions=lowerCAmelCase_   )
														_a      	=							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			:    str				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    Any				,     )     ->				Tuple:


														"""simple docstring"""


														_a      	=							XLMForQuestionAnswering(lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()

														_a      	=							model(lowerCAmelCase_   )

														_a      	=							model(
														    lowerCAmelCase_				,     start_positions=lowerCAmelCase_				,     end_positions=lowerCAmelCase_				,     cls_index=lowerCAmelCase_				,     is_impossible=lowerCAmelCase_				,     p_mask=lowerCAmelCase_				,     )

														_a      	=							model(
														    lowerCAmelCase_				,     start_positions=lowerCAmelCase_				,     end_positions=lowerCAmelCase_				,     cls_index=lowerCAmelCase_				,     is_impossible=lowerCAmelCase_				,     )

														((_a)	,				)      	=							result_with_labels.to_tuple()

														_a      	=							model(lowerCAmelCase_				,     start_positions=lowerCAmelCase_				,     end_positions=lowerCAmelCase_   )

														((_a)	,				)      	=							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			:    str				,     lowerCAmelCase_			:    Dict				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    Tuple				,     )     ->				Dict:


														"""simple docstring"""


														_a      	=							XLMForSequenceClassification(lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()

														_a      	=							model(lowerCAmelCase_   )
														_a      	=							model(lowerCAmelCase_				,     labels=lowerCAmelCase_   )
														self.parent.assertEqual(result.loss.shape				,     ()   )
														self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size)   )







							def   __lowerCAmelCase     (    self			:    List[Any]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    List[str]				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    str				,     )     ->				Optional[Any]:


														"""simple docstring"""


														_a      	=							self.num_labels
														_a      	=							XLMForTokenClassification(lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()

														_a      	=							model(lowerCAmelCase_				,     attention_mask=lowerCAmelCase_				,     labels=lowerCAmelCase_   )
														self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.num_labels)   )







							def   __lowerCAmelCase     (    self			:    Union[str, Any]				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Tuple				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    Tuple				,     lowerCAmelCase_			:    Union[str, Any]				,     )     ->				Any:


														"""simple docstring"""


														_a      	=							self.num_choices
														_a      	=							XLMForMultipleChoice(config=lowerCAmelCase_   )
														model.to(lowerCAmelCase_   )
														model.eval()
														_a      	=							input_ids.unsqueeze(1   ).expand(-1				,     self.num_choices				,     -1   ).contiguous()
														_a      	=							token_type_ids.unsqueeze(1   ).expand(-1				,     self.num_choices				,     -1   ).contiguous()
														_a      	=							input_mask.unsqueeze(1   ).expand(-1				,     self.num_choices				,     -1   ).contiguous()
														_a      	=							model(
														    lowerCAmelCase_				,     attention_mask=lowerCAmelCase_				,     token_type_ids=lowerCAmelCase_				,     labels=lowerCAmelCase_				,     )
														self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_choices)   )







							def   __lowerCAmelCase     (    self			:    int   )     ->				Optional[int]:


														"""simple docstring"""


														_a      	=							self.prepare_config_and_inputs()
														(
														    (
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				(
														    _a
														)	,				
														)      	=							config_and_inputs
														_a      	=							{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
														return config, inputs_dict



@require_torch
class      A       (						_a	,_a	,_a	,unittest.TestCase       ):
							lowercase_							     =							(
							    (
							        XLMModel,
							        XLMWithLMHeadModel,
							        XLMForQuestionAnswering,
							        XLMForSequenceClassification,
							        XLMForQuestionAnsweringSimple,
							        XLMForTokenClassification,
							        XLMForMultipleChoice,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase_							     =							(
							    (XLMWithLMHeadModel,) if is_torch_available() else ()
							)  # TODO (PVP): Check other models whether language generation is also applicable
							lowercase_							     =							(
							    {
							        '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			:    Optional[int]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    Optional[Any]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    Tuple   )     ->				Optional[int]:


														"""simple docstring"""


														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			:    List[str]				,     lowerCAmelCase_			:    Optional[int]				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    int=False   )     ->				List[Any]:


														"""simple docstring"""


														_a      	=							super()._prepare_for_class(lowerCAmelCase_				,     lowerCAmelCase_				,     return_labels=lowerCAmelCase_   )

														if return_labels:
																					if model_class.__name__ == "XLMForQuestionAnswering":
																												_a      	=							torch.zeros(
																												    self.model_tester.batch_size				,     dtype=torch.long				,     device=lowerCAmelCase_   )
																												_a      	=							torch.zeros(
																												    self.model_tester.batch_size				,     dtype=torch.long				,     device=lowerCAmelCase_   )

														return inputs_dict







							def   __lowerCAmelCase     (    self			:    Any   )     ->				List[Any]:


														"""simple docstring"""


														_a      	=							XLMModelTester(self   )
														_a      	=							ConfigTester(self				,     config_class=lowerCAmelCase_				,     emb_dim=37   )







							def   __lowerCAmelCase     (    self			:    Optional[int]   )     ->				str:


														"""simple docstring"""


														self.config_tester.run_common_tests()







							def   __lowerCAmelCase     (    self			:    List[Any]   )     ->				List[Any]:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_model(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Optional[int]   )     ->				List[str]:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_lm_head(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Optional[Any]   )     ->				List[Any]:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_simple_qa(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Dict   )     ->				Optional[int]:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_qa(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Union[str, Any]   )     ->				int:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_sequence_classif(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    List[str]   )     ->				List[str]:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_token_classif(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    List[Any]   )     ->				int:


														"""simple docstring"""


														_a      	=							self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Any				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    int				,     lowerCAmelCase_			:    Union[str, Any]				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    str=False				,     lowerCAmelCase_			:    str=1   )     ->				int:


														"""simple docstring"""


														self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )
														self.assertListEqual(
														    [isinstance(lowerCAmelCase_				,     lowerCAmelCase_   ) for iter_attentions in attentions]				,     [True] * len(lowerCAmelCase_   )   )
														self.assertEqual(len(lowerCAmelCase_   )				,     (max_length - min_length) * num_beam_groups   )

														for idx, iter_attentions in enumerate(lowerCAmelCase_   ):
																					# adds PAD dummy token
																					_a      	=							min_length + idx + 1
																					_a      	=							min_length + idx + 1

																					_a      	=							(
																					    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(lowerCAmelCase_   )   )







							def   __lowerCAmelCase     (    self			:    str				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    Tuple				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Any				,     lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    int=False				,     lowerCAmelCase_			:    List[str]=1   )     ->				Optional[Any]:


														"""simple docstring"""


														self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )
														self.assertListEqual(
														    [isinstance(lowerCAmelCase_				,     lowerCAmelCase_   ) for iter_hidden_states in hidden_states]				,     [True] * len(lowerCAmelCase_   )				,     )
														self.assertEqual(len(lowerCAmelCase_   )				,     (max_length - min_length) * num_beam_groups   )

														for idx, iter_hidden_states in enumerate(lowerCAmelCase_   ):
																					# adds PAD dummy token
																					_a      	=							min_length + idx + 1
																					_a      	=							(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(lowerCAmelCase_   )				,     )
														pass







							@slow
							def   __lowerCAmelCase     (    self			:    Optional[Any]   )     ->				List[Any]:


														"""simple docstring"""


														for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_a      	=							XLMModel.from_pretrained(lowerCAmelCase_   )
																					self.assertIsNotNone(lowerCAmelCase_   )



@require_torch
class      A       (						unittest.TestCase       ):







							@slow
							def   __lowerCAmelCase     (    self			:    int   )     ->				Optional[int]:


														"""simple docstring"""


														_a      	=							XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048'''   )
														model.to(lowerCAmelCase_   )
														_a      	=							torch.tensor([[14, 4_47]]				,     dtype=torch.long				,     device=lowerCAmelCase_   )  # the president
														_a      	=							[
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														    14,
														    4_47,
														]  # 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
														_a      	=							model.generate(lowerCAmelCase_				,     do_sample=lowerCAmelCase_   )
														self.assertListEqual(output_ids[0].cpu().numpy().tolist()				,     lowerCAmelCase_   )







'''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,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_snake_case : Dict  				=						logging.get_logger(__name__)

class      A       (						_a       ):
							lowercase_							     =							['pixel_values']







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


														"""simple docstring"""


														super().__init__(**lowerCAmelCase_   )
														_a      	=							size if size is not None else {'''height''': 2_24, '''width''': 2_24}
														_a      	=							get_size_dict(lowerCAmelCase_   )
														_a      	=							crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
														_a      	=							get_size_dict(lowerCAmelCase_				,     default_to_square=lowerCAmelCase_				,     param_name='''crop_size'''   )

														_a      	=							do_resize
														_a      	=							do_rescale
														_a      	=							do_normalize
														_a      	=							do_center_crop
														_a      	=							crop_size
														_a      	=							size
														_a      	=							resample
														_a      	=							rescale_factor
														_a      	=							image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
														_a      	=							image_std if image_std is not None else IMAGENET_DEFAULT_STD







							def   __lowerCAmelCase     (    self			:    Optional[int]				,     lowerCAmelCase_			:    np.ndarray				,     lowerCAmelCase_			:    Dict[str, int]				,     lowerCAmelCase_			:    PILImageResampling = PILImageResampling.BILINEAR				,     lowerCAmelCase_			:    Optional[Union[str, ChannelDimension]] = None				,     **lowerCAmelCase_			:    int				,     )     ->				np.ndarray:


														"""simple docstring"""


														_a      	=							get_size_dict(lowerCAmelCase_   )

														if "shortest_edge" in size:
																					_a      	=							get_resize_output_image_size(lowerCAmelCase_				,     size=size['''shortest_edge''']				,     default_to_square=lowerCAmelCase_   )
																					# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
														elif "height" in size and "width" in size:
																					_a      	=							(size['''height'''], size['''width'''])
														else:
																					raise ValueError(F'Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'   )
														return resize(lowerCAmelCase_				,     size=lowerCAmelCase_				,     resample=lowerCAmelCase_				,     data_format=lowerCAmelCase_				,     **lowerCAmelCase_   )







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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

														_a      	=							size if size is not None else self.size
														_a      	=							get_size_dict(lowerCAmelCase_   )

														if not is_batched(lowerCAmelCase_   ):
																					_a      	=							[images]

														if not valid_images(lowerCAmelCase_   ):
																					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.'''   )

														# All transformations expect numpy arrays.
														_a      	=							[to_numpy_array(lowerCAmelCase_   ) for image in images]

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

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

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

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

														_a      	=							[to_channel_dimension_format(lowerCAmelCase_				,     lowerCAmelCase_   ) for image in images]

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

